Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61use crate::worktree_setup;
62
63/// Bytes of a failing command's output kept in an event, so the reason a run
64/// stopped is readable from the report without opening `run.json`.
65const EVENT_OUTPUT_TAIL: usize = 2_000;
66
67/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
68/// command's pid before releasing the build cache's lease.
69const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
70
71/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
72/// command's pid to actually exit before giving up and releasing anyway.
73///
74/// A timeout means the process was asked to die (`kill_on_drop`,
75/// `start_kill`), not that it already has — on Windows in particular that can
76/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
77/// the instant the command returns would let the very next acquirer (this
78/// run's own next round, another run's verification, the janitor's prune)
79/// start touching the same directory while it might still be writing to it,
80/// so this polls the actual pid — real confirmation, not a fixed guess —
81/// until it is gone or this ceiling is reached. It is still not full
82/// process-tree reaping: a grandchild the timed-out process spawned and that
83/// outlives it independently is invisible to a pid check, and continuing to
84/// observe and collect *that* stays a different piece of work with its own
85/// owner. Set generously because the common case returns early the moment
86/// the pid is confirmed gone, not because every timeout pays this in full.
87const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
88
89/// Consecutive review rounds with no tree progress (see
90/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
91/// instead of spending the rest of the round budget.
92///
93/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
94/// legitimately finds nothing left to change (its previous round's fix already
95/// covered it, and this round's reviewers re-raised only nits) looks the same
96/// as one that is spinning, for exactly one round. Two in a row is where the
97/// two stop being distinguishable, and a review round on this workload has
98/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
99/// third attempt at a tree that has not moved twice running is pure cost.
100/// This does not touch `review_rounds` itself, which stays the operator's
101/// call.
102pub(crate) const STAGNANT_LIMIT: usize = 2;
103
104/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
105/// a base that moved before giving up and leaving the run `Blocked` for a
106/// person.
107///
108/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
109/// that keeps moving faster than a run can catch it is not something more
110/// rebasing fixes, it is a person's call. Not the same *number as*
111/// `land_rounds` - this budget is spent before a pull request exists, land's
112/// after - but bounded for the identical reason, so it uses the same
113/// default. Counted across both call sites in [`Runner::finish_after_tally`]
114/// (once before review, once before the gate), because either one finding
115/// the base still moving is the same signal.
116pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
117
118/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
119/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
120/// reply held no [`FixReport`].
121///
122/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
123/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
124/// "I'll pause here until the `cargo make check` background run reports
125/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
126/// No `FixReport` was ever collected from that seat, and the run moved on to
127/// the next review round regardless.
128///
129/// Bounded independently of `review_rounds` and `graph.retries`: this
130/// recovers one seat's missing report mid-round, not a new round of review or
131/// an ordinary parse retry, and must not itself become the unbounded wait the
132/// rest of this module exists to avoid.
133const MAX_FIX_CONTINUATIONS: usize = 2;
134
135/// One queued agent invocation.
136///
137/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
138/// CLI hung up on its own stream is asked again from the same job rather than
139/// rebuilt from scratch. See [`Runner::resume_undelivered`].
140#[derive(Clone)]
141struct SeatJob {
142    spec: AgentSpec,
143    seat: SeatState,
144    cwd: PathBuf,
145    prompt: String,
146    timeout: Duration,
147    allow_write: bool,
148    sessions: bool,
149    artifacts: PathBuf,
150    stem: String,
151    /// The prompt for a seat that has been handed to another roster agent
152    /// (a fresh session): everything the original seat would have
153    /// remembered. `None` when `prompt` already carries it, as the first
154    /// ranking and the implement prompt do. Never a resume-style prompt.
155    handover: Option<String>,
156}
157
158/// How the graph reads one agent invocation.
159///
160/// Quota is split out from an ordinary failure on purpose: a rate-limited call
161/// is known to fail again if retried now, so the retry loop must not spend an
162/// attempt on it. `Dropped` is split out for the opposite reason: unlike
163/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
164/// error JSON, never the agent's answer — a caller that matched only
165/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
166/// left to read that JSON as if it were usable output. `resume_undelivered`
167/// is the only caller that acts on it; everywhere else it is reported like an
168/// ordinary failure.
169enum AgentOutcome {
170    /// A usable output.
171    Ok(AgentOutput),
172    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
173    Quota(AgentOutput),
174    /// The CLI hung up on its own stream after billed work. See
175    /// [`agent::AgentOutput::work_undelivered`].
176    Dropped(AgentOutput),
177    /// Any other failure: a timeout, a bad exit code, an empty reply.
178    Failed(String),
179    /// A resource prevented admission or interrupted execution. Not an agent
180    /// failure: never advance a fallback chain or spend an attempt on it.
181    /// Post-spawn interruptions carry a typed error into wave, which records
182    /// implementation preservation before returning this outcome. This outcome
183    /// alone is not proof that no source changes were made.
184    /// [`RunState::resource_block`] says why.
185    ResourceBlocked(String),
186}
187
188/// A request to park the run at its next node boundary.
189///
190/// Cloning is how the request travels: the loop keeps one handle and hands a
191/// clone to each [`Runner`], and every clone points at the same flag. There
192/// is no channel because there is nothing to send - the only message is
193/// "park", it is idempotent, and a flag cannot be missed by a receiver that
194/// was not listening yet.
195///
196/// The boundary is what makes this cheap. Every node writes the run's state
197/// before the next one starts, and every node skips what is already recorded:
198/// `prep` returns early once candidates exist, `implement` asks only the seats
199/// with nothing on disk, `judge` returns early once judgements exist. So a
200/// parked run resumes into exactly the node it stopped before, and no agent
201/// work is thrown away. Killing the process mid-node, by contrast, loses
202/// whatever the seats in flight had not yet written - which for an implement
203/// wave is an hour of paid work.
204///
205/// A [`Runner`] watches two independent handles of this type - see
206/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
207/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
208/// clone covering the whole daemon's lifetime and is never asked to un-park,
209/// which is correct exactly because nothing is dispatched after it fires.
210/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
211/// that parks for an interrupted task must go on to run other tasks
212/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
213/// reusing the daemon-wide one.
214#[derive(Debug, Clone, Default)]
215pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
216
217impl Pause {
218    /// A pause nobody has asked for yet.
219    #[must_use]
220    pub fn new() -> Self {
221        Self::default()
222    }
223
224    /// Ask the run to park at its next node boundary. Idempotent.
225    pub fn park(&self) {
226        self.0.store(true, Ordering::SeqCst);
227    }
228
229    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
230    /// fold into the run's own `park` event - so an operator reading the run
231    /// later knows this was a deliberate interrupt rather than a shutdown or
232    /// a binary swap. The first reason recorded wins; a park already in
233    /// flight is not relabelled by a second, unrelated request.
234    pub fn park_because(&self, reason: impl Into<String>) {
235        self.park_for(ParkCause::Interrupt {
236            reason: reason.into(),
237        });
238    }
239
240    /// [`Pause::park`], recording the structured cause. The first cause
241    /// recorded wins, like [`Pause::park_because`].
242    pub fn park_for(&self, cause: ParkCause) {
243        let mut reason_guard = self
244            .1
245            .lock()
246            .unwrap_or_else(std::sync::PoisonError::into_inner);
247        if reason_guard.is_none() {
248            *reason_guard = Some(cause);
249        }
250        drop(reason_guard);
251        self.park();
252    }
253
254    /// Has a park been asked for?
255    #[must_use]
256    pub fn parked(&self) -> bool {
257        self.0.load(Ordering::SeqCst)
258    }
259
260    /// Why the park was asked for, when the caller used [`Pause::park_because`].
261    #[must_use]
262    pub fn reason(&self) -> Option<String> {
263        self.cause().map(|c| c.label())
264    }
265
266    /// The structured cause, when one was recorded.
267    #[must_use]
268    pub fn cause(&self) -> Option<ParkCause> {
269        self.1
270            .lock()
271            .unwrap_or_else(std::sync::PoisonError::into_inner)
272            .clone()
273    }
274}
275
276/// Drives one run.
277pub struct Runner {
278    /// Run state; public so the CLI can report on it.
279    pub state: RunState,
280    roles: ResolvedRoles,
281    sem: Arc<Semaphore>,
282    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
283    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
284    /// this is never the same handle as `interrupt`.
285    pause: Pause,
286    /// Set when `magi serve`'s interrupt scheduler wants this specific run
287    /// parked at its next node boundary, to let a task marked
288    /// [`crate::queue::Task::interrupt`] run alone before this one carries
289    /// on. Unlike `pause`, a fresh, unshared handle per run - see
290    /// [`Runner::watch_interrupt`].
291    interrupt: Pause,
292}
293
294/// Where the branch's own commits start: its merge base with the base branch
295/// as the remote has it now, else with the recorded `base_commit`. A branch
296/// rebased onto a base that moved past `base_commit` would otherwise count
297/// the base's commits as its own under `base_commit..branch`.
298async fn review_base(
299    repo: &Path,
300    remote: &str,
301    base_branch: &str,
302    base_commit: &str,
303    branch: &str,
304) -> String {
305    review_base_checked(repo, remote, base_branch, base_commit, branch)
306        .await
307        .0
308}
309
310/// [`review_base`] plus whether the base was read from a freshly fetched
311/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
312/// never older than `base_commit`'s view of the base), but the answer is then
313/// not trusted to rewrite a pull request's title.
314async fn review_base_checked(
315    repo: &Path,
316    remote: &str,
317    base_branch: &str,
318    base_commit: &str,
319    branch: &str,
320) -> (String, bool) {
321    let tracking = format!("{remote}/{base_branch}");
322    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
323    if git::rev_exists(repo, &tracking).await
324        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
325        && !mb.is_empty()
326    {
327        return (mb, fresh);
328    }
329    let mb = git::merge_base(repo, base_commit, branch)
330        .await
331        .ok()
332        .filter(|mb| !mb.is_empty())
333        .unwrap_or_else(|| base_commit.to_owned());
334    (mb, false)
335}
336
337/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
338/// when git cannot say or finds nothing: a stale list is better than a wrong
339/// or empty one.
340pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
341    if !is_review_run(state) {
342        return;
343    }
344    let base = review_base(
345        &state.repo,
346        &state.config.merge.remote,
347        &state.base_branch,
348        &state.base_commit,
349        branch,
350    )
351    .await;
352    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
353        && !subjects.is_empty()
354        && state.reviewed_commits.as_ref() != Some(&subjects)
355    {
356        state.reviewed_commits = Some(subjects);
357        state.save().ok();
358    }
359}
360
361/// Subjects of the base's commits between the recorded start and the branch's
362/// merge base: what a stale `base_commit..branch` would have mistaken for the
363/// branch's own work.
364async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
365    let (base, trusted) = review_base_checked(
366        &state.repo,
367        &state.config.merge.remote,
368        &state.base_branch,
369        &state.base_commit,
370        branch,
371    )
372    .await;
373    if !trusted {
374        return None;
375    }
376    git::subjects(&state.repo, &state.base_commit, &base)
377        .await
378        .ok()
379}
380
381/// May an adopted pull request's title be replaced with `computed`? Only when
382/// it is empty, magi's own shape, or a base commit's subject that leaked in;
383/// a title a person wrote stays. Never when `computed` is itself a leak.
384pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
385    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
386    if is_leak(computed) {
387        return false;
388    }
389    let cur = current.trim();
390    cur.is_empty()
391        || cur.starts_with(REVIEW_PROMPT_OPENING)
392        || cur.starts_with("chore: land candidate")
393        || cur.starts_with("magi: candidate")
394        || is_leak(cur)
395}
396
397/// The commit a run branches from: the base branch as the remote has it.
398///
399/// Two failures this replaces. A run used to branch off `HEAD` and so refused
400/// to start on a dirty tree, which made `magi serve` decline every task for as
401/// long as the operator had work in progress - most of the time. Branching off
402/// the *local* base branch fixed that and introduced a worse one: `land` merges
403/// the winner on GitHub, nothing updates the local ref, and the next run
404/// branches off a base missing everything the previous runs landed. Two tasks
405/// in a row from a phone would have had the second silently re-implementing
406/// against stale code and opening a pull request that reverted the first.
407///
408/// Only refs move here - no checkout, no local branch, no merge - so it is safe
409/// with uncommitted work in the tree. A machine with no network still starts:
410/// the fetch may fail and the local tip is used with a warning, because
411/// refusing to run offline is a worse failure than running against a base the
412/// operator can see for themselves.
413///
414/// One function, called by both entry points. Two answers to "where does a run
415/// branch from" is the kind of drift nobody notices until a diff is wrong.
416/// Bring the local `branch` in line with `<remote>/<branch>` before a review
417/// checks it out.
418///
419/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
420/// anything other than plain `git push` from this checkout (a jj colocated
421/// workspace, another clone) moves only the remote-tracking ref - so the local
422/// one can be a stale placeholder. It moves only when local is behind the remote or is an
423/// empty placeholder that diverged from it; unpushed local work is kept, and a real
424/// divergence is refused rather than guessed at.
425async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
426    let tracking = format!("{remote}/{branch}");
427    let fetched = git::fetch(repo, remote, branch).await;
428    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
429    let local_exists = git::branch_exists(repo, branch).await?;
430    if !fresh {
431        if !local_exists {
432            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
433        }
434        tracing::warn!(
435            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
436        );
437        return Ok(());
438    }
439    let remote_sha = git::rev_parse(repo, &tracking).await?;
440    if !local_exists {
441        git::git(repo, &["branch", branch, &tracking]).await?;
442        return Ok(());
443    }
444    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
445    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
446        return Ok(());
447    }
448    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
449        // Diverged. `reconcile` settles it only when it can prove nothing is
450        // lost: a local tip that is the remote's change rebased is pushed over
451        // it (lease pinned to the tip read here), a tip whose every extra
452        // commit is empty is a placeholder the remote's work replaced, and
453        // anything else is two different changes - a question for a person.
454        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
455            .await?
456        {
457            crate::reconcile::Reconciliation::Pushed => {
458                tracing::warn!(
459                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
460                    short(&local_sha),
461                    short(&remote_sha)
462                );
463                return Ok(());
464            }
465            crate::reconcile::Reconciliation::Placeholder => {}
466            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
467        }
468    }
469    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
470    if !out.ok() {
471        bail!(
472            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
473            short(&local_sha),
474            short(&remote_sha),
475            out.stderr
476        );
477    }
478    tracing::warn!(
479        "local `{branch}` was stale: fast-forwarded {} -> {}",
480        short(&local_sha),
481        short(&remote_sha)
482    );
483    Ok(())
484}
485
486async fn resolve_base(
487    repo: &Path,
488    base_branch: &str,
489    remote: &str,
490    coordination: Option<&crate::config::Coordination>,
491) -> Result<crate::run::FetchedBase> {
492    let _lease = crate::repo_lock::SeatLease::operation_with(
493        repo,
494        coordination,
495        &crate::repo_lock::WaitPolicy::current(),
496    )
497    .await?;
498    let tracking = format!("{remote}/{base_branch}");
499    let fetched = git::fetch(repo, remote, base_branch).await;
500    if let Ok(out) = &fetched
501        && out.ok()
502        && git::rev_exists(repo, &tracking).await
503    {
504        return Ok(crate::run::FetchedBase {
505            remote: remote.to_owned(),
506            branch: base_branch.to_owned(),
507            commit: git::rev_parse(repo, &tracking).await?,
508            fetched_at: jiff::Timestamp::now(),
509        });
510    }
511    let why = match &fetched {
512        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
513        Ok(_) => format!("{remote} has no {base_branch}"),
514        Err(e) => e.to_string(),
515    };
516    // No fallback to the local branch: it may be behind, and branching off an
517    // old commit is the stale-checkout bug this check exists to prevent.
518    bail!(
519        "cannot read {tracking} ({why}); refusing to branch off the local \
520         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
521         base / remote in magi.toml. This is launcher preparation: check the \
522         launcher's network, Git access and repository coordination before \
523         retrying"
524    )
525}
526
527/// Outcome of the shared fixer chain, before caller-owned stop policy.
528enum FixStep {
529    Resource,
530    Recorded { report_lost: bool },
531}
532
533/// Exclusive claim shared by targeted repairs and repository reassignment.
534/// Held before asynchronous fix preflight and released on every return or panic.
535///
536/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
537/// manual `magi fix` invocations against the same run are otherwise
538/// invisible to each other and would race to remove and recreate the same
539/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
540/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
541/// which is only ever reclaimed later, out of band, by
542/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
543/// `magi fix` invocation is not necessarily running under either of those, so
544/// nothing would ever sweep a lock a killed or crashed process left behind.
545/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
546/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
547/// lease use: an unreadable or unparsable pid, or a liveness query the
548/// platform cannot answer, reads as alive and the lock is left in place.
549pub(crate) struct FixClaim {
550    path: PathBuf,
551}
552
553impl FixClaim {
554    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
555        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
556        let path = dir.join("fix.lock");
557        let retry = crate::lock_file::Retry::new(None);
558        match Self::create(&path, retry) {
559            Ok(claim) => Ok(claim),
560            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
561                if Self::reclaim_if_dead(&path) {
562                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
563                } else {
564                    bail!(
565                        "another repair or `magi fix` is already running for this run ({} exists)",
566                        path.display()
567                    )
568                }
569            }
570            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
571        }
572    }
573
574    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
575        let mut f = retry.create(path)?;
576        use std::io::Write as _;
577        // Read back by `reclaim_if_dead` on a later, stuck invocation.
578        writeln!(f, "{}", std::process::id())?;
579        Ok(Self {
580            path: path.to_owned(),
581        })
582    }
583
584    /// True if the lock named a process confirmed dead, in which case it was
585    /// also removed. Never true on an unreadable file, an unparsable pid, or
586    /// a liveness query the platform cannot answer — see this type's own doc.
587    fn reclaim_if_dead(path: &Path) -> bool {
588        let dead = std::fs::read_to_string(path)
589            .ok()
590            .and_then(|body| body.trim().parse::<u32>().ok())
591            .is_some_and(|pid| !crate::proc::pid_alive(pid));
592        dead && std::fs::remove_file(path).is_ok()
593    }
594}
595
596impl Drop for FixClaim {
597    fn drop(&mut self) {
598        let _ = std::fs::remove_file(&self.path);
599    }
600}
601
602#[doc(hidden)]
603pub struct ExecutionLeaseGuard {
604    _lease: crate::driver::ExecutionLease,
605}
606
607#[doc(hidden)]
608pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
609    Ok(ExecutionLeaseGuard {
610        _lease: crate::driver::maintenance(home, run_id)?,
611    })
612}
613
614/// Holds the mutable runner as well as its durable lease: cancellation must
615/// clear both copies of ownership, including state a caller may save later.
616struct DriverExecution<'a> {
617    runner: &'a mut Runner,
618    driver: crate::driver::DriverGuard,
619}
620
621impl Drop for DriverExecution<'_> {
622    fn drop(&mut self) {
623        self.driver.release_local(&mut self.runner.state);
624    }
625}
626
627fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
628    if let Some(startup) = &mut state.startup {
629        startup.stage = stage.to_owned();
630    }
631    state.save()
632}
633
634/// Keep a reservation visible as blocked until startup finishes. A killed process
635/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
636struct StartupGuard {
637    id: String,
638    armed: bool,
639}
640
641impl StartupGuard {
642    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
643        state.startup = Some(crate::run::Startup {
644            kind: kind.to_owned(),
645            branch: branch.map(str::to_owned),
646            stage: "reserved".to_owned(),
647            complete: false,
648            failure: None,
649        });
650        state.status = RunStatus::Blocked;
651        state.reserve()?;
652        Ok(Self {
653            id: state.id.clone(),
654            armed: true,
655        })
656    }
657
658    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
659        startup_stage(state, stage)
660    }
661
662    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
663        let result = result.and_then(|()| {
664            state.startup.as_mut().expect("reserved startup").complete = true;
665            state.save()
666        });
667        self.armed = false;
668        match result {
669            Ok(()) => Ok(()),
670            Err(error) => {
671                let startup = state.startup.as_mut().expect("reserved startup");
672                startup.complete = false;
673                startup.failure = Some(format!("{error:#}"));
674                let context = crate::run::StartupFailure {
675                    run: state.id.clone(),
676                    stage: startup.stage.clone(),
677                };
678                // Repository assets may remain. Never infer that a failed startup
679                // is safe to resume or that an earlier owner has been restored.
680                state.status = RunStatus::Failed;
681                state.driver_exited = true;
682                state.event(
683                    "startup-failed",
684                    format!("{context}: {error:#}; retained assets require inspection"),
685                );
686                if let Err(save) = state.save() {
687                    tracing::warn!(
688                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
689                        state.id
690                    );
691                }
692                Err(error.context(context))
693            }
694        }
695    }
696}
697
698impl Drop for StartupGuard {
699    fn drop(&mut self) {
700        if self.armed
701            && let Ok(mut state) = RunState::load(&self.id)
702        {
703            state.status = RunStatus::Blocked;
704            state.driver_exited = true;
705            if let Some(startup) = &mut state.startup {
706                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
707            }
708            state.event(
709                "startup-interrupted",
710                "startup did not finish; inspect retained assets before recovery",
711            );
712            if let Err(error) = state.save() {
713                tracing::error!(
714                    "could not record interrupted startup {}: {error:#}",
715                    self.id
716                );
717            }
718        }
719    }
720}
721
722impl Runner {
723    /// A queue-side failure after construction must not strand an unexecuted run.
724    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
725        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
726            return error;
727        }
728        if let Some(startup) = &mut self.state.startup {
729            startup.stage = stage.to_owned();
730        } else {
731            // A resumed run already has execution history: do not rewrite it.
732            return error;
733        }
734        StartupGuard {
735            id: self.state.id.clone(),
736            armed: true,
737        }
738        .finish(&mut self.state, Err(error))
739        .expect_err("startup failed")
740    }
741
742    /// Start a fresh run against `repo`.
743    pub async fn start(
744        repo: &Path,
745        instruction: String,
746        config: Config,
747        origin: Origin,
748    ) -> Result<Self> {
749        Self::start_naming(repo, instruction, "", config, origin).await
750    }
751
752    /// [`Runner::start`] for a queued task. Titles and instructions never
753    /// select implementation sources. The title argument is retained for callers.
754    pub async fn start_naming(
755        repo: &Path,
756        instruction: String,
757        _also_scan: &str,
758        config: Config,
759        origin: Origin,
760    ) -> Result<Self> {
761        let repo = git::toplevel(repo).await?;
762        let missing = agent::missing_programs(&config.agents);
763        if !missing.is_empty() {
764            bail!(
765                "these agent programs are not on PATH: {}. Fix the roster in \
766                 magi.toml or install them.",
767                missing.join(", ")
768            );
769        }
770        let base_branch =
771            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
772                .await?;
773        let fetched_base = resolve_base(
774            &repo,
775            &base_branch,
776            &config.merge.remote,
777            config.coordination.as_ref(),
778        )
779        .await?;
780        let base_commit = fetched_base.commit.clone();
781        let roles = config.resolve_roles()?;
782        let max_parallel = config.graph.max_parallel.max(1);
783        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
784        // Capture task identity and repository assignment before the first
785        // save, so publication scope survives crashes and later task moves.
786        state.fetched_base = Some(fetched_base);
787        state.set_origin(origin)?;
788        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
789        state.status = RunStatus::Prep;
790        state.event("start", format!("run {} created", state.id));
791        startup.finish(&mut state, Ok(()))?;
792        Ok(Self {
793            state,
794            roles,
795            sem: Arc::new(Semaphore::new(max_parallel)),
796            pause: Pause::new(),
797            interrupt: Pause::new(),
798        })
799    }
800
801    /// Open a review-only run against work that already exists on `branch`.
802    ///
803    /// The expensive half of the graph is the implement wave — measured at
804    /// 111 and 134 internal tool-loop turns on this repository, against a
805    /// handful for a judge or a reviewer. The cheap half is worth running on
806    /// hand-written work too, and there was no way to reach it.
807    ///
808    /// No new state and no schema change are needed: a run with **one** viable
809    /// candidate and a tally already decided degrades `execute` to exactly
810    /// review → gate → merge, because `judge` skips a single-candidate field,
811    /// `deliberate` has fewer than two first choices to reconcile, `vote`
812    /// returns early, `tally` is already present and `fold_losers` has no
813    /// losers. Resuming such a run therefore does the right thing as well.
814    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
815        Self::review_taking_over(repo, branch, config, None, origin).await
816    }
817
818    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
819    /// at the same task still has `branch` checked out, its worktree is
820    /// released first if that is safe (see [`crate::handover`]), and the
821    /// review refuses with the reason if it is not. `None` is a hand-run
822    /// review: it has no earlier attempts, so only a worktree of a dead run
823    /// magi recorded itself can be released.
824    pub async fn review_taking_over(
825        repo: &Path,
826        branch: &str,
827        config: Config,
828        takeover: Option<crate::handover::Takeover>,
829        origin: Origin,
830    ) -> Result<Self> {
831        let repo = git::toplevel(repo).await?;
832        let missing = agent::missing_programs(&config.agents);
833        if !missing.is_empty() {
834            bail!(
835                "these agent programs are not on PATH: {}. Fix the roster in \
836                 magi.toml or install them.",
837                missing.join(", ")
838            );
839        }
840        let base_branch =
841            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
842                .await?;
843        if base_branch == branch {
844            bail!("`{branch}` is the base branch; there is nothing to review against");
845        }
846        let fetched_base = resolve_base(
847            &repo,
848            &base_branch,
849            &config.merge.remote,
850            config.coordination.as_ref(),
851        )
852        .await?;
853        let base_commit = fetched_base.commit.clone();
854
855        let roles = config.resolve_roles()?;
856        let max_parallel = config.graph.max_parallel.max(1);
857        let mut state = RunState::new(
858            repo.clone(),
859            base_branch,
860            base_commit.clone(),
861            format!("Review the work already on branch `{branch}`."),
862            config,
863        );
864        state.fetched_base = Some(fetched_base);
865        state.set_origin(origin)?;
866        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
867        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
868        let opened = async {
869            startup.stage(&mut state, "handover")?;
870
871            // Released before anything else touches the branch: a stale local
872            // branch is moved with `git branch -f`, which git refuses while an
873            // earlier attempt's worktree still has it checked out. Everything
874            // after this point that can fail puts the old run back.
875            // A hand-run review has no task, hence no earlier attempts, but a
876            // worktree of a dead run magi made may still be released.
877            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
878                earlier: Vec::new(),
879                home: crate::run::home(),
880                choice: None,
881                task_instruction: None,
882            });
883            let wait = repository_wait(&state, None);
884            let coordination_config = state.config.coordination.clone();
885            let coordination =
886                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
887                    .await?;
888            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
889            if let Some(released) = &released {
890                state.event(
891                    "release",
892                    format!(
893                        "took `{branch}` over from run {}: its worktree was released: {}",
894                        crate::run::short_of(&released.old_id),
895                        released.audit
896                    ),
897                );
898            }
899            let opened = async {
900                startup.stage(&mut state, "review-preflight")?;
901                // The owner's answer to an earlier divergence question is applied
902                // here: after the release (git will not move a checked-out branch)
903                // and before the sync that would otherwise ask again.
904                state.foreign_checkout = crate::handover::preflight_review(
905                    &repo,
906                    branch,
907                    &takeover.home,
908                    &state.config.merge.remote,
909                )
910                .await?;
911                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
912                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
913                }
914                if let Some(choice) = takeover.choice.as_ref()
915                    && let Err(e) =
916                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
917                            .await
918                {
919                    return Err(e.context("applying the owner's answer about the diverged branch"));
920                }
921                // An earlier attempt of this task that published the task head, and
922                // whose work is the branch under review, hands that head over: the
923                // review run updates the same pull request. Without one (a legacy
924                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
925                // own head and its own open pull request is adopted as before.
926                for id in takeover.earlier.iter().rev() {
927                    if let Ok(old) = RunState::load_under(id, &takeover.home)
928                        && let Some(head) = old.pr_head.clone()
929                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
930                    {
931                        state.pr_head = Some(head);
932                        break;
933                    }
934                }
935                drop(coordination);
936                startup.stage(&mut state, "open-review")?;
937                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
938            }
939            .await;
940            if opened.is_err()
941                && let Some(released) = &released
942            {
943                // Restoration is ownership checked and best effort. Keep the original
944                // startup cause even if reacquiring coordination is no longer possible.
945                match crate::repo_lock::SeatLease::operation_with(
946                    &repo,
947                    coordination_config.as_ref(),
948                    &wait,
949                )
950                .await
951                {
952                    Ok(_coordination) => {
953                        released.restore(&repo, branch).await;
954                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
955                            .map(|old| {
956                                format!(
957                                    "predecessor released_to={:?}; candidate path exists={}",
958                                    old.released_to,
959                                    old.candidates.iter().any(|c| {
960                                        c.branch == branch && c.worktree.exists()
961                                    }),
962                                )
963                            })
964                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
965                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
966                    }
967                    Err(error) => {
968                        tracing::warn!(
969                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
970                            state.id
971                        );
972                        state.event(
973                            "startup-restore",
974                            format!("restoration not attempted: {error:#}"),
975                        );
976                    }
977                }
978            }
979            opened
980        }
981        .await;
982        startup.finish(&mut state, opened)?;
983        Ok(Self {
984            state,
985            roles,
986            sem: Arc::new(Semaphore::new(max_parallel)),
987            pause: Pause::new(),
988            interrupt: Pause::new(),
989        })
990    }
991
992    /// Recover exactly the operator-selected public implementation, without touching old sources.
993    pub async fn recover_pr(
994        repo: &Path,
995        task: &str,
996        selection: crate::pr_recovery::Selection,
997        mut config: Config,
998    ) -> Result<Self> {
999        selection.configure(&mut config)?;
1000        let assignment = crate::run::task_assignment_for(task)?;
1001        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1002        let base_branch =
1003            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1004                .await?;
1005        let fetched_base = resolve_base(
1006            repo,
1007            &base_branch,
1008            &config.merge.remote,
1009            config.coordination.as_ref(),
1010        )
1011        .await?;
1012        let base_commit = fetched_base.commit.clone();
1013        selection
1014            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1015            .await?;
1016        Box::pin(selection.verify_source(repo)).await?;
1017        if let Some(proof) = &selection.source_proof {
1018            anyhow::ensure!(
1019                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1020                "source rebase base is outside the fetched landing base"
1021            );
1022        }
1023        let roles = config.resolve_roles()?;
1024        let max_parallel = config.graph.max_parallel.max(1);
1025        let mut state = RunState::new(
1026            repo.to_path_buf(),
1027            base_branch,
1028            base_commit.clone(),
1029            selection.instruction.clone(),
1030            config,
1031        );
1032        state.fetched_base = Some(fetched_base);
1033        state.set_origin(crate::run::Origin::queue(task))?;
1034        state.pr_head = Some(selection.branch.clone());
1035        state.pr_recovery = Some(selection.clone());
1036        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1037    }
1038
1039    async fn open_selected(
1040        repo: &Path,
1041        mut state: RunState,
1042        roles: ResolvedRoles,
1043        max_parallel: usize,
1044        base_commit: String,
1045        selection: crate::pr_recovery::Selection,
1046    ) -> Result<Self> {
1047        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1048        let opened = async {
1049            startup.stage(&mut state, "predecessors")?;
1050            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1051            startup.stage(&mut state, "open-selected")?;
1052            let branch = state.branch_for('A');
1053            let wait = repository_wait(&state, None);
1054            let prepared = async {
1055                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1056                git::git(repo, &["branch", &branch, selection.source()]).await?;
1057                drop(coordination);
1058                anyhow::Ok(())
1059            }
1060            .await;
1061            prepared?;
1062            state.event(
1063                "recovery",
1064                format!(
1065                    "selected implementation {} for {} (public lease {})",
1066                    selection.source(),
1067                    selection.url,
1068                    selection.head
1069                ),
1070            );
1071            let takeover = crate::handover::Takeover {
1072                earlier: Vec::new(),
1073                home: crate::run::home(),
1074                choice: None,
1075                task_instruction: Some(selection.instruction.clone()),
1076            };
1077            state.save()?;
1078            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1079        }
1080        .await;
1081        startup.finish(&mut state, opened)?;
1082        Ok(Self {
1083            state,
1084            roles,
1085            sem: Arc::new(Semaphore::new(max_parallel)),
1086            pause: Pause::new(),
1087            interrupt: Pause::new(),
1088        })
1089    }
1090
1091    /// What the newest earlier attempt that reviewed `branch` leaves for this
1092    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1093    /// no earlier attempts. Reads the earlier record only: ownership of its
1094    /// worktree and branch is [`crate::handover`]'s business.
1095    async fn inherit(
1096        repo: &Path,
1097        branch: &str,
1098        base_commit: &str,
1099        takeover: &crate::handover::Takeover,
1100    ) -> Option<crate::recovery::RecoveryRecord> {
1101        use crate::recovery::{Relation, assess};
1102        let newest = takeover.earlier.last()?;
1103        let mut chosen = None;
1104        for id in takeover.earlier.iter().rev() {
1105            if let Ok(old) = RunState::load_under(id, &takeover.home)
1106                && !old.reviews.is_empty()
1107                && (old.winner().is_some_and(|w| w.branch == branch)
1108                    || old.pr_head.as_deref() == Some(branch))
1109            {
1110                chosen = Some(old);
1111                break;
1112            }
1113        }
1114        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1115            .await
1116            .unwrap_or_default();
1117        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1118            Some(last) if last.head == tip => Relation::Same,
1119            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1120            _ => Relation::Diverged,
1121        };
1122        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1123        Some(assess(from, chosen.as_ref(), base_commit, relation))
1124    }
1125
1126    /// The half of [`Runner::review_taking_over`] that can fail after an
1127    /// earlier attempt's worktree was released.
1128    async fn open_review(
1129        repo: &Path,
1130        branch: &str,
1131        state: &mut RunState,
1132        base_commit: String,
1133        takeover: &crate::handover::Takeover,
1134    ) -> Result<()> {
1135        startup_stage(state, "review-sync")?;
1136        let wait = repository_wait(state, None);
1137        let _coordination = coordinate_operation(state, repo, &wait).await?;
1138        if state.foreign_checkout.is_some() {
1139            // Never reconcile or force-move a ref checked out by the operator.
1140            if state.pr_head.is_none() {
1141                state.pr_head = Some(branch.to_owned());
1142            }
1143        } else if state.pr_recovery.is_none() {
1144            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1145        }
1146        // The commit subjects are the closest thing to a task statement that
1147        // existing work carries, and the reviewers are told as much.
1148        let start = review_base(
1149            repo,
1150            &state.config.merge.remote,
1151            &state.base_branch,
1152            &base_commit,
1153            branch,
1154        )
1155        .await;
1156        let log = git::log_oneline(repo, &start, branch)
1157            .await
1158            .unwrap_or_default();
1159        let log_text = if log.trim().is_empty() {
1160            "(no commit messages)"
1161        } else {
1162            log.trim()
1163        };
1164        let mut instruction = format!(
1165            "Review the work already on branch `{branch}`. There is no task \
1166             statement: what the change claims to do is whatever its commits \
1167             say.\n\n{log_text}"
1168        );
1169        // A retry of a task whose earlier attempt left reviews behind carries
1170        // that attempt's evidence, and the task's own statement with it: the
1171        // completion criteria are the task's, not whatever the commits claim.
1172        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1173            if let Some(task) = takeover
1174                .task_instruction
1175                .as_deref()
1176                .filter(|t| !t.trim().is_empty())
1177                && rec.reviewed_head.is_some()
1178            {
1179                instruction = format!(
1180                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1181                    task.trim()
1182                );
1183                rec.criteria_inherited = true;
1184            }
1185            state.event("recovery", rec.summary());
1186            state.recovery = Some(rec);
1187        }
1188        if let Some(selected) = &state.pr_recovery {
1189            instruction = selected.instruction.clone();
1190        }
1191        state.task_instruction = takeover.task_instruction.clone();
1192        state.instruction = instruction;
1193        state.reviewed_commits = Some(
1194            git::subjects(repo, &start, branch)
1195                .await
1196                .unwrap_or_default(),
1197        );
1198
1199        // A takeover must not forget a hold that a previous review observed,
1200        // even if repairs have since removed it from the branch.
1201        for id in &takeover.earlier {
1202            if let Ok(old) = RunState::load_under(id, &takeover.home)
1203                && old.repo == state.repo
1204                && (old.pr_head.as_deref() == Some(branch)
1205                    || old.winner().is_some_and(|w| w.branch == branch))
1206            {
1207                for hold in old.branch_owner_holds {
1208                    if !state.branch_owner_holds.contains(&hold) {
1209                        state.event(
1210                            "approval-policy",
1211                            format!(
1212                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1213                                hold.control.key(),
1214                                hold.file,
1215                                hold.head
1216                            ),
1217                        );
1218                        state.branch_owner_holds.push(hold);
1219                    }
1220                }
1221            }
1222        }
1223        // Select the actual review tip before observing owner policy. A foreign
1224        // checkout can lag its remote descendant, and repairs must not erase
1225        // holds introduced only on that selected commit.
1226        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1227            let tracking = format!("{}/{branch}", state.config.merge.remote);
1228            // A surviving tracking ref is not evidence that the remote still
1229            // offers this tip. Adopt it only after a successful fetch here.
1230            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1231            let mut head = checkout.synced_head.clone();
1232            if matches!(fetched, Ok(out) if out.ok()) {
1233                let remote = git::rev_parse(repo, &tracking).await?;
1234                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1235                    head = remote;
1236                }
1237            }
1238            head
1239        } else {
1240            git::rev_parse(repo, branch).await?
1241        };
1242        state.observe_branch_owner_holds(&reviewed_head).await;
1243
1244        // An attached worktree, so the fixer's commits land on the branch under
1245        // review rather than on a detached head nobody will look at again.
1246        let worktree = state.worktree_root().join("under-review");
1247        if let Some(parent) = worktree.parent() {
1248            tokio::fs::create_dir_all(parent).await.ok();
1249        }
1250        let path = worktree.to_string_lossy().to_string();
1251        let review_branch = if state.foreign_checkout.is_some() {
1252            let shadow = format!("magi/{}/review", state.short());
1253            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1254            shadow
1255        } else {
1256            branch.to_owned()
1257        };
1258        startup_stage(state, "review-checkout")?;
1259        git::git(repo, &["worktree", "add", &path, &review_branch])
1260            .await
1261            .with_context(|| {
1262                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1263            })?;
1264
1265        startup_stage(state, "worktree-setup")?;
1266        let setup = match ensure_setup_config(state, repo).await {
1267            Ok(()) => {
1268                worktree_setup::prepare_with(
1269                    &state.config,
1270                    repo,
1271                    &worktree,
1272                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1273                )
1274                .await
1275            }
1276            Err(e) => Err(e),
1277        };
1278        if let Err(e) = setup {
1279            git::worktree_remove_clean(repo, &worktree).await.ok();
1280            return Err(e);
1281        }
1282        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1283            .await
1284            .unwrap_or(0);
1285        if commits == 0 {
1286            git::worktree_remove_clean(repo, &worktree).await.ok();
1287            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1288        }
1289        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1290            .await
1291            .map(|f| f.len())
1292            .unwrap_or(0);
1293        if files == 0
1294            && let (Ok(head_tree), Ok(base_tree)) = (
1295                git::tree_of(&worktree, "HEAD").await,
1296                git::tree_of(&worktree, &base_commit).await,
1297            )
1298            && head_tree == base_tree
1299        {
1300            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1301            git::worktree_remove_clean(repo, &worktree).await.ok();
1302            bail!(
1303                "`{branch}` at {} has a tree identical to base {}; this usually means \
1304                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1305                 against `{}/{branch}`) rather than an empty change",
1306                short(&head),
1307                short(&base_commit),
1308                state.config.merge.remote
1309            );
1310        }
1311        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1312            .await
1313            .unwrap_or_default();
1314
1315        state.candidates.push(Candidate {
1316            index: 0,
1317            label: 'A',
1318            // Not an agent id on purpose: nothing in the roster wrote this, and
1319            // the stats tables must not credit anyone with a win for it.
1320            agent: EXISTING_BRANCH.to_owned(),
1321            branch: review_branch,
1322            worktree,
1323            summary: String::new(),
1324            stat,
1325            files,
1326            commits,
1327            empty: false,
1328            failed: None,
1329            verified_noop: None,
1330            duration_ms: 0,
1331            folded: false,
1332        });
1333        state.tally = Some(Tally {
1334            first_choice: BTreeMap::from([('A', 0)]),
1335            borda: BTreeMap::new(),
1336            winner: 'A',
1337            rankings: 0,
1338            unanimous_initial: false,
1339            deliberated: false,
1340            changed_votes: 0,
1341            unanimous_final: false,
1342            tie_break: None,
1343            // No panel sat, so no quorum applies. Zero judges is the correct
1344            // number for work that never competed, and must not be reported as
1345            // a collapsed panel.
1346            judges: 0,
1347            present: 0,
1348            quorum: 0,
1349            met_quorum: true,
1350            uncontested: Some("review-only run: nothing competed".to_owned()),
1351        });
1352        state.status = RunStatus::Reviewing;
1353        state.prep_complete = Some(true);
1354        state.event(
1355            "start",
1356            format!(
1357                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1358                state.id
1359            ),
1360        );
1361        Ok(())
1362    }
1363
1364    /// Authorize one bounded synchronization interval, under the caller's queue task
1365    /// claim and the same owner/execution locks used by run maintenance.
1366    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1367        Self::authorize_base_recovery_request(home, id, task, false, None).await
1368    }
1369
1370    /// Queue release uses its durable approval generation exactly once.
1371    pub(crate) async fn authorize_base_recovery_from_resumption(
1372        home: &Path,
1373        id: &str,
1374        task: &str,
1375    ) -> Result<()> {
1376        Self::authorize_base_recovery_request(home, id, task, true, None).await
1377    }
1378
1379    pub(crate) async fn authorize_base_recovery_control(
1380        home: &Path,
1381        task: &str,
1382        control: &mut crate::base_recovery_control::Transaction,
1383    ) -> Result<()> {
1384        let id = control.request.run.clone();
1385        Self::authorize_base_recovery_request(home, &id, task, false, Some(control)).await
1386    }
1387
1388    async fn authorize_base_recovery_request(
1389        home: &Path,
1390        id: &str,
1391        task: &str,
1392        resumption: bool,
1393        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1394    ) -> Result<()> {
1395        let _owner = crate::pr_head::owner_lock(home, id)?;
1396        let mut state = RunState::load_under(id, home)?;
1397        crate::pr_head::ensure_owner(&state)?;
1398        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1399        anyhow::ensure!(
1400            queued.execution_runs().last().is_some_and(|run| run == id)
1401                && queued.status != crate::queue::TaskStatus::Done
1402                && !queued.fresh_start
1403                && queued.review_branch.is_none(),
1404            "run task ownership changed"
1405        );
1406        anyhow::ensure!(
1407            state
1408                .origin
1409                .as_ref()
1410                .and_then(|o| o.task.as_deref())
1411                .is_none_or(|owner| owner == task),
1412            "run belongs to another task"
1413        );
1414        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1415        anyhow::ensure!(
1416            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1417            "run is live or its ownership is unknown"
1418        );
1419        // Judge the previous driver's lease before acquiring our maintenance
1420        // lease. The owner lock excludes new driver claims across both steps.
1421        let _execution = crate::driver::maintenance(home, id)?;
1422        anyhow::ensure!(
1423            state.status.resumable()
1424                && state.released_to.is_none()
1425                && state.retired_to.is_none()
1426                && state.pr_taken_over_by.is_none(),
1427            "run ownership is final"
1428        );
1429        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1430        anyhow::ensure!(
1431            !state.pr_publication_pending
1432                && !crate::handover::landing_checkpoint(&state)
1433                && state.merge_decision.is_none(),
1434            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1435        );
1436        let winner = state.winner().context("run has no retained winner")?;
1437        anyhow::ensure!(
1438            git::is_clean(&winner.worktree).await?,
1439            "retained worktree has uncommitted changes"
1440        );
1441        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1442        anyhow::ensure!(
1443            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1444            "retained worktree does not match the winner branch"
1445        );
1446        if let Some(control) = control.as_ref() {
1447            anyhow::ensure!(
1448                head.starts_with(&control.request.head),
1449                "retained HEAD changed since the owner request"
1450            );
1451            anyhow::ensure!(
1452                state
1453                    .base_sync_recovery
1454                    .stop
1455                    .as_ref()
1456                    .is_none_or(|stop| stop.head == head),
1457                "retained HEAD differs from the recorded stop head; inspect it first"
1458            );
1459        }
1460        state.ensure_base_episode();
1461        state.record_base_sync_stop(&head);
1462        anyhow::ensure!(
1463            state
1464                .base_sync_recovery
1465                .stop
1466                .as_ref()
1467                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1468            "base recovery refused: missing eligible movement-exhaustion evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1469        );
1470        let fetched =
1471            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1472        anyhow::ensure!(
1473            fetched.ok(),
1474            "cannot authorize base recovery without a fetched base"
1475        );
1476        let approved_tip = git::rev_parse(
1477            &state.repo,
1478            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1479        )
1480        .await?;
1481        if let Some(control) = control.as_deref_mut() {
1482            let queue = crate::queue::Queue::at(home.join("queue"));
1483            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1484            if let Some(prior) = state
1485                .base_sync_recovery
1486                .authorizations
1487                .iter()
1488                .find(|a| a.request.as_deref() == Some(&control.key()))
1489            {
1490                anyhow::ensure!(
1491                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1492                    "recovery request was consumed or invalidated; it cannot queue again"
1493                );
1494                return control.enqueue(&queue);
1495            }
1496        }
1497        if resumption {
1498            anyhow::ensure!(
1499                crate::daemon::compatible_run_instruction(&state, &queued),
1500                "resumption instruction does not match the retained run"
1501            );
1502            let approval = queued
1503                .resumption
1504                .as_ref()
1505                .context("no operator resumption")?;
1506            anyhow::ensure!(
1507                approval.instruction == queued.instruction,
1508                "resumption approval does not match the current task instruction"
1509            );
1510            state.authorize_base_sync_resumption(task, approval)?;
1511        } else {
1512            state.authorize_base_sync(task)?;
1513        }
1514        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1515        state
1516            .base_sync_recovery
1517            .authorizations
1518            .last_mut()
1519            .unwrap()
1520            .scope = Some(crate::base_sync_recovery::Scope {
1521            tip: approved_tip,
1522            instruction: queued.instruction.clone(),
1523            episode,
1524        });
1525        if let Some(control) = control.as_deref_mut() {
1526            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1527            authorization.request = Some(control.key());
1528            authorization.generation = control.generation();
1529            authorization.decision = control.decision();
1530            authorization.question = control
1531                .request
1532                .decision
1533                .as_ref()
1534                .map(|_| control.request.request.clone());
1535        }
1536        state.event(
1537            "base-recovery",
1538            "owner authorized a bounded base synchronization interval; fresh verification required",
1539        );
1540        state.save_under(home)?;
1541        if let Some(control) = control {
1542            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1543        }
1544        Ok(())
1545    }
1546
1547    /// Reopen an existing run.
1548    pub fn resume(id: &str) -> Result<Self> {
1549        let state = RunState::load(id)?;
1550        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1551        if state.startup.as_ref().is_some_and(|s| !s.complete)
1552            || (state.status == RunStatus::Prep
1553                && state.instruction.trim().is_empty()
1554                && state.candidates.is_empty()
1555                && state.prep_complete == Some(false))
1556        {
1557            bail!(
1558                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1559            );
1560        }
1561        crate::pr_head::ensure_owner(&state)?;
1562        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1563            bail!(
1564                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1565            );
1566        }
1567        if let Some(to) = &state.released_to {
1568            bail!(
1569                "run {} cannot be resumed: its worktree was released to run {}",
1570                state.short(),
1571                crate::run::short_of(to)
1572            );
1573        }
1574        let roles = state.config.resolve_roles()?;
1575        if let Some(id) = &state.config.graph.selected_implementer
1576            && state.candidates.iter().any(|c| c.agent != *id)
1577        {
1578            bail!(
1579                "replacement implementer pin does not match the saved candidates; task must stay held"
1580            );
1581        }
1582        let max_parallel = state.config.graph.max_parallel.max(1);
1583        Ok(Self {
1584            state,
1585            roles,
1586            sem: Arc::new(Semaphore::new(max_parallel)),
1587            pause: Pause::new(),
1588            interrupt: Pause::new(),
1589        })
1590    }
1591
1592    /// Walk the graph to a terminal state, skipping nodes already recorded.
1593    ///
1594    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1595    /// the phone - ends here, so this is the one place a run that ended
1596    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1597    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1598    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1599        // Allocate before polling: boxing inside an async wrapper would still
1600        // retain its construction frame while the nested graph is polled.
1601        Box::pin(self.execute_inner(None))
1602    }
1603
1604    pub(crate) async fn execute_sync_only(
1605        &mut self,
1606        request: crate::base_sync_only::Request,
1607    ) -> Result<()> {
1608        Box::pin(self.execute_inner(Some(request))).await
1609    }
1610
1611    async fn execute_inner(
1612        &mut self,
1613        sync_only: Option<crate::base_sync_only::Request>,
1614    ) -> Result<()> {
1615        anyhow::ensure!(
1616            self.state.startup.as_ref().is_none_or(|s| s.complete),
1617            "startup incomplete; inspect retained evidence before explicit recovery"
1618        );
1619        if let Some(selection) = &self.state.pr_recovery
1620            && (selection.source_proof.is_some() || selection.source_run.is_some())
1621        {
1622            Box::pin(selection.verify_source(&self.state.repo)).await?;
1623        }
1624        // Queue claims cover daemon work; this also serializes manual drivers
1625        // consuming a repair answer, including the new review and decision.
1626        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1627            || self.state.land_approval.is_some()
1628            || self.state.merge_decision.is_some()
1629            || !self.state.merge_repairs.is_empty()
1630            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1631        {
1632            let claim = FixClaim::acquire(&self.state.dir())?;
1633            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1634            let disk = RunState::load(&self.state.id)?;
1635            let checkpoint = |s: &RunState| {
1636                (
1637                    s.merge_repairs.len(),
1638                    s.merge_repairs
1639                        .last()
1640                        .map(|r| (r.question.clone(), r.phase)),
1641                    s.land_approval
1642                        .as_ref()
1643                        .map(|a| (a.question.clone(), a.head.clone())),
1644                )
1645            };
1646            if checkpoint(&disk) != checkpoint(&self.state) {
1647                bail!(
1648                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1649                );
1650            }
1651            Some(claim)
1652        } else {
1653            None
1654        };
1655        let base_only = sync_only.is_some();
1656        let mut execution = self.claim_driver(sync_only).await?;
1657        let runner = &mut *execution.runner;
1658        let wait = runner.repository_wait();
1659        // Keep the graph's large future off the callers' stack, including
1660        // standalone task attempts running on a default-sized test thread.
1661        let result = if base_only {
1662            wait.scope(Box::pin(async {
1663                let repo = runner.state.repo.clone();
1664                let result = async {
1665                    let _coordination = runner.coordinate(&repo).await?;
1666                    anyhow::ensure!(
1667                        !runner.pause.parked() && !runner.interrupt.parked(),
1668                        "paused before base synchronization"
1669                    );
1670                    crate::base_sync_only::sync(&mut runner.state).await
1671                }
1672                .await;
1673                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1674                pass.result = match result {
1675                    Ok(outcome) => outcome,
1676                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1677                };
1678                let summary = pass.summary();
1679                runner.state.event("base-sync-only", summary);
1680                runner.state.save()
1681            }))
1682            .await
1683        } else {
1684            wait.scope(Box::pin(runner.execute_graph())).await
1685        };
1686        let result = match result {
1687            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1688                record_repository_block(&mut runner.state, &e);
1689                runner.park_here()?;
1690                Ok(())
1691            }
1692            other => other,
1693        };
1694        execution.driver.finish(&mut runner.state).await?;
1695        let ended = if result.is_err() {
1696            Some({
1697                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1698                if let Err(error) = &result {
1699                    notice.message = format!(
1700                        "Run {} stopped with an error: {}",
1701                        runner.state.id,
1702                        error.to_string().lines().next().unwrap_or("unknown error")
1703                    );
1704                }
1705                notice
1706            })
1707        } else {
1708            crate::notices::run_ended(&runner.state)
1709        };
1710        if let Some(notice) = ended {
1711            crate::notices::raise(notice);
1712        }
1713        result
1714    }
1715
1716    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1717        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1718    }
1719
1720    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1721        let wait = self.repository_wait();
1722        coordinate_operation(&mut self.state, cwd, &wait).await
1723    }
1724
1725    /// Validate ownership and persist the driver claim in one critical section.
1726    async fn claim_driver(
1727        &mut self,
1728        sync_only: Option<crate::base_sync_only::Request>,
1729    ) -> Result<DriverExecution<'_>> {
1730        let owner = match crate::pr_head::owner_lock_wait(
1731            &crate::run::home(),
1732            &self.state.id,
1733            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1734        )
1735        .await
1736        {
1737            Ok(owner) => owner,
1738            Err(error) => {
1739                let detail = format!("worktree maintenance or ownership update: {error:#}");
1740                // Admission did not own run.json: retain this resource outcome
1741                // in memory for queue settlement without overwriting a concurrent
1742                // retirement or publication transaction.
1743                self.state.resource_block = Some(crate::run::ResourceBlock {
1744                    cause: crate::run::ResourceBlockCause::Other,
1745                    node: "start".into(),
1746                    kind: "worktree maintenance".into(),
1747                    detail: detail.clone(),
1748                    at: Timestamp::now(),
1749                });
1750                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1751            }
1752        };
1753        let disk = RunState::load(&self.state.id)?;
1754        crate::pr_head::ensure_owner(&disk)?;
1755        let claimed =
1756            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1757        // Only proven-live ownership refuses here. Unknown records (legacy runs
1758        // with no claim marker or process identity) fall through to the
1759        // exclusive execution lease taken just below, which is what actually
1760        // keeps a second driver out.
1761        anyhow::ensure!(
1762            disk.liveness(claimed) != crate::run::Liveness::Live,
1763            "run already has a live driver; wait for its execution to end"
1764        );
1765        if let Some(to) = &disk.released_to {
1766            bail!(
1767                "run {} cannot continue: its worktree was released to run {}",
1768                self.state.short(),
1769                crate::run::short_of(to)
1770            );
1771        }
1772        anyhow::ensure!(
1773            serde_json::to_value(&disk.base_sync_recovery)?
1774                == serde_json::to_value(&self.state.base_sync_recovery)?,
1775            "base recovery changed since this run was loaded; reload the saved run"
1776        );
1777        anyhow::ensure!(
1778            disk.sync_only_passes == self.state.sync_only_passes,
1779            "base-only synchronization changed since this run was loaded; reload the saved run"
1780        );
1781        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1782        let mut execution = DriverExecution {
1783            runner: self,
1784            driver,
1785        };
1786        // Declare after the execution guard: on any claim error this short
1787        // lock must drop before that guard reloads and releases ownership.
1788        let _owner = owner;
1789        if let Some(request) = sync_only {
1790            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1791            anyhow::ensure!(
1792                request.run == disk.id,
1793                "sync-base-only request targets a different run"
1794            );
1795            let state = &mut execution.runner.state;
1796            let task_entry = state.next_pass_task_entry;
1797            *state = disk;
1798            state.next_pass_task_entry = task_entry;
1799            if state.pending_sync_only().is_some() {
1800                let pass_index = state.passes.len();
1801                let pass = state.sync_only_passes.last_mut().unwrap();
1802                anyhow::ensure!(
1803                    pass.request == request,
1804                    "interrupted base-only synchronization belongs to a different request"
1805                );
1806                pass.pass_index = pass_index;
1807            } else {
1808                let pass = crate::base_sync_only::Pass::new(request, state);
1809                state.sync_only_passes.push(pass);
1810            }
1811            if state.status == RunStatus::Failed {
1812                state.status = RunStatus::Blocked;
1813            }
1814        } else {
1815            anyhow::ensure!(
1816                disk.pending_sync_only().is_none(),
1817                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1818            );
1819            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1820                .await?;
1821        }
1822        let state = &mut execution.runner.state;
1823        // Moving again, so it is no longer parked. Set before the walk rather
1824        // than in `resume`, so every way of re-entering the graph clears it
1825        // and a card cannot claim a run is waiting to be resumed while the
1826        // agents are already working.
1827        state.parked = false;
1828        state.resource_wait = None;
1829        state.resource_block = None;
1830        // Any seat this state still lists as answering belongs to whatever
1831        // process last drove this run — this one included, if it crashed
1832        // mid-wave. Cleared and flushed immediately, before anything else
1833        // runs, so a resume can never show a seat as live when nothing is
1834        // asking it anything yet; the node that actually dispatches the next
1835        // wave repopulates it.
1836        state.clear_active();
1837        // Recorded in the same spot, and flushed together with the clear
1838        // above: this is the pid a reader checks (`RunState::liveness`) when
1839        // no daemon claim exists to answer "is a process still driving this
1840        // run" — a plain `magi run` / `magi review` typed into a terminal
1841        // claims nothing there. Always overwritten, never only-if-absent, so
1842        // a resumed run's stale pid from a previous, possibly-dead process
1843        // can never survive into this one's own report. Unlike
1844        // `clear_active`, this changes on every single `execute()` call, so
1845        // the save below is now unconditional rather than only-if-cleared.
1846        //
1847        // `driver_started_at` is recorded in the same breath, from this same
1848        // pid, so `liveness` can tell a live pid that is genuinely still us
1849        // apart from one the OS has since handed to an unrelated process —
1850        // see that field's own doc for why the pid alone is not enough.
1851        let pid = std::process::id();
1852        state.driver_pid = Some(pid);
1853        state.driver_started_at = crate::proc::process_started_at(pid);
1854        state.driver_exited = false;
1855        state.driver_claimed = Some(true);
1856        state.begin_pass();
1857        execution.driver.bind(state);
1858        state.save()?;
1859        execution.driver.record(state)?;
1860        Ok(execution)
1861    }
1862
1863    /// No conflict checkpoint proves dispatch was never reached. End that
1864    /// consumed generation so an owner can explicitly authorize a fresh one.
1865    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1866        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1867        if let Err(error) = &result
1868            && !error.is::<crate::repo_lock::ResourceBlocked>()
1869            && self
1870                .state
1871                .repair_grants
1872                .last()
1873                .is_some_and(|g| g.conflict.is_none())
1874        {
1875            self.state.repair_grants.last_mut().unwrap().phase =
1876                crate::repair_budget::Phase::Complete;
1877            self.state.status = RunStatus::Blocked;
1878            self.state.save()?;
1879            bail!(
1880                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1881                self.state.passes.last().map_or(0, |p| p.index)
1882            );
1883        }
1884        result
1885    }
1886
1887    /// A grant owns only these repair attempts. Confirmation reviews cannot
1888    /// create another fixer allowance, and every operation is restart-checkpointed.
1889    async fn execute_granted_repair(&mut self) -> Result<()> {
1890        use crate::repair_budget::{Kind, Phase};
1891        let index = self.state.repair_grants.len() - 1;
1892        let winner = self
1893            .state
1894            .winner()
1895            .cloned()
1896            .context("repair winner missing")?;
1897        loop {
1898            let grant = self.state.repair_grants[index].clone();
1899            match grant.phase {
1900                Phase::Pending => {
1901                    if grant.spent >= grant.receipt.request.rounds {
1902                        self.state.repair_grants[index].phase = Phase::Complete;
1903                        self.state.status = RunStatus::Blocked;
1904                        self.state.save()?;
1905                        return Ok(());
1906                    }
1907                    // Reserve before dispatch. A crash can consume an attempt,
1908                    // but can never duplicate it or reset saved fixer history.
1909                    self.state.repair_grants[index].spent += 1;
1910                    self.state.repair_grants[index].phase = Phase::Fixing;
1911                    self.state.save()?;
1912                    match grant.receipt.request.kind {
1913                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1914                        Kind::Gate => {
1915                            let failed = self.state.gate.clone();
1916                            let _ = self.gate_fix_round(&winner, &failed).await?;
1917                        }
1918                        Kind::Review => {
1919                            let mut record = self
1920                                .state
1921                                .reviews
1922                                .last()
1923                                .cloned()
1924                                .context("review failure missing")?;
1925                            let round = record.round;
1926                            let step = self.run_fix_round(&winner, &mut record).await?;
1927                            self.state.reviews[round - 1] = record;
1928                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1929                                self.state.repair_grants[index].phase = Phase::Complete;
1930                                self.state.status = RunStatus::Blocked;
1931                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1932                                self.state.save()?;
1933                                return Ok(());
1934                            }
1935                            if matches!(step, FixStep::Resource) {
1936                                self.stop_for_resource()?;
1937                                return Ok(());
1938                            }
1939                            self.state.save()?;
1940                        }
1941                    }
1942                    if self.resource_halt()? {
1943                        return Ok(());
1944                    }
1945                }
1946                Phase::Fixing => {
1947                    if grant.receipt.request.kind == Kind::BaseConflict {
1948                        self.repair_base_conflict(false).await?;
1949                    }
1950                    // Interrupted fixers may have left source changes or an
1951                    // unpushed commit. Preserve them before fresh assessment.
1952                    let _coordination = self.coordinate(&winner.worktree).await?;
1953                    let rescued = git::rescue_commit(
1954                        &winner.worktree,
1955                        "magi: preserve interrupted granted repair",
1956                    )
1957                    .await?;
1958                    self.state.note_withheld("repair-grant", &rescued.withheld);
1959                    // Fresh checks must supersede even a same-head failure.
1960                    // Archive rather than erase failure evidence or counters.
1961                    self.state
1962                        .verification_history
1963                        .push(crate::run::VerificationEvidence {
1964                            superseded_by: None,
1965                            archived_at: Some(Timestamp::now()),
1966                            fixes_spent: Some(self.state.gate_fixes.len()),
1967                            gate_head: self.state.gate_head.take(),
1968                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1969                            gate: std::mem::take(&mut self.state.gate),
1970                            e2e: self.state.head_e2e.take(),
1971                        });
1972                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1973                        self.state
1974                            .verification_history
1975                            .push(crate::run::VerificationEvidence {
1976                                superseded_by: None,
1977                                archived_at: Some(Timestamp::now()),
1978                                fixes_spent: Some(self.state.gate_fixes.len()),
1979                                gate_head: None,
1980                                gate_ran: false,
1981                                gate: Vec::new(),
1982                                e2e: Some(e2e),
1983                            });
1984                    }
1985                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1986                    self.state.repair_grants[index].head =
1987                        git::rev_parse(&winner.worktree, "HEAD").await?;
1988                    self.state.repair_grants[index].phase = Phase::Reviewing;
1989                    if grant.receipt.request.kind == Kind::BaseConflict {
1990                        self.state.base_sync_recovery.stop = None;
1991                        if let Some(sync) = &mut self.state.base_sync {
1992                            sync.tip = grant
1993                                .receipt
1994                                .request
1995                                .tip
1996                                .clone()
1997                                .context("repair base tip missing")?;
1998                            sync.conflict = None;
1999                            sync.behind = 0;
2000                        }
2001                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2002                    }
2003                    self.state.save()?;
2004                }
2005                Phase::Reviewing => {
2006                    self.review_loop_pass().await?;
2007                    if self.resource_halt()? {
2008                        return Ok(());
2009                    }
2010                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2011                    let clean = self.state.reviews.len() > grant.review_start
2012                        && self.state.reviews.last().is_some_and(|r| {
2013                            r.head == head
2014                                && r.clean
2015                                && r.expected > 0
2016                                && r.answered == r.expected
2017                                && matches!(
2018                                    r.e2e_status(),
2019                                    E2eStatus::Passed | E2eStatus::NotConfigured
2020                                )
2021                        });
2022                    if !clean {
2023                        // A confirmation review carries no additional fix budget.
2024                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2025                            == Kind::Review
2026                            && grant.spent < grant.receipt.request.rounds
2027                            && self.state.reviews.last().is_some_and(|r| {
2028                                r.fix.is_none()
2029                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2030                            }) {
2031                            Phase::Pending
2032                        } else {
2033                            Phase::Complete
2034                        };
2035                        self.state.status = RunStatus::Blocked;
2036                        self.state.event(
2037                            "repair-grant",
2038                            "fresh review did not clear the repaired head; no publication",
2039                        );
2040                        self.state.save()?;
2041                        if self.state.repair_grants[index].phase == Phase::Pending {
2042                            continue;
2043                        }
2044                        return Ok(());
2045                    }
2046                    self.state.repair_grants[index].phase = Phase::Gating;
2047                    self.state.save()?;
2048                }
2049                Phase::Gating => {
2050                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2051                    self.state.reconcile_verification_head(&head);
2052                    let wait = self.repository_wait();
2053                    if self
2054                        .state
2055                        .reviews
2056                        .last()
2057                        .is_none_or(|r| r.head != head || !r.clean)
2058                    {
2059                        self.state.status = RunStatus::Blocked;
2060                        self.state.repair_grants[index].phase = Phase::Complete;
2061                        self.state.event(
2062                            "repair-grant",
2063                            "head changed since fresh review; repair held",
2064                        );
2065                        self.state.save()?;
2066                        return Ok(());
2067                    }
2068                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2069                        return Ok(());
2070                    }
2071                    let outcomes = self.run_gate(&winner).await?;
2072                    if verify_inconclusive(&outcomes) {
2073                        return Ok(());
2074                    }
2075                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2076                    if after != head {
2077                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2078                        self.state.repair_grants[index].head = after;
2079                        self.state.repair_grants[index].phase = Phase::Reviewing;
2080                        self.state.status = RunStatus::Blocked;
2081                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2082                        self.state.save()?;
2083                        return Ok(());
2084                    }
2085                    let passed = outcomes.iter().all(CommandOutcome::ok);
2086                    // Follow-up grants owe the same guarded checkout delivery
2087                    // as the conflict repair that introduced the new head.
2088                    if passed
2089                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2090                    {
2091                        return Ok(());
2092                    }
2093                    self.state.repair_grants[index].succeeded = passed;
2094                    self.state.gate = outcomes;
2095                    self.state.gate_ran = true;
2096                    self.state.status = if passed {
2097                        RunStatus::Gating
2098                    } else {
2099                        RunStatus::Blocked
2100                    };
2101                    self.state.repair_grants[index].phase = if !passed
2102                        && grant.receipt.request.kind == Kind::Gate
2103                        && grant.spent < grant.receipt.request.rounds
2104                    {
2105                        Phase::Pending
2106                    } else {
2107                        Phase::Complete
2108                    };
2109                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2110                        // Persist publication debt with the successful checkpoint.
2111                        self.state.pr_publication_pending = true;
2112                    } else if passed {
2113                        self.state.status = RunStatus::Ready;
2114                    }
2115                    self.state.save()?;
2116                    if !passed {
2117                        continue;
2118                    }
2119                    // Existing PR ownership and push lease stay in place. The
2120                    // normal publisher owes the new reviewed/gated SHA, and
2121                    // land's fresh owner approval remains mandatory.
2122                    if self.state.config.merge.mode != MergeMode::Pr {
2123                        self.state.status = RunStatus::Ready;
2124                        self.state.event(
2125                            "repair-grant",
2126                            "repair verified locally; grant carries no merge authorization",
2127                        );
2128                        self.state.save()?;
2129                        return Ok(());
2130                    }
2131                    return self.merge().await;
2132                }
2133                Phase::Complete => return Ok(()),
2134            }
2135        }
2136    }
2137
2138    async fn execute_graph(&mut self) -> Result<()> {
2139        // Even a terminal run may reenter through an explicit recovery action.
2140        // Restore before prep shortcuts, saved conversations or graph nodes use
2141        // a disposable path; GC may already have removed its original objects.
2142        let archive_home = crate::run::home().canonicalize()?;
2143        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2144            let repo = self.state.repo.clone();
2145            let _coordination = self.coordinate(&repo).await?;
2146            ensure_setup_config(&mut self.state, &repo).await?;
2147            crate::retention::restore_execution_seats(
2148                &archive_home,
2149                &self.state,
2150                _coordination.as_ref(),
2151            )
2152            .await?;
2153        }
2154        self.state.configure_recovery_resume()?;
2155        if self
2156            .state
2157            .repair_grants
2158            .last()
2159            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2160        {
2161            return self.execute_granted_repair().await;
2162        }
2163        if self
2164            .state
2165            .repair_grants
2166            .last()
2167            .is_some_and(|g| !g.succeeded)
2168        {
2169            self.state.status = RunStatus::Blocked;
2170            self.state.save()?;
2171            return Ok(());
2172        }
2173        // Preservation may invalidate an old empty classification. Resolve it
2174        // before any resume shortcut can reuse a verdict or publish a branch.
2175        self.persist_candidates().await?;
2176        // A saved base stop outranks stage markers, including legacy Voting.
2177        // Recovery never reenters implementation, deliberation or voting.
2178        if self.state.base_sync_blocked() {
2179            self.sync_to_base().await?;
2180            if !self.state.base_sync_blocked()
2181                && self.state.status != RunStatus::AlreadyInBase
2182                && !self.resource_halt()?
2183            {
2184                self.finish_after_tally().await?;
2185            }
2186            return Ok(());
2187        }
2188        if self
2189            .state
2190            .merge_decision
2191            .as_ref()
2192            .is_some_and(|decision| !decision.closed)
2193            && self.state.status != RunStatus::Landing
2194        {
2195            if crate::merge_decision::resumable_hold(&self.state) {
2196                self.state.merge = Some(MergeOutcome {
2197                    mode: MergeMode::Pr,
2198                    ok: false,
2199                    detail: self
2200                        .state
2201                        .merge_decision
2202                        .as_ref()
2203                        .unwrap()
2204                        .target
2205                        .pr
2206                        .clone(),
2207                    empty: false,
2208                });
2209                self.run_land().await?;
2210                self.settle_questions();
2211                return Ok(());
2212            }
2213            bail!(
2214                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2215            );
2216        }
2217        if self.state.config.graph.selected_implementer.is_some()
2218            && self.state.status == RunStatus::Blocked
2219            && self.state.tally.is_none()
2220            && self.state.candidate_preservation.is_empty()
2221            && self.state.interrupted_implementations.is_empty()
2222        {
2223            bail!(
2224                "selected implementation is held; explicitly release the owning task to retry it"
2225            );
2226        }
2227
2228        if self.state.merge_repairs.last().is_some_and(|r| {
2229            matches!(
2230                r.phase,
2231                crate::run::MergeRepairPhase::Requested
2232                    | crate::run::MergeRepairPhase::Fixing
2233                    | crate::run::MergeRepairPhase::Reviewing
2234            )
2235        }) {
2236            if self.repair_merge_review().await? {
2237                self.run_land().await?;
2238            }
2239            self.settle_questions();
2240            return Ok(());
2241        }
2242        // Publication already passed review and gate. Resume only that node:
2243        // syncing to a newer base here could change the verified commit.
2244        if self.state.pr_publication_pending {
2245            self.merge().await?;
2246            if self.resource_halt()? {
2247                return Ok(());
2248            }
2249            self.state.save()?;
2250            self.settle_questions();
2251            return Ok(());
2252        }
2253        // A run that already lost its quorum never resumes into the verdict
2254        // machinery: `deliberate` and `vote` would otherwise clobber the
2255        // stalled marker back to Voting and the run would keep going past a
2256        // verdict that is no longer trustworthy. Everything already recorded is
2257        // kept, so the run stays resumable (or foldable) for a human to pick up.
2258        //
2259        // On --resume the run gets one chance to repair itself: the seats a
2260        // rate limit took out are re-asked. If their quota has since reset and
2261        // the quorum is restored, the run picks up and finishes; otherwise it
2262        // stays stale and still-resumable for a later retry. If it does not
2263        // recover, the returned status stays `Stalled` and nothing was
2264        // clobbered (the recovery only mutates entries for the lost seats).
2265        if self.state.status == RunStatus::Stalled {
2266            if self.recover_stall().await? {
2267                self.finish_after_tally().await?;
2268            } else {
2269                // Still below quorum: persist the marker and stay resumable.
2270                self.state.save()?;
2271            }
2272            return Ok(());
2273        }
2274        // A run parked inside `land` - watching CI, mid fix-round, or
2275        // waiting on the owner's merge approval - resumes directly into it,
2276        // never back through `prep`. Everything before `merge` already
2277        // concluded; that is the only way `status` reaches `Landing` in the
2278        // first place. Re-walking `review_loop` first would also be actively
2279        // wrong: its own status recomputation (see its doc) treats any
2280        // clean round as reason to set `status` to `Gating`, which would
2281        // clobber this marker before `merge` ever ran, and this run would
2282        // never find its way back into `land` at all.
2283        if self.state.status == RunStatus::Landing
2284            || crate::handover::landing_checkpoint(&self.state)
2285        {
2286            self.state.land_sync_pending = true;
2287            self.state.save()?;
2288            self.run_land().await?;
2289            // `run_land` may have settled the run right here - CI came back
2290            // green and the PR merged, say - without ever passing back
2291            // through `merge`'s own trailing call. Whatever it left `status`
2292            // as is what this has to read.
2293            self.settle_questions();
2294            return Ok(());
2295        }
2296        // A run parked at `merge` on the owner's word about a withheld PR text
2297        // resumes straight into `merge`. Re-walking the tail would sync to the
2298        // base again (possibly rebasing, possibly spending the fixer) after the
2299        // gate had passed, and then push a tree nobody reviewed or gated.
2300        if self.state.github_text.is_some()
2301            && self.state.merge.is_none()
2302            && self.state.status == RunStatus::Gating
2303        {
2304            self.merge().await?;
2305            if self.resource_halt()? {
2306                return Ok(());
2307            }
2308            self.state.save()?;
2309            return Ok(());
2310        }
2311        if let Err(e) = self.prep().await {
2312            if e.is::<crate::repo_lock::ResourceBlocked>() {
2313                return Err(e);
2314            }
2315            self.state.status = RunStatus::Blocked;
2316            self.state
2317                .prep_failure
2318                .get_or_insert_with(|| format!("{e:#}"));
2319            self.state
2320                .event("prep", format!("preparation stopped: {e:#}"));
2321            self.state.save()?;
2322            return Err(e);
2323        }
2324        if self.park_here()? {
2325            return Ok(());
2326        }
2327        self.advise().await?;
2328        if self.park_here()? {
2329            return Ok(());
2330        }
2331        self.implement().await?;
2332        if self.park_here()? {
2333            return Ok(());
2334        }
2335        // `after_implement` already saved the state and settled any open
2336        // questions when it set this; nothing later in the graph has
2337        // anything to judge.
2338        if self.state.status == RunStatus::VerifiedNoop {
2339            return Ok(());
2340        }
2341        self.judge().await?;
2342        if self.park_here()? {
2343            return Ok(());
2344        }
2345        self.deliberate().await?;
2346        if self.park_here()? {
2347            return Ok(());
2348        }
2349        self.vote().await?;
2350        if self.park_here()? {
2351            return Ok(());
2352        }
2353        self.tally()?;
2354        // A verdict that lost its quorum is not trustworthy: do not review,
2355        // gate, or merge on it. Everything already done is kept, so the run
2356        // stays resumable (or foldable); the human can replace the agent that
2357        // ran out of quota and pick it up.
2358        if self.state.status == RunStatus::Stalled {
2359            // Persist the stalled marker now — the normal end-of-execute save
2360            // below is below this early return, and without it a resumed run
2361            // would reload a pre-tally status and keep going.
2362            self.state.save()?;
2363            return Ok(());
2364        }
2365        self.finish_after_tally().await?;
2366        Ok(())
2367    }
2368
2369    /// A wave could not start its agents because a shared resource stayed busy
2370    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2371    /// resumable. Unstarted seats have no result; completed peers retain
2372    /// their saved candidate state.
2373    fn stop_for_resource(&mut self) -> Result<()> {
2374        // Resource acquisition observes cancellation inside a node. Complete
2375        // the same durable park as every other node boundary before returning.
2376        if self.pause.parked() || self.interrupt.parked() {
2377            self.park_here()?;
2378            return Ok(());
2379        }
2380        if self.state.resource_block.is_some() {
2381            self.state.status = RunStatus::Blocked;
2382        }
2383        self.state.save()
2384    }
2385
2386    /// Stop walking the graph if a node ended on a resource block.
2387    fn resource_halt(&mut self) -> Result<bool> {
2388        if self.state.resource_block.is_none() {
2389            return Ok(false);
2390        }
2391        self.stop_for_resource()?;
2392        Ok(true)
2393    }
2394
2395    /// Park here if asked to, recording it in the run's own timeline.
2396    ///
2397    /// Returns whether the caller should stop walking the graph. The state is
2398    /// saved either way by the node that just finished; this adds the event so
2399    /// the operator's card says why a run that is neither finished nor moving
2400    /// is sitting where it is.
2401    fn park_here(&mut self) -> Result<bool> {
2402        let parking = self.pause.parked() || self.interrupt.parked();
2403        if !parking && self.state.resource_block.is_some() {
2404            self.stop_for_resource()?;
2405            return Ok(true);
2406        }
2407        // Either handle asking is enough - see `Pause`'s own doc for why
2408        // they are never the same one. `interrupt` is checked second so a
2409        // reason it carries is preferred in the message below over a plain
2410        // shutdown park racing it at the same boundary.
2411        if !self.pause.parked() && !self.interrupt.parked() {
2412            return Ok(false);
2413        }
2414        if self.state.parked {
2415            return Ok(true);
2416        }
2417        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2418        if let Some(block) = &mut self.state.resource_block
2419            && matches!(
2420                block.cause,
2421                crate::run::ResourceBlockCause::Cancelled { .. }
2422            )
2423        {
2424            block.cause = crate::run::ResourceBlockCause::Cancelled {
2425                park: cause.clone(),
2426            };
2427        }
2428        let why = match cause.as_ref().map(ParkCause::label) {
2429            Some(reason) => format!(
2430                "parked after `{}` ({reason}) — resume to carry on from here",
2431                self.state.status.as_str()
2432            ),
2433            None => format!(
2434                "parked after `{}` — resume to carry on from here",
2435                self.state.status.as_str()
2436            ),
2437        };
2438        self.state.event("park", why);
2439        self.state
2440            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2441        self.state.parked = true;
2442        self.state.save()?;
2443        Ok(true)
2444    }
2445
2446    /// Only a new explicit operator approval may retry failed preparation.
2447    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2448        if self.state.prep_failure.is_none() {
2449            return Ok(());
2450        }
2451        let failed_at = self
2452            .state
2453            .events
2454            .iter()
2455            .rev()
2456            .find(|event| event.node == "prep")
2457            .map_or(self.state.updated_at, |event| event.at);
2458        anyhow::ensure!(
2459            approval_at > failed_at,
2460            "preparation retry requires a new explicit release after the failure"
2461        );
2462        self.state.prep_failure = None;
2463        self.state.prep_complete = Some(false);
2464        self.state
2465            .event("prep-retry", "operator approved retry of preparation");
2466        Ok(())
2467    }
2468
2469    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2470    pub fn on_pause(&mut self, pause: Pause) {
2471        self.pause = pause;
2472    }
2473
2474    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2475    /// scheduler asking this one run - and no other - to park so a task
2476    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2477    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2478    /// handle.
2479    pub fn watch_interrupt(&mut self, pause: Pause) {
2480        self.interrupt = pause;
2481    }
2482
2483    /// Abandon this run's own open questions, once `status` has actually
2484    /// settled rather than merely paused.
2485    ///
2486    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2487    /// either back up with the candidates, the review round and the seat
2488    /// sessions already on disk, so a question an implementer asked mid-round
2489    /// may still get a real answer read by a real resume. Only the statuses
2490    /// `resumable` excludes are actually final: the run merged, it reached
2491    /// `Ready` with nothing left to do, it failed outright with no
2492    /// established point to continue from, or every candidate agreed, with
2493    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2494    /// every one of those the seat that asked is gone for good, exactly like
2495    /// the run being deleted under `magi run rm` - so the same cleanup
2496    /// applies, worded for what actually happened instead of "the run was
2497    /// deleted".
2498    ///
2499    /// Best-effort and silent on success: called from every place `status`
2500    /// can land on one of those three, including ones a resumed run revisits,
2501    /// so it must cost nothing when there was nothing open to begin with.
2502    fn settle_questions(&mut self) {
2503        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2504            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2505        }
2506    }
2507
2508    /// The tail of the graph after a trustworthy tally: fold losers, review,
2509    /// gate, merge, and persist.
2510    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2511        Box::pin(self.finish_after_tally_inner())
2512    }
2513
2514    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2515        // Before the losers are folded: their branches are what the graft
2516        // reads from.
2517        self.graft().await?;
2518        if self.resource_halt()? {
2519            return Ok(());
2520        }
2521        self.fold_losers().await?;
2522        // Before review starts, and again right before the gate: a run's
2523        // review rounds can themselves take long enough for the base to move
2524        // a second time, and the gate is the one node whose "green" gets
2525        // acted on.
2526        self.sync_to_base().await?;
2527        if self.hold_base_sync().await? || self.resource_halt()? {
2528            return Ok(());
2529        }
2530        if self.state.status == RunStatus::AlreadyInBase {
2531            return Ok(());
2532        }
2533        self.review_loop().await?;
2534        if self.resource_halt()? {
2535            return Ok(());
2536        }
2537        self.sync_to_base().await?;
2538        if self.hold_base_sync().await? || self.resource_halt()? {
2539            return Ok(());
2540        }
2541        if self.state.status == RunStatus::AlreadyInBase {
2542            return Ok(());
2543        }
2544        self.gate().await?;
2545        self.merge().await?;
2546        if self.resource_halt()? {
2547            return Ok(());
2548        }
2549        self.state.save()?;
2550        Ok(())
2551    }
2552
2553    // ---------------------------------------------------------------- prep
2554
2555    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2556    /// run with the step and its output in the event; it is never swallowed.
2557    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2558    /// resume starts over instead of finding candidates and missing seats.
2559    async fn setup_seat_worktree(
2560        &mut self,
2561        repo: &Path,
2562        wt: &Path,
2563        in_prep: bool,
2564        coordination: Option<&crate::repo_lock::SeatLease>,
2565    ) -> Result<()> {
2566        let result = match ensure_setup_config(&mut self.state, repo).await {
2567            Ok(()) => {
2568                worktree_setup::prepare_with(
2569                    &self.state.config,
2570                    repo,
2571                    wt,
2572                    crate::build_target::Coordination::Held(coordination),
2573                )
2574                .await
2575            }
2576            Err(e) => Err(e),
2577        };
2578        if let Err(e) = result {
2579            git::worktree_remove_clean(repo, wt).await.ok();
2580            if in_prep {
2581                self.rollback_prep(repo).await;
2582            }
2583            self.state.status = RunStatus::Blocked;
2584            self.state.event(
2585                "setup",
2586                format!("worktree setup failed in {}: {e:#}", wt.display()),
2587            );
2588            self.state.save()?;
2589            return Err(e);
2590        }
2591        Ok(())
2592    }
2593
2594    /// Undo everything `prep` created, so a resume re-runs it whole.
2595    async fn rollback_prep(&mut self, repo: &Path) {
2596        let root = self.state.worktree_root();
2597        for c in std::mem::take(&mut self.state.candidates) {
2598            if matches!(
2599                git::worktree_remove_clean(repo, &c.worktree).await,
2600                Ok(true)
2601            ) {
2602                git::branch_delete(repo, &c.branch).await.ok();
2603            } else {
2604                self.state.candidates.push(c);
2605            }
2606        }
2607        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2608        for j in 1..=seats {
2609            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2610                .await
2611                .ok();
2612        }
2613        for k in 1..=self.state.config.graph.advisors {
2614            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2615                .await
2616                .ok();
2617        }
2618    }
2619
2620    async fn prep(&mut self) -> Result<()> {
2621        if let Some(reason) = &self.state.prep_failure {
2622            bail!(
2623                "candidate preparation previously failed: {reason}; correct the source before retrying"
2624            );
2625        }
2626        if self
2627            .state
2628            .prep_complete
2629            .unwrap_or(!self.state.candidates.is_empty())
2630        {
2631            return Ok(());
2632        }
2633        let repo = self.state.repo.clone();
2634        // Includes rollback, config, refs, checkout creation and setup. No
2635        // repository mutation may precede the real shared lock acquisition.
2636        let _coordination = self.coordinate(&repo).await?;
2637        let base = self.state.base_commit.clone();
2638        let plan = self.state.sources.plan(&repo, &base).await?;
2639        self.rollback_prep(&repo).await;
2640        if !self.state.candidates.is_empty() {
2641            bail!(
2642                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2643            );
2644        }
2645        self.state.prep_complete = Some(false);
2646        self.state.status = RunStatus::Prep;
2647        self.state.save()?;
2648        let repo = self.state.repo.clone();
2649        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2650        let root = self.state.worktree_root();
2651        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2652
2653        // The hook is the write-time half of the blindness contract; the
2654        // presentation filter in `blind` is the half that cannot be bypassed.
2655        let hooks_dir = self.state.dir().join("hooks");
2656        if self.state.config.blind.commit_msg_hook {
2657            std::fs::create_dir_all(&hooks_dir)
2658                .with_context(|| format!("create {}", hooks_dir.display()))?;
2659            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2660            let path = hooks_dir.join("commit-msg");
2661            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2662            make_executable(&path)?;
2663            // Ref-counted rather than a plain idempotent set: with more than
2664            // one run able to be in flight in the same repository at once
2665            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2666            // true?" check cannot tell "another run of mine still needs
2667            // this" from "nobody does", and the run that happens to finish
2668            // first would disable the hook out from under a sibling still
2669            // relying on it.
2670            git::acquire_worktree_config(&repo).await?;
2671            self.state.enabled_worktree_config = true;
2672        }
2673
2674        // `[worktree] setup` hides its products per worktree, which needs the
2675        // same per-worktree config the hook does. Held until fold, like it.
2676        ensure_setup_config(&mut self.state, &repo).await?;
2677
2678        for (index, (spec, label)) in self
2679            .roles
2680            .implementers
2681            .clone()
2682            .into_iter()
2683            .zip(labels)
2684            .enumerate()
2685        {
2686            let branch = self.state.branch_for(label);
2687            let worktree = root.join(format!("cand-{label}"));
2688            // Persist intent before Git can leave a partially created tree.
2689            // Candidate registration follows setup, so it cannot inventory
2690            // crashes or refusals during creation itself.
2691            self.state.event(
2692                "prep-intent",
2693                serde_json::json!({
2694                    "branch": branch,
2695                    "worktree": worktree,
2696                    "start": start,
2697                    "picks": plan.picks,
2698                })
2699                .to_string(),
2700            );
2701            self.state.save()?;
2702            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2703            if self.state.config.blind.commit_msg_hook {
2704                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2705            }
2706            git::local_exclude(&worktree, "/.magi/").await?;
2707            if let Err(e) = worktree_setup::prepare_with(
2708                &self.state.config,
2709                &repo,
2710                &worktree,
2711                crate::build_target::Coordination::Held(_coordination.as_ref()),
2712            )
2713            .await
2714            {
2715                // Nothing of this prep may survive: a resume must start over,
2716                // not find half the candidates and skip the rest.
2717                git::worktree_remove_clean(&repo, &worktree).await.ok();
2718                git::branch_delete(&repo, &branch).await.ok();
2719                self.rollback_prep(&repo).await;
2720                self.state.status = RunStatus::Blocked;
2721                self.state
2722                    .event("prep", format!("worktree setup failed: {e:#}"));
2723                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2724                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2725                }
2726                self.state.save()?;
2727                return Err(e);
2728            }
2729            self.state.candidates.push(Candidate {
2730                index,
2731                label,
2732                agent: spec.id.clone(),
2733                branch,
2734                worktree,
2735                summary: String::new(),
2736                stat: String::new(),
2737                files: 0,
2738                commits: 0,
2739                empty: false,
2740                failed: None,
2741                verified_noop: None,
2742                duration_ms: 0,
2743                folded: false,
2744            });
2745            self.state.save()?;
2746            for pick in &plan.picks {
2747                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2748                {
2749                    self.state.status = RunStatus::Blocked;
2750                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2751                    self.state
2752                        .event("prep", format!("cannot apply referenced commit: {e}"));
2753                    self.state.save()?;
2754                    return Err(e);
2755                }
2756            }
2757        }
2758
2759        for j in 1..=self.roles.judges.len() {
2760            let wt = root.join(format!("judge-{j}"));
2761            if !wt.exists() {
2762                git::worktree_add_detached(&repo, &wt, &base).await?;
2763                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2764                    .await?;
2765            }
2766        }
2767
2768        // Disposable, detached checkouts for the design-deliberation stage's
2769        // advisor seats — the same shape as the judges' above, at the same
2770        // base commit, since advisors also only ever read. Sized off the
2771        // configured count directly rather than a resolved roster: unlike
2772        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2773        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2774        // `prep` has no `ResolvedRoles` field to read a count from here.
2775        if self.state.config.graph.advise {
2776            for k in 1..=self.state.config.graph.advisors {
2777                let wt = root.join(format!("advisor-{k}"));
2778                if !wt.exists() {
2779                    git::worktree_add_detached(&repo, &wt, &base).await?;
2780                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2781                        .await?;
2782                }
2783            }
2784        }
2785
2786        // A judge cannot tell it is looking at its own patch — the seats keep
2787        // separate conversations — but a panel that shares agents with the
2788        // field is less independent than it looks, and that is worth saying out
2789        // loud once per run rather than leaving it in the config.
2790        let authors: Vec<&str> = self
2791            .roles
2792            .implementers
2793            .iter()
2794            .map(|a| a.id.as_str())
2795            .collect();
2796        let overlap: Vec<String> = self
2797            .roles
2798            .judges
2799            .iter()
2800            .enumerate()
2801            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2802            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2803            .collect();
2804        if !overlap.is_empty() {
2805            let note = format!(
2806                "{} also authored a candidate; blind, but the panel is less \
2807                 independent than {} distinct agents would be",
2808                overlap.join(", "),
2809                self.roles.judges.len()
2810            );
2811            self.state.event("prep", note);
2812        }
2813
2814        self.state.event(
2815            "prep",
2816            format!(
2817                "{} candidates, {} judges, base {} ({})",
2818                self.state.candidates.len(),
2819                self.roles.judges.len(),
2820                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2821                self.state.base_branch
2822            ),
2823        );
2824        self.state.prep_complete = Some(true);
2825        self.state.status = RunStatus::Implementing;
2826        self.state.save()?;
2827        Ok(())
2828    }
2829
2830    // -------------------------------------------------------------- advise
2831
2832    /// The design-deliberation stage: independent, read-only advisor seats
2833    /// each sketch a design before any implementer touches the repository,
2834    /// and (when at least one produced a usable proposal) a synthesis seat
2835    /// blends them into a brief `implement` carries in every candidate's
2836    /// prompt.
2837    ///
2838    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2839    /// advisors` is the proposal count. Everything here is best-effort and
2840    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2841    /// that cannot reach quota, or a synthesis seat that produced nothing
2842    /// usable all leave `implement` exactly as it was before this stage
2843    /// existed — the task instruction alone — rather than failing the whole
2844    /// competition over an enrichment stage. Every outcome is still recorded
2845    /// as an event, so a run that got nothing from this stage says why.
2846    ///
2847    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2848    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2849    /// resumed run whose stage failed would re-run it, and re-spend the
2850    /// agent calls, on every reentry before `implement`.
2851    ///
2852    /// Also skipped once any candidate shows implementation progress — the
2853    /// exact predicate `implement` itself uses to decide a candidate is no
2854    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2855    /// is not enough: a run created by an older binary that predates this
2856    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2857    /// an already-`Implementing`-or-later run under this build would
2858    /// otherwise walk straight back through `prep` (a no-op once candidates
2859    /// exist) into this node and spawn every advisor seat against worktrees
2860    /// `prep` never recreated — after implementation has already started,
2861    /// which is exactly the invariant this stage exists to guarantee.
2862    async fn advise(&mut self) -> Result<()> {
2863        let implement_untouched = self
2864            .state
2865            .candidates
2866            .iter()
2867            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2868        if !self.state.config.graph.advise || self.state.advise_attempted {
2869            return Ok(());
2870        }
2871        if !implement_untouched {
2872            self.state.event(
2873                "advise",
2874                "skipping the design-deliberation stage: at least one \
2875                 candidate already shows implementation progress, so this \
2876                 run is past the point the stage exists to run before"
2877                    .to_owned(),
2878            );
2879            self.state.advise_attempted = true;
2880            self.state.save()?;
2881            return Ok(());
2882        }
2883        let run_id = self.state.id.clone();
2884        let prompts = self.state.config.prompts.clone();
2885        let instruction = self.state.instruction.clone();
2886        let language = self.state.config.graph.language.clone();
2887        let root = self.state.worktree_root();
2888        let n = self.state.config.graph.advisors;
2889        let where_recorded = self.state.dir().join("run.json");
2890
2891        let seats = match self.state.config.advisors() {
2892            Ok(seats) if !seats.is_empty() => seats,
2893            Ok(_) => {
2894                self.state.event(
2895                    "advise",
2896                    format!(
2897                        "[graph] advisors is 0; skipping the design-deliberation \
2898                         stage and continuing without a synthesis brief (see {})",
2899                        where_recorded.display()
2900                    ),
2901                );
2902                self.state.advise_attempted = true;
2903                self.state.save()?;
2904                return Ok(());
2905            }
2906            Err(e) => {
2907                self.state.event(
2908                    "advise",
2909                    format!(
2910                        "could not resolve advisor seats ({e:#}); continuing \
2911                         without a design-deliberation brief (see {})",
2912                        where_recorded.display()
2913                    ),
2914                );
2915                self.state.advise_attempted = true;
2916                self.state.save()?;
2917                return Ok(());
2918            }
2919        };
2920
2921        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2922        let artifacts = agent::artifacts_dir(&self.state.dir());
2923        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2924
2925        let mut jobs = Vec::new();
2926        for (i, spec) in seats.iter().cloned().enumerate() {
2927            let seat_key = format!("advisor-{}", i + 1);
2928            let seat = self.seat(&seat_key, &spec.id);
2929            jobs.push(SeatJob {
2930                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2931                spec,
2932                seat,
2933                cwd: worktrees[i % worktrees.len()].clone(),
2934                timeout,
2935                allow_write: false,
2936                sessions: false,
2937                artifacts: artifacts.clone(),
2938                stem: seat_key,
2939                handover: None,
2940            });
2941        }
2942
2943        self.state.event(
2944            "advise",
2945            format!(
2946                "{} advisor seat(s) sketching a design in parallel",
2947                jobs.len()
2948            ),
2949        );
2950        let mut quota_losses = Vec::new();
2951        let cache = self.state.config.cache_dir();
2952        let ctx = WaveCtx {
2953            carry_seats: false,
2954            pauses: Some((&self.pause, &self.interrupt)),
2955            run: &run_id,
2956            node: "advise",
2957            prompts: &prompts,
2958            cache: cache.as_deref(),
2959            round: None,
2960        };
2961        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2962        let results = ask_json_wave::<Proposal>(
2963            jobs,
2964            Arc::clone(&self.sem),
2965            self.state.config.graph.retries,
2966            &advisor_roster,
2967            &ctx,
2968            &mut quota_losses,
2969            &mut self.state,
2970            &|p: &Proposal| p.validate(),
2971        )
2972        .await;
2973        if self.state.resource_block.is_some() {
2974            return self.stop_for_resource();
2975        }
2976        self.state.quota.extend(quota_losses);
2977
2978        let mut records = Vec::with_capacity(results.len());
2979        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2980            let agent_id = seat.agent.clone();
2981            self.state.seats.insert(seat.key.clone(), seat);
2982            match res {
2983                Ok((proposal, out)) => {
2984                    self.state
2985                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2986                    records.push(advise::AdvisorRecord::proposed(
2987                        i + 1,
2988                        agent_id,
2989                        proposal,
2990                        out.duration_ms,
2991                    ));
2992                }
2993                Err(e) => {
2994                    self.state.event(
2995                        "advise",
2996                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
2997                    );
2998                    records.push(advise::AdvisorRecord::failed(
2999                        i + 1,
3000                        agent_id,
3001                        e.to_string(),
3002                    ));
3003                }
3004            }
3005        }
3006
3007        let mut advice = advise::Advice {
3008            records,
3009            synthesis: None,
3010        };
3011        if advice.proposals().is_empty() {
3012            self.state.event(
3013                "advise",
3014                "no advisor produced a usable proposal; continuing without a \
3015                 synthesis brief"
3016                    .to_owned(),
3017            );
3018        } else {
3019            match self
3020                .synthesize_brief(
3021                    &advice,
3022                    &instruction,
3023                    &language,
3024                    &worktrees[0],
3025                    &artifacts,
3026                    &run_id,
3027                    &prompts,
3028                    cache.as_deref(),
3029                )
3030                .await
3031            {
3032                Ok(Some(text)) => {
3033                    self.state.event(
3034                        "advise",
3035                        "synthesized a design brief for the implementer".to_owned(),
3036                    );
3037                    advice.synthesis = Some(text);
3038                }
3039                Ok(None) => {
3040                    self.state.event(
3041                        "advise",
3042                        "the synthesis seat produced nothing usable; continuing \
3043                         without a design brief"
3044                            .to_owned(),
3045                    );
3046                }
3047                Err(e) => {
3048                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3049                        return Err(e);
3050                    }
3051                    self.state.event(
3052                        "advise",
3053                        format!("could not synthesize a design brief: {e:#}"),
3054                    );
3055                }
3056            }
3057        }
3058        advise::apply_reflection(&mut advice);
3059
3060        self.state.advice = Some(advice);
3061        self.state.advise_attempted = true;
3062        self.state.save()?;
3063        Ok(())
3064    }
3065
3066    /// The synthesis seat: reads every advisor's proposal and blends them
3067    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3068    /// out of [`Runner::advise`] only for readability — it is not called
3069    /// anywhere else.
3070    ///
3071    /// Picked the same way [`crate::talk`]'s standing conversation and
3072    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3073    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3074    /// order (a claude seat, else the first runnable agent in roster order)
3075    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3076    /// in [`crate::config`] for why a dedicated field exists here at all.
3077    #[allow(clippy::too_many_arguments)]
3078    async fn synthesize_brief(
3079        &mut self,
3080        advice: &advise::Advice,
3081        instruction: &str,
3082        language: &str,
3083        cwd: &Path,
3084        artifacts: &Path,
3085        run_id: &str,
3086        prompts: &Prompts,
3087        cache: Option<&Path>,
3088    ) -> Result<Option<String>> {
3089        let chain = agent::pick_chain(
3090            &self.state.config.agents,
3091            self.state.config.roles.synthesizer.as_ref(),
3092            &agent::installed,
3093            "synthesizer",
3094        )?;
3095        let proposals = advice.proposals();
3096        let mut prompt = prompt::with_overlay(
3097            prompt::synthesize_brief(instruction, &proposals, language),
3098            prompts.overlay("advise"),
3099        );
3100        if cache.is_some() {
3101            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3102            // below — see `prompt::build_cache_note`'s doc for why telling a
3103            // read-only seat to build through the shared cache is exactly how
3104            // a sandbox's write refusal gets misread as a defect.
3105            prompt.push('\n');
3106            prompt.push_str(&prompt::build_cache_note("advise", false));
3107        }
3108        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3109        // Each id is tried once, in order; a quota hit, error or unusable
3110        // answer moves to the next. The seat is single-turn (`sessions:
3111        // false`) and the prompt is the whole context, so a fallback agent
3112        // needs nothing carried over.
3113        let mut last = None;
3114        for (n, spec) in chain.iter().enumerate() {
3115            if n > 0 {
3116                self.state
3117                    .event("advise", format!("synthesis falling back to {}", spec.id));
3118            }
3119            let mut seat = self.seat("advise-synthesis", &spec.id);
3120            let wait = self.repository_wait();
3121            let outcome = wait
3122                .scope(agent::invoke(
3123                    spec,
3124                    &mut seat,
3125                    &Invocation {
3126                        coordination: self.state.config.coordination.as_ref(),
3127                        fetched_base: None,
3128                        cwd,
3129                        prompt: &prompt,
3130                        timeout,
3131                        allow_write: false,
3132                        sessions: false,
3133                        artifacts,
3134                        stem: &if n == 0 {
3135                            "advise-synthesis".to_owned()
3136                        } else {
3137                            format!("advise-synthesis-{}", spec.id)
3138                        },
3139                        run: run_id,
3140                        node: "advise",
3141                        cache_dir: None,
3142                        attachments: &[],
3143                        writable: &[],
3144                    },
3145                ))
3146                .await;
3147            if outcome.is_ok() {
3148                self.state.seats.insert(seat.key.clone(), seat);
3149            }
3150            let advance = agent::chain_advances(&outcome);
3151            last = Some(outcome);
3152            if !advance {
3153                break;
3154            }
3155        }
3156        // Exhausted: the last attempt's result is what a single failed seat
3157        // would have produced.
3158        let out = last.expect("a chain holds at least one agent")?;
3159        if !out.usable() {
3160            return Ok(None);
3161        }
3162        let text =
3163            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3164        Ok((!text.trim().is_empty()).then_some(text))
3165    }
3166
3167    // ----------------------------------------------------------- implement
3168
3169    async fn implement(&mut self) -> Result<()> {
3170        self.persist_candidates().await?;
3171        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3172        // agent files with `magi task add` name the run that paid for it. The
3173        // prompt overlay is cloned alongside it because the waves borrow it
3174        // while `self` is mutably borrowed by the node's own bookkeeping.
3175        let run_id = self.state.id.clone();
3176        let prompts = self.state.config.prompts.clone();
3177        let todo: Vec<usize> = self
3178            .state
3179            .candidates
3180            .iter()
3181            .enumerate()
3182            .filter(|(_, c)| {
3183                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3184                    && c.failed.is_none()
3185                    && !c.empty
3186            })
3187            .map(|(i, _)| i)
3188            .collect();
3189        if todo.is_empty() {
3190            return self.after_implement();
3191        }
3192        self.state.status = RunStatus::Implementing;
3193
3194        let language = self.state.config.graph.language.clone();
3195        let github_language = self.state.config.graph.github_language.clone();
3196        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3197        let sessions = self.state.config.graph.sessions;
3198        let artifacts = agent::artifacts_dir(&self.state.dir());
3199        // The design-deliberation stage's blended brief, when `advise` found
3200        // one — carried into every implementer's prompt the same way
3201        // regardless of which candidate it is.
3202        let brief = self
3203            .state
3204            .advice
3205            .as_ref()
3206            .and_then(|a| a.synthesis.as_deref())
3207            .map(str::to_owned);
3208        let attachments = self.state.attachments.clone();
3209
3210        let mut jobs = Vec::new();
3211        for &i in &todo {
3212            let (index, label, worktree) = {
3213                let c = &self.state.candidates[i];
3214                (c.index, c.label, c.worktree.clone())
3215            };
3216            let spec = self.roles.implementers[index].clone();
3217            let seat_key = format!("impl-{label}");
3218            let seat = self.seat(&seat_key, &spec.id);
3219            let instruction = seeded_instruction(&self.state);
3220            jobs.push(SeatJob {
3221                spec,
3222                seat,
3223                prompt: prompt::implement_in(
3224                    &instruction,
3225                    &worktree.to_string_lossy(),
3226                    &language,
3227                    &github_language,
3228                    brief.as_deref(),
3229                    &attachments,
3230                ),
3231                cwd: worktree,
3232                timeout,
3233                allow_write: true,
3234                sessions,
3235                artifacts: artifacts.clone(),
3236                stem: format!("impl-{label}"),
3237                handover: None,
3238            });
3239        }
3240
3241        self.state.event(
3242            "implement",
3243            format!("{} candidates in parallel", jobs.len()),
3244        );
3245        // Kept so a seat whose CLI hung up can be asked again from the same
3246        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3247        // can update a seat's own entry once a fallback agent takes it over —
3248        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3249        // whichever agent actually answered, not the one that quota'd out.
3250        let mut sent = jobs.clone();
3251        let cache = self.state.config.cache_dir();
3252        let ctx = WaveCtx {
3253            carry_seats: false,
3254            pauses: Some((&self.pause, &self.interrupt)),
3255            run: &run_id,
3256            node: "implement",
3257            prompts: &prompts,
3258            cache: cache.as_deref(),
3259            round: None,
3260        };
3261        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3262        if !wave_blocked(&results) {
3263            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3264                .await;
3265            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3266                .await?;
3267            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3268                .await;
3269        }
3270        // Do not finalize failed candidates when the entire wave needs machine
3271        // recovery: leaving them pending resumes this node with its work intact.
3272        if !results.is_empty()
3273            && results
3274                .iter()
3275                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3276        {
3277            let losses: Vec<_> = results
3278                .iter()
3279                .map(|(_, seat, out)| {
3280                    let AgentOutcome::Quota(o) = out else {
3281                        unreachable!()
3282                    };
3283                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3284                })
3285                .collect();
3286            self.state.quota.extend(losses.clone());
3287            for (_, seat, _) in results {
3288                self.state.seats.insert(seat.key.clone(), seat);
3289            }
3290            for &i in &todo {
3291                let label = self.state.candidates[i].label;
3292                self.state.interrupted_implementations.insert(label);
3293                self.state
3294                    .candidate_preservation
3295                    .insert(label, "machine outage awaiting persistence".into());
3296            }
3297            // Preserve partial edits too, while keeping every interrupted seat
3298            // pending even when its tree already contains an inherited patch.
3299            block_machine_outage(&mut self.state, "implement", &losses);
3300            self.state.save()?;
3301            self.persist_candidates().await?;
3302            for &i in &todo {
3303                self.state
3304                    .interrupted_implementations
3305                    .insert(self.state.candidates[i].label);
3306            }
3307            return self.stop_for_resource();
3308        }
3309        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3310
3311        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3312            && results
3313                .iter()
3314                .any(|(_, _, out)| FailClass::of(out).is_some());
3315        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3316            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3317                // Executed turns interrupted by disk pressure already carry
3318                // a preservation barrier from wave. Admission-only waits do
3319                // not. Keep the interrupted seat's session for recovery too.
3320                if self
3321                    .state
3322                    .candidate_preservation
3323                    .contains_key(&self.state.candidates[i].label)
3324                {
3325                    self.state.seats.insert(seat.key.clone(), seat);
3326                }
3327                continue;
3328            }
3329            let seat_key = seat.key.clone();
3330            // A quota fallback (`resume_seat_handovers`) may have handed this
3331            // seat to a different agent than the one `prep` recorded on the
3332            // candidate; the stats tables and any later fixer-defaults-to-
3333            // winner's-author lookup must credit whoever actually answered —
3334            // unless every fallback also quota'd out, in which case nobody
3335            // actually answered and crediting the last agent tried would
3336            // erase every earlier agent's own quota loss from the stats
3337            // tables instead of just this one seat's.
3338            let agent = seat.agent.clone();
3339            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3340            self.state.seats.insert(seat.key.clone(), seat);
3341            let label = self.state.candidates[i].label;
3342            self.state.interrupted_implementations.remove(&label);
3343
3344            let (summary, duration, failed, verified_claim) = match out {
3345                AgentOutcome::Ok(o) => {
3346                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3347                    let failed = (!o.usable()).then(|| {
3348                        if o.timed_out {
3349                            "agent timed out".to_owned()
3350                        } else {
3351                            format!(
3352                                "agent exited with {}",
3353                                crate::notices::exit_status(o.exit_code)
3354                            )
3355                        }
3356                    });
3357                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3358                    (text, o.duration_ms, failed, verified_claim)
3359                }
3360                // Left un-resumed by `resume_undelivered` (a dirty tree
3361                // already rescues the work, or there was no session left to
3362                // resume into) — reported like the ordinary failure it is,
3363                // never as if `o.text` (the CLI's raw error JSON) were an
3364                // answer.
3365                AgentOutcome::Dropped(o) => {
3366                    let why = o
3367                        .dropped
3368                        .as_ref()
3369                        .map(|d| d.why.as_str())
3370                        .unwrap_or("the CLI ended the stream without delivering its answer");
3371                    (
3372                        String::new(),
3373                        o.duration_ms,
3374                        Some(format!("the CLI dropped the stream ({why})")),
3375                        None,
3376                    )
3377                }
3378                AgentOutcome::Quota(o) => {
3379                    self.state.quota.push(QuotaLoss::from_report(
3380                        seat_key,
3381                        "implement",
3382                        o.quota.as_ref(),
3383                    ));
3384                    (
3385                        String::new(),
3386                        o.duration_ms,
3387                        Some("rate limited (quota); produced no change".to_owned()),
3388                        None,
3389                    )
3390                }
3391                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3392                    (String::new(), 0, Some(e), None)
3393                }
3394            };
3395
3396            // Save every completed turn before any fallible Git operation. A failed
3397            // rescue must not erase the reply or prevent collection of other seats.
3398            let c = &mut self.state.candidates[i];
3399            if !exhausted_the_fallback_chain {
3400                c.agent = agent;
3401            }
3402            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3403            c.duration_ms = duration;
3404            c.failed = failed;
3405            c.verified_noop = verified_claim;
3406            self.state
3407                .candidate_preservation
3408                .insert(label, "awaiting persistence".to_owned());
3409        }
3410        self.state.save()?;
3411        self.persist_candidates().await?;
3412
3413        if resource_blocked {
3414            return self.stop_for_resource();
3415        }
3416        if selected_failed {
3417            self.state.status = RunStatus::Blocked;
3418            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3419            self.state.save()?;
3420            bail!(
3421                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3422            );
3423        }
3424        self.after_implement()
3425    }
3426
3427    /// Retry only persistence after a completed implementation turn.
3428    async fn persist_candidates(&mut self) -> Result<()> {
3429        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3430        for label in labels {
3431            let i = self
3432                .state
3433                .candidates
3434                .iter()
3435                .position(|c| c.label == label)
3436                .context("pending candidate is missing")?;
3437            let c = self.state.candidates[i].clone();
3438            let interrupted = self.state.interrupted_implementations.contains(&label);
3439            let result = async {
3440                let wait = crate::repo_lock::WaitPolicy::new(
3441                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3442                    || false,
3443                );
3444                let _coordination =
3445                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3446                // Best effort evidence requires no index writes. A successful snapshot
3447                // never authorizes removal of a tree whose rescue failed.
3448                if let Err(e) = git::snapshot_uncommitted(
3449                    &c.worktree,
3450                    &self
3451                        .state
3452                        .dir()
3453                        .join("artifacts")
3454                        .join(format!("candidate-{label}-recovery")),
3455                )
3456                .await
3457                {
3458                    self.state.event(
3459                        "preserve",
3460                        format!("candidate {label} snapshot incomplete: {e:#}"),
3461                    );
3462                }
3463                let rescued = git::rescue_commit(
3464                    &c.worktree,
3465                    &format!("magi: candidate {label} (uncommitted work)"),
3466                )
3467                .await?;
3468                self.state.note_withheld("implement", &rescued.withheld);
3469                let base = &self.state.base_commit;
3470                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3471                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3472                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3473                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3474                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3475                if c.empty && commits > 0 && !patch.trim().is_empty()
3476                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3477                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3478                        || self.state.tally.is_some())
3479                {
3480                    // Keep the old classification and pending marker so every
3481                    // retry stops too. Retain decisions as recovery evidence;
3482                    // only a supported recovery operation may replace them.
3483                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3484                }
3485                let c = &mut self.state.candidates[i];
3486                c.commits = commits;
3487                c.stat = stat;
3488                c.files = files;
3489                let no_changes = commits == 0 || patch.trim().is_empty();
3490                c.empty = no_changes && !interrupted;
3491                if interrupted && no_changes {
3492                    c.failed = None;
3493                    c.verified_noop = None;
3494                }
3495                if !c.empty {
3496                    c.failed = None;
3497                    c.verified_noop = None;
3498                }
3499                self.state.event(
3500                    "preserve",
3501                    format!("candidate {label}: {files} files, {commits} commits"),
3502                );
3503                Ok::<_, anyhow::Error>(())
3504            }
3505            .await;
3506            match result {
3507                Ok(()) => {
3508                    self.state.candidate_preservation.remove(&label);
3509                    if !interrupted || self.state.candidates[i].files > 0 {
3510                        self.state.interrupted_implementations.remove(&label);
3511                    }
3512                }
3513                Err(e) => {
3514                    let reason = format!("candidate {label} preservation failed: {e:#}");
3515                    self.state.event("preserve", &reason);
3516                    self.state.candidate_preservation.insert(label, reason);
3517                }
3518            }
3519            if self.state.candidate_preservation.is_empty()
3520                && self.state.status == RunStatus::Blocked
3521                && self.state.candidates.iter().all(|c| c.failed.is_none())
3522            {
3523                // Persist the recovered phase with the cleared pending marker;
3524                // a crash between saves must not turn this into a selected-seat
3525                // failure hold on the next resume.
3526                self.state.status = RunStatus::Implementing;
3527                self.state.event(
3528                    "preserve",
3529                    "candidate persistence recovered; implementation can continue",
3530                );
3531            }
3532            self.state.save()?;
3533        }
3534        if !self.state.candidate_preservation.is_empty() {
3535            self.state.status = RunStatus::Blocked;
3536            self.state.save()?;
3537            bail!(
3538                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3539            );
3540        }
3541        Ok(())
3542    }
3543
3544    /// Ask again, once, for work a CLI did and then failed to hand over.
3545    ///
3546    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3547    /// status with an empty response and a usage report showing output tokens,
3548    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3549    /// seven minutes and 14,267 output tokens that arrived as an empty
3550    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3551    ///
3552    /// Two conditions, and both matter:
3553    ///
3554    /// - **Only when the tree is untouched.** Often the agent has already
3555    ///   written its files and only the closing message was lost; the rescue
3556    ///   commit below picks that up and there is nothing to ask for. Re-asking
3557    ///   then would pay for a second implementation of work already on disk.
3558    /// - **Once.** A CLI that drops one stream can drop the next, and this
3559    ///   node is the most expensive in the graph.
3560    ///
3561    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3562    /// dropped reply still carried its `conversation_id`, so the seat is asked
3563    /// to finish what it was doing rather than sent the whole task again. It
3564    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3565    /// node's - for the same reason a re-ranked judge does: restating finished
3566    /// work is not the work.
3567    ///
3568    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3569    /// same way until it resets, while an abandoned conversation is still
3570    /// there to be picked up.
3571    async fn resume_undelivered(
3572        &mut self,
3573        results: &mut [(usize, SeatState, AgentOutcome)],
3574        sent: &[SeatJob],
3575        prompts: &Prompts,
3576        run_id: &str,
3577    ) {
3578        for (wi, seat, out) in results.iter_mut() {
3579            let Some(dropped) = (match &*out {
3580                AgentOutcome::Dropped(o) => o.dropped.clone(),
3581                _ => None,
3582            }) else {
3583                continue;
3584            };
3585            let Some(job) = sent.get(*wi) else { continue };
3586            // Already on disk? Then only the closing message was lost.
3587            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3588                self.state.event(
3589                    "implement",
3590                    format!(
3591                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3592                         work is in the tree",
3593                        seat.key, dropped.output_tokens, dropped.why
3594                    ),
3595                );
3596                continue;
3597            }
3598            // The re-ask only makes sense as a resume: `resume_after_drop`
3599            // says nothing about the task, trusting the seat to still hold it.
3600            // Without a session to resume — sessions disabled, or this CLI's
3601            // drop shape happened not to carry a session id — that prompt
3602            // would open a brand-new conversation with no context at all,
3603            // which is worse than leaving this as the ordinary failure it
3604            // already is.
3605            if !has_context(&job.spec, seat, job.sessions) {
3606                self.state.event(
3607                    "implement",
3608                    format!(
3609                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3610                         is no session left to resume",
3611                        seat.key, dropped.output_tokens, dropped.why
3612                    ),
3613                );
3614                continue;
3615            }
3616            self.state.event(
3617                "implement",
3618                format!(
3619                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3620                     conversation",
3621                    seat.key, dropped.output_tokens, dropped.why
3622                ),
3623            );
3624            let mut retry = job.clone();
3625            retry.seat = seat.clone();
3626            retry.prompt = prompt::resume_after_drop(&dropped.why);
3627            retry.timeout = retry_budget(job.timeout, true);
3628            retry.stem = format!("{}-resume", job.stem);
3629            let cache = self.state.config.cache_dir();
3630            let ctx = WaveCtx {
3631                carry_seats: false,
3632                pauses: Some((&self.pause, &self.interrupt)),
3633                run: run_id,
3634                node: "implement",
3635                prompts,
3636                cache: cache.as_deref(),
3637                round: None,
3638            };
3639            let (resumed_seat, resumed) =
3640                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3641            *seat = resumed_seat;
3642            *out = resumed;
3643        }
3644    }
3645
3646    /// Fall an implement seat through to the next untried agent in the
3647    /// implementer roster when it lost to quota — or, since the handover was
3648    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3649    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3650    /// quota path itself being unchanged — instead of leaving the
3651    /// seat's loss final the moment one agent's account runs dry.
3652    ///
3653    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3654    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3655    /// truncates to the single slot rotation picked, so a solo task whose one
3656    /// implementer hits quota mid-run used to have nothing else to try. This
3657    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3658    /// unrotated roster — which is the only place the *other* candidates in
3659    /// the machine's roster still exist once `implementers` has been cut down
3660    /// to size.
3661    ///
3662    /// Walks forward from just past the seat's own original position in the
3663    /// roster, never wrapping back to the front: a later candidate slot (say
3664    /// `beta`, the roster's second entry) must fall through to the *next*
3665    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3666    /// almost certainly a different candidate's own agent already — and once
3667    /// the roster's tail is exhausted there is nothing left to fall through
3668    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3669    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3670    /// let this retry that id forever. The loop keeps falling through until
3671    /// an attempt lands something other than `Quota` or the roster's tail
3672    /// runs out of untried ids, at which point the seat is left exactly as
3673    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3674    /// `QuotaLoss` recorded, the candidate failed/empty.
3675    ///
3676    /// `sent` is taken mutably and updated with the fallback agent's spec:
3677    /// `resume_unconfirmed_commands`, which runs after this and also reads
3678    /// `sent`, must see whichever agent actually ended up answering the seat
3679    /// — reading the stale, original spec there would check session
3680    /// eligibility against the wrong CLI and could hand a fallback agent's
3681    /// session id to the agent that just lost the seat to quota.
3682    ///
3683    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3684    /// — `self.seat` only reuses state when the agent id is unchanged, so
3685    /// handing it a different id already gets this for free. Reusing the old
3686    /// seat would resume a different CLI's session as if it were a
3687    /// continuation of this one.
3688    ///
3689    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3690    /// a quota loss cuts an agent off mid-turn, so anything already in the
3691    /// tree is unfinished work, not a completed candidate a re-ask would pay
3692    /// for twice. A dirty tree is rescued into a commit first (the same
3693    /// neutral-identity rescue `implement`'s own outcome loop gives every
3694    /// candidate) so the next agent starts clean.
3695    ///
3696    /// The new agent gets the implementer's full prompt and full
3697    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3698    /// it has no session and no context, and is implementing the task from
3699    /// nothing, unlike a resumed drop which is only restating work already
3700    /// done.
3701    ///
3702    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3703    /// `implement` event, never into `self.state.quota` — that is what
3704    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3705    /// go unspent, and a seat that ultimately recovered on its second or
3706    /// third agent is not the stalled panel that check exists to catch. Only
3707    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3708    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3709    /// outcome loop already has — this helper never pushes to it itself.
3710    async fn resume_seat_handovers(
3711        &mut self,
3712        results: &mut [(usize, SeatState, AgentOutcome)],
3713        sent: &mut [SeatJob],
3714        prompts: &Prompts,
3715        run_id: &str,
3716    ) -> Result<()> {
3717        let instruction = seeded_instruction(&self.state);
3718        let language = self.state.config.graph.language.clone();
3719        let github_language = self.state.config.graph.github_language.clone();
3720        let brief = self
3721            .state
3722            .advice
3723            .as_ref()
3724            .and_then(|a| a.synthesis.as_deref())
3725            .map(str::to_owned);
3726        let attachments = self.state.attachments.clone();
3727        for (wi, seat, out) in results.iter_mut() {
3728            // Who holds the other candidate seats of this wave right now
3729            // (earlier handovers already written back to `sent`).
3730            let others: BTreeSet<String> = sent
3731                .iter()
3732                .enumerate()
3733                .filter(|(j, _)| j != wi)
3734                .map(|(_, j)| j.spec.id.clone())
3735                .collect();
3736            let Some(job) = sent.get_mut(*wi) else {
3737                continue;
3738            };
3739            // Where the seat's own original agent sits in the roster — the
3740            // fallback walk starts just past here, never at the front, so a
3741            // later candidate slot's quota loss does not fall back onto an
3742            // earlier slot's own agent.
3743            let start = self
3744                .roles
3745                .implementer_roster
3746                .iter()
3747                .position(|s| s.id == job.spec.id)
3748                .unwrap_or(0);
3749            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3750            let mut fallback_attempt = 0usize;
3751            let mut prev: Option<FailClass> = None;
3752            while let Some(cur) = FailClass::of(&*out) {
3753                if !should_hand_over(prev.as_ref(), &cur) {
3754                    break;
3755                }
3756                let Some(next) =
3757                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3758                        .cloned()
3759                else {
3760                    break;
3761                };
3762                tried.insert(next.id.clone());
3763                fallback_attempt += 1;
3764
3765                let coordination = self.coordinate(&job.cwd).await?;
3766                if let Ok(r) = git::rescue_commit(
3767                    &job.cwd,
3768                    &format!(
3769                        "magi: candidate {} (uncommitted work before {} fallback)",
3770                        seat.key,
3771                        if cur == FailClass::Quota {
3772                            "quota"
3773                        } else {
3774                            "handover"
3775                        }
3776                    ),
3777                )
3778                .await
3779                {
3780                    self.state.note_withheld("implement", &r.withheld);
3781                }
3782                drop(coordination);
3783
3784                record_handover(
3785                    &mut self.state,
3786                    "implement",
3787                    &seat.key,
3788                    &seat.agent,
3789                    &next.id,
3790                    &cur,
3791                    &fail_reason(&*out),
3792                );
3793                prev = Some(cur.clone());
3794
3795                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3796                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3797                // Kept in sync on `sent` itself, not just the local retry: a
3798                // later helper (`resume_unconfirmed_commands`) reads `sent`
3799                // after this one returns and must see whichever agent is now
3800                // occupying the seat, not the one that just quota'd out —
3801                // otherwise it would judge session/continuation eligibility
3802                // by the wrong CLI and could resend a fallback's session id
3803                // to the agent that lost it the seat in the first place.
3804                job.spec = next.clone();
3805                let mut retry = job.clone();
3806                retry.seat = new_seat;
3807                retry.prompt = prompt::implement_in(
3808                    &instruction,
3809                    &job.cwd.to_string_lossy(),
3810                    &language,
3811                    &github_language,
3812                    brief.as_deref(),
3813                    &attachments,
3814                );
3815                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3816                let cache = self.state.config.cache_dir();
3817                let ctx = WaveCtx {
3818                    carry_seats: false,
3819                    pauses: Some((&self.pause, &self.interrupt)),
3820                    run: run_id,
3821                    node: "implement",
3822                    prompts,
3823                    cache: cache.as_deref(),
3824                    round: None,
3825                };
3826                let (fallback_seat, fallback_out) = run_one(
3827                    retry,
3828                    Arc::clone(&self.sem),
3829                    &ctx,
3830                    &mut self.state,
3831                    fallback_attempt,
3832                )
3833                .await;
3834                *seat = fallback_seat;
3835                *out = fallback_out;
3836            }
3837        }
3838        Ok(())
3839    }
3840
3841    /// Ask an implement seat's own CLI to confirm what it started, once, when
3842    /// its reply reported a command whose completion status it never
3843    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3844    /// that does and does not mean.
3845    ///
3846    /// The completion contract this task asks for, extended to `implement`
3847    /// with the same signal `continue_fix_report` reads for the fixer,
3848    /// rather than a keyword search over the reply or a hard requirement on
3849    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3850    /// a candidate's CLI turn ended cleanly while a test run it had started
3851    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3852    /// named in it at all is untouched by this: `commands` is empty, so
3853    /// there is nothing to be unconfirmed.
3854    ///
3855    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3856    /// this is not about recovering edits that might already be on disk, it
3857    /// is about a result the seat itself never vouched for, which resuming
3858    /// asks for regardless of what the tree already holds. Bounded to one
3859    /// attempt for the same reason `resume_undelivered` is — this is the
3860    /// most expensive node in the graph — and a seat that still cannot
3861    /// confirm on that attempt is left as whatever its (possibly still
3862    /// unconfirmed) reply says; this does not invent a new "failed" reason
3863    /// for a candidate that otherwise produced a real, committed change.
3864    async fn resume_unconfirmed_commands(
3865        &mut self,
3866        results: &mut [(usize, SeatState, AgentOutcome)],
3867        sent: &[SeatJob],
3868        prompts: &Prompts,
3869        run_id: &str,
3870    ) {
3871        for (wi, seat, out) in results.iter_mut() {
3872            let AgentOutcome::Ok(o) = &*out else {
3873                continue;
3874            };
3875            if !has_unconfirmed_command(&o.commands) {
3876                continue;
3877            }
3878            let Some(job) = sent.get(*wi) else { continue };
3879            if !has_context(&job.spec, seat, job.sessions) {
3880                self.state.event(
3881                    "implement",
3882                    format!(
3883                        "{}: the reply named a command whose own CLI never confirmed the exit \
3884                         status of, but there is no session left to resume",
3885                        seat.key
3886                    ),
3887                );
3888                continue;
3889            }
3890            self.state.event(
3891                "implement",
3892                format!(
3893                    "{}: the reply named a command whose own CLI never confirmed the exit \
3894                     status of; resuming the conversation",
3895                    seat.key
3896                ),
3897            );
3898            let mut retry = job.clone();
3899            retry.seat = seat.clone();
3900            retry.prompt = prompt::resume_incomplete(
3901                "a command in your last reply had no confirmed exit status",
3902            );
3903            retry.timeout = retry_budget(job.timeout, true);
3904            retry.stem = format!("{}-confirm", job.stem);
3905            let cache = self.state.config.cache_dir();
3906            let ctx = WaveCtx {
3907                carry_seats: false,
3908                pauses: Some((&self.pause, &self.interrupt)),
3909                run: run_id,
3910                node: "implement",
3911                prompts,
3912                cache: cache.as_deref(),
3913                round: None,
3914            };
3915            let (resumed_seat, resumed) =
3916                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3917            *seat = resumed_seat;
3918            *out = resumed;
3919        }
3920    }
3921
3922    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3923    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3924    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3925    /// that motivated this.
3926    ///
3927    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3928    /// own nudge loop already covers for judge/review/vote seats, and not a
3929    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3930    /// implement seats: here the CLI turn genuinely finished while the node's
3931    /// own work — the fixer's account of what it did — had not. Gated purely
3932    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3933    /// reply, never on any wording in it, so a fixer whose valid, first-try
3934    /// `FixReport` happens to mention having waited on a background test is
3935    /// never resumed — the `Ok(report)` branch at the call site returns
3936    /// before this is ever invoked.
3937    ///
3938    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3939    /// attempt ([`retry_budget`]), nothing attempted once the session is
3940    /// gone, and a quota hit ends the loop immediately rather than retrying a
3941    /// rate limit that fails the same way again.
3942    async fn continue_fix_report(
3943        &mut self,
3944        mut seat: SeatState,
3945        parse_err: String,
3946        job: &SeatJob,
3947        prompts: &Prompts,
3948        run_id: &str,
3949        round: usize,
3950    ) -> (
3951        SeatState,
3952        Option<FixReport>,
3953        Option<String>,
3954        ContinuationRecord,
3955    ) {
3956        let mut last_err = parse_err;
3957        let mut cumulative_wait_ms = 0u64;
3958        let mut attempts = 0usize;
3959        loop {
3960            if !has_context(&job.spec, &seat, job.sessions) {
3961                self.state.event(
3962                    "fix",
3963                    format!(
3964                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3965                         session left to resume into"
3966                    ),
3967                );
3968                let outcome = if attempts == 0 {
3969                    ContinuationOutcome::NoSession
3970                } else {
3971                    ContinuationOutcome::Exhausted
3972                };
3973                return (
3974                    seat,
3975                    None,
3976                    Some(format!("unparsable fix report: {last_err}")),
3977                    ContinuationRecord {
3978                        attempts,
3979                        cumulative_wait_ms,
3980                        outcome,
3981                    },
3982                );
3983            }
3984            if attempts >= MAX_FIX_CONTINUATIONS {
3985                self.state.event(
3986                    "fix",
3987                    format!(
3988                        "round {round}: fixer's reply still had no adoption report after \
3989                         {attempts} continuation(s) ({last_err}); giving up"
3990                    ),
3991                );
3992                return (
3993                    seat,
3994                    None,
3995                    Some(format!(
3996                        "unparsable fix report after {attempts} continuation(s): {last_err}"
3997                    )),
3998                    ContinuationRecord {
3999                        attempts,
4000                        cumulative_wait_ms,
4001                        outcome: ContinuationOutcome::Exhausted,
4002                    },
4003                );
4004            }
4005            attempts += 1;
4006            self.state.event(
4007                "fix",
4008                format!(
4009                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4010                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4011                ),
4012            );
4013            let mut retry = job.clone();
4014            retry.seat = seat.clone();
4015            retry.prompt = prompt::resume_incomplete(&last_err);
4016            retry.timeout = retry_budget(job.timeout, true);
4017            retry.stem = format!("{}-continue{attempts}", job.stem);
4018            let cache = self.state.config.cache_dir();
4019            let ctx = WaveCtx {
4020                carry_seats: false,
4021                pauses: Some((&self.pause, &self.interrupt)),
4022                run: run_id,
4023                node: "fix",
4024                prompts,
4025                cache: cache.as_deref(),
4026                round: Some(round),
4027            };
4028            let (resumed_seat, resumed_out) = run_one(
4029                retry,
4030                Arc::clone(&self.sem),
4031                &ctx,
4032                &mut self.state,
4033                attempts,
4034            )
4035            .await;
4036            seat = resumed_seat;
4037            match resumed_out {
4038                AgentOutcome::Ok(o) => {
4039                    cumulative_wait_ms += o.duration_ms;
4040                    match verdict::extract_json::<FixReport>(&o.text) {
4041                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4042                            self.state.event(
4043                                "fix",
4044                                format!(
4045                                    "round {round}: fixer's adoption report recovered after \
4046                                     {attempts} continuation(s)"
4047                                ),
4048                            );
4049                            return (
4050                                seat,
4051                                Some(report),
4052                                None,
4053                                ContinuationRecord {
4054                                    attempts,
4055                                    cumulative_wait_ms,
4056                                    outcome: ContinuationOutcome::Resumed,
4057                                },
4058                            );
4059                        }
4060                        // The report parsed, but this same reply's own
4061                        // CommandEvidence — the identical record `state.jobs`
4062                        // renders — names a command whose CLI never
4063                        // confirmed an exit status. Read together, that is
4064                        // not a resolved answer: keep nudging rather than
4065                        // accept a report standing next to a command the
4066                        // seat's own CLI cannot vouch for.
4067                        Ok(_) => {
4068                            last_err = "the reply parsed, but it reported a command whose own CLI \
4069                                 never confirmed an exit status"
4070                                .to_owned();
4071                        }
4072                        Err(e) => last_err = e.to_string(),
4073                    }
4074                }
4075                AgentOutcome::Quota(o) => {
4076                    cumulative_wait_ms += o.duration_ms;
4077                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4078                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4079                    self.state.quota.push(loss);
4080                    self.state.event(
4081                        "fix",
4082                        format!(
4083                            "round {round}: continuation rate limited (quota); not retrying now"
4084                        ),
4085                    );
4086                    return (
4087                        seat,
4088                        None,
4089                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4090                        ContinuationRecord {
4091                            attempts,
4092                            cumulative_wait_ms,
4093                            outcome: ContinuationOutcome::QuotaLost,
4094                        },
4095                    );
4096                }
4097                AgentOutcome::Dropped(o) => {
4098                    cumulative_wait_ms += o.duration_ms;
4099                    let why = o
4100                        .dropped
4101                        .as_ref()
4102                        .map(|d| d.why.as_str())
4103                        .unwrap_or("the CLI ended the stream without delivering its answer");
4104                    last_err = format!("the CLI dropped the stream ({why})");
4105                }
4106                AgentOutcome::Failed(e) => last_err = e,
4107                // The continuation was never started; the report stays lost
4108                // and the caller records that, without any handover.
4109                AgentOutcome::ResourceBlocked(e) => {
4110                    return (
4111                        seat,
4112                        None,
4113                        Some(format!("the continuation was not started: {e}")),
4114                        ContinuationRecord {
4115                            attempts: attempts.saturating_sub(1),
4116                            cumulative_wait_ms,
4117                            outcome: ContinuationOutcome::NoSession,
4118                        },
4119                    );
4120                }
4121            }
4122        }
4123    }
4124
4125    fn after_implement(&mut self) -> Result<()> {
4126        if !self.state.candidate_preservation.is_empty() {
4127            bail!("candidate preservation incomplete; judging is unsafe");
4128        }
4129        // Scan every candidate patch once the set is complete.
4130        if self.state.leaks.is_empty() {
4131            let cfg = self.state.config.blind.clone();
4132            let mut leaks = Vec::new();
4133            for c in &self.state.candidates {
4134                let Some(patch) =
4135                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4136                else {
4137                    continue;
4138                };
4139                leaks.extend(blind::scan(
4140                    &format!("candidate {} patch", c.label),
4141                    &patch,
4142                    &cfg.vendor_tokens,
4143                ));
4144            }
4145            if !leaks.is_empty() {
4146                let summary = leaks
4147                    .iter()
4148                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4149                    .collect::<Vec<_>>()
4150                    .join(", ");
4151                match cfg.on_leak {
4152                    LeakPolicy::Fail => {
4153                        self.state.status = RunStatus::Failed;
4154                        self.state
4155                            .event("blind", format!("vendor text in a patch: {summary}"));
4156                        self.state.leaks = leaks;
4157                        self.state.save()?;
4158                        self.settle_questions();
4159                        bail!(
4160                            "blind.on_leak = \"fail\" and vendor text reached a \
4161                             judged patch: {summary}"
4162                        );
4163                    }
4164                    LeakPolicy::Redact => self.state.event(
4165                        "blind",
4166                        format!("redacting vendor text for judging: {summary}"),
4167                    ),
4168                    LeakPolicy::Warn => self.state.event(
4169                        "blind",
4170                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4171                    ),
4172                }
4173                self.state.leaks = leaks;
4174            }
4175        }
4176
4177        if self.state.viable().is_empty() {
4178            if self.state.all_candidates_verified_noop() {
4179                // Every candidate agreed, with evidence the adoption guard
4180                // accepted, that nothing belongs in this worktree. That is
4181                // not the same fact as a candidate that simply failed to
4182                // write anything, and settling it as an ordinary `Failed`
4183                // (see `SCHEMA`'s doc for schema 10) is what let two of
4184                // task 391f's attempts burn a retry each re-discovering the
4185                // same already-landed fix. Terminal either way, so `judge`
4186                // must never run over an empty candidate set — unlike the
4187                // `Failed` branch below this returns `Ok`, not an error:
4188                // nothing here failed.
4189                self.state.status = RunStatus::VerifiedNoop;
4190                self.state.save()?;
4191                self.settle_questions();
4192                return Ok(());
4193            }
4194            self.state.status = RunStatus::Failed;
4195            self.state.save()?;
4196            self.settle_questions();
4197            bail!("no candidate produced a change; nothing to judge");
4198        }
4199        self.state.status = RunStatus::Judging;
4200        self.state.save()?;
4201        Ok(())
4202    }
4203
4204    // --------------------------------------------------------------- judge
4205
4206    async fn judge(&mut self) -> Result<()> {
4207        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4208        // agent files with `magi task add` name the run that paid for it. The
4209        // prompt overlay is cloned alongside it because the waves borrow it
4210        // while `self` is mutably borrowed by the node's own bookkeeping.
4211        let run_id = self.state.id.clone();
4212        let prompts = self.state.config.prompts.clone();
4213        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4214            return Ok(());
4215        }
4216        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4217        if viable.len() == 1 {
4218            // Recorded so this is a one-time event: `judgements` stays empty
4219            // either way, which without this flag is indistinguishable from
4220            // "not yet judged" on the next reentry — and status is left
4221            // untouched, so a later node's conclusion (e.g. `Blocked` after
4222            // the review budget ran out) survives a resume instead of being
4223            // clobbered back to `Judging` by this node running again.
4224            self.state.judge_skipped = true;
4225            self.state.event(
4226                "judge",
4227                format!(
4228                    "only candidate {} produced a change; judging skipped",
4229                    viable[0].label
4230                ),
4231            );
4232            self.state.save()?;
4233            return Ok(());
4234        }
4235        self.state.status = RunStatus::Judging;
4236
4237        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4238        let language = self.state.config.graph.language.clone();
4239        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4240        let sessions = self.state.config.graph.sessions;
4241        let artifacts = agent::artifacts_dir(&self.state.dir());
4242        let root = self.state.worktree_root();
4243        let base_short = short(&self.state.base_commit);
4244
4245        let mut jobs = Vec::new();
4246        let mut orders = Vec::new();
4247        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4248            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4249            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4250            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4251            let seat_key = format!("judge-{}", j + 1);
4252            let seat = self.seat(&seat_key, &spec.id);
4253            jobs.push(SeatJob {
4254                prompt: prompt::judge(
4255                    &self.state.instruction,
4256                    &views,
4257                    self.roles.judges.len(),
4258                    &base_short,
4259                    &language,
4260                ),
4261                spec,
4262                seat,
4263                cwd: root.join(format!("judge-{}", j + 1)),
4264                timeout,
4265                allow_write: false,
4266                sessions,
4267                artifacts: artifacts.clone(),
4268                stem: format!("judge-{}", j + 1),
4269                handover: None,
4270            });
4271        }
4272
4273        self.state.event(
4274            "judge",
4275            format!(
4276                "{} judges ranking {} candidates blind",
4277                jobs.len(),
4278                viable.len()
4279            ),
4280        );
4281        let labels_for_check = labels.clone();
4282        let mut quota_losses = Vec::new();
4283        let cache = self.state.config.cache_dir();
4284        let ctx = WaveCtx {
4285            carry_seats: false,
4286            pauses: Some((&self.pause, &self.interrupt)),
4287            run: &run_id,
4288            node: "judge",
4289            prompts: &prompts,
4290            cache: cache.as_deref(),
4291            round: None,
4292        };
4293        let results = ask_json_wave::<Ranking>(
4294            jobs,
4295            Arc::clone(&self.sem),
4296            self.state.config.graph.retries,
4297            &self.roles.judge_roster,
4298            &ctx,
4299            &mut quota_losses,
4300            &mut self.state,
4301            &move |r: &Ranking| r.validate(&labels_for_check),
4302        )
4303        .await;
4304        if self.state.resource_block.is_some() {
4305            return self.stop_for_resource();
4306        }
4307        self.state.quota.extend(quota_losses);
4308
4309        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4310            let agent_id = seat.agent.clone();
4311            self.state.seats.insert(seat.key.clone(), seat);
4312            let mut record = Judgement {
4313                judge: j + 1,
4314                seat: format!("judge-{}", j + 1),
4315                agent: agent_id,
4316                ranking: Vec::new(),
4317                reasons: BTreeMap::new(),
4318                confidence: None,
4319                strengths: BTreeMap::new(),
4320                order: orders[j].clone(),
4321                failed: None,
4322                duration_ms: 0,
4323            };
4324            match res {
4325                Ok((ranking, out)) => {
4326                    record.ranking = ranking.normalized();
4327                    record.reasons = ranking.reasons;
4328                    record.strengths = ranking.strengths;
4329                    record.confidence = ranking.confidence;
4330                    record.duration_ms = out.duration_ms;
4331                    self.state.event(
4332                        "judge",
4333                        format!(
4334                            "judge {} ranked {}",
4335                            j + 1,
4336                            record.ranking.iter().collect::<String>()
4337                        ),
4338                    );
4339                }
4340                Err(e) => {
4341                    record.failed = Some(e.to_string());
4342                    self.state
4343                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4344                }
4345            }
4346            self.state.judgements.push(record);
4347            self.state.save()?;
4348        }
4349        Ok(())
4350    }
4351
4352    // ---------------------------------------------------------- deliberate
4353
4354    async fn deliberate(&mut self) -> Result<()> {
4355        if self.hold_base_sync().await? {
4356            return Ok(());
4357        }
4358        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4359        // agent files with `magi task add` name the run that paid for it. The
4360        // prompt overlay is cloned alongside it because the waves borrow it
4361        // while `self` is mutably borrowed by the node's own bookkeeping.
4362        let run_id = self.state.id.clone();
4363        let prompts = self.state.config.prompts.clone();
4364        let rounds = self.state.config.graph.deliberate_rounds;
4365        // Resume unfinished rounds after an outage, but never reopen a tally.
4366        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4367            return Ok(());
4368        }
4369        let tops: Vec<char> = self
4370            .state
4371            .judgements
4372            .iter()
4373            .filter_map(|j| j.ranking.first().copied())
4374            .collect();
4375        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4376            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4377                self.state.event(
4378                    "deliberate",
4379                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4380                );
4381            }
4382            self.state.status = RunStatus::Voting;
4383            self.state.save()?;
4384            return Ok(());
4385        }
4386
4387        self.state.status = RunStatus::Deliberating;
4388        self.state.event(
4389            "deliberate",
4390            format!(
4391                "split: first choices were {} — opening {rounds} round(s)",
4392                tops.iter().collect::<String>()
4393            ),
4394        );
4395
4396        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4397        let language = self.state.config.graph.language.clone();
4398        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4399        let sessions = self.state.config.graph.sessions;
4400        let artifacts = agent::artifacts_dir(&self.state.dir());
4401        let root = self.state.worktree_root();
4402        let base_short = short(&self.state.base_commit);
4403
4404        // Judges argue in sequence so that a turn can answer the one before it;
4405        // that is the difference between deliberation and three parallel
4406        // monologues.
4407        for round in self.state.deliberation.len() + 1..=rounds {
4408            let mut turns: Vec<DeliberationTurn> = Vec::new();
4409            let mut round_losses = Vec::new();
4410            let mut asked = 0;
4411            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4412                if self.state.judgements[j].failed.is_some() {
4413                    continue;
4414                }
4415                let seat_key = format!("judge-{}", j + 1);
4416                let spec = self.occupant(&seat_key, spec);
4417                let mut seat = self.seat(&seat_key, &spec.id);
4418                let transcript = self.transcript(&turns, j);
4419                let build = |context: Option<&str>| {
4420                    prompt::deliberate(
4421                        &self.state.instruction,
4422                        context,
4423                        &transcript,
4424                        round,
4425                        rounds,
4426                        &language,
4427                    )
4428                };
4429                let block = self.candidate_block(&viable, &base_short);
4430                let full = build(Some(&block));
4431                let text = if has_context(&spec, &seat, sessions) {
4432                    build(None)
4433                } else {
4434                    full.clone()
4435                };
4436                let job = SeatJob {
4437                    spec,
4438                    seat: seat.clone(),
4439                    prompt: text,
4440                    cwd: root.join(format!("judge-{}", j + 1)),
4441                    timeout,
4442                    allow_write: false,
4443                    sessions,
4444                    artifacts: artifacts.clone(),
4445                    stem: format!("delib-{round}-judge-{}", j + 1),
4446                    handover: Some(full),
4447                };
4448                let cache = self.state.config.cache_dir();
4449                let ctx = WaveCtx {
4450                    carry_seats: false,
4451                    pauses: Some((&self.pause, &self.interrupt)),
4452                    run: &run_id,
4453                    node: "deliberate",
4454                    prompts: &prompts,
4455                    cache: cache.as_deref(),
4456                    round: None,
4457                };
4458                // A turn is never nudged (`retries` 0): a failed seat is
4459                // handed to the next roster agent, which gets the full
4460                // context. An empty answer is a turn, not a failure.
4461                let mut losses = Vec::new();
4462                asked += 1;
4463                let mut results = ask_wave_with::<String>(
4464                    vec![job],
4465                    Arc::clone(&self.sem),
4466                    0,
4467                    &self.roles.judge_roster,
4468                    &ctx,
4469                    &mut losses,
4470                    &mut self.state,
4471                    &|text: &str| {
4472                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4473                    },
4474                )
4475                .await;
4476                if self.state.resource_block.is_some() {
4477                    return self.stop_for_resource();
4478                }
4479                round_losses.extend(losses.iter().cloned());
4480                self.state.quota.extend(losses);
4481                let (updated, res, _) = results.pop().expect("one job in, one result out");
4482                seat = updated;
4483                let agent_id = seat.agent.clone();
4484                self.state.seats.insert(seat.key.clone(), seat);
4485                let body = match res {
4486                    Ok((body, _)) => body,
4487                    // Skip the seat; a CLI's raw error JSON is never read as
4488                    // this judge's position.
4489                    Err(e) => {
4490                        self.state
4491                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4492                        continue;
4493                    }
4494                };
4495                let tentative = verdict::extract_json::<Position>(&body)
4496                    .ok()
4497                    .and_then(|p| p.tentative)
4498                    .and_then(|s| s.trim().chars().next())
4499                    .map(|c| c.to_ascii_uppercase());
4500                self.state.event(
4501                    "deliberate",
4502                    format!(
4503                        "round {round}: judge {} now favours {}",
4504                        j + 1,
4505                        tentative.map_or("—".to_owned(), |c| c.to_string())
4506                    ),
4507                );
4508                turns.push(DeliberationTurn {
4509                    judge: j + 1,
4510                    agent: agent_id,
4511                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4512                    tentative,
4513                });
4514            }
4515            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4516                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4517                return self.stop_for_resource();
4518            }
4519            self.state
4520                .deliberation
4521                .push(DeliberationRound { round, turns });
4522            self.state.save()?;
4523        }
4524
4525        self.state.status = RunStatus::Voting;
4526        self.state.save()?;
4527        Ok(())
4528    }
4529
4530    // ---------------------------------------------------------------- vote
4531
4532    async fn vote(&mut self) -> Result<()> {
4533        if self.hold_base_sync().await? {
4534            return Ok(());
4535        }
4536        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4537        // agent files with `magi task add` name the run that paid for it. The
4538        // prompt overlay is cloned alongside it because the waves borrow it
4539        // while `self` is mutably borrowed by the node's own bookkeeping.
4540        let run_id = self.state.id.clone();
4541        let prompts = self.state.config.prompts.clone();
4542        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4543            return Ok(());
4544        }
4545        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4546        if viable.len() == 1 {
4547            return Ok(());
4548        }
4549        self.state.status = RunStatus::Voting;
4550
4551        let language = self.state.config.graph.language.clone();
4552        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4553        let sessions = self.state.config.graph.sessions;
4554        let artifacts = agent::artifacts_dir(&self.state.dir());
4555        let root = self.state.worktree_root();
4556        let base_short = short(&self.state.base_commit);
4557        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4558
4559        let mut jobs = Vec::new();
4560        let mut seats_at = Vec::new();
4561        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4562            if self
4563                .state
4564                .judgements
4565                .get(j)
4566                .is_some_and(|r| r.failed.is_some())
4567            {
4568                continue;
4569            }
4570            let seat_key = format!("judge-{}", j + 1);
4571            let spec = self.occupant(&seat_key, spec);
4572            let seat = self.seat(&seat_key, &spec.id);
4573            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4574            let text = if has_context(&spec, &seat, sessions) {
4575                prompt::final_vote(&viable, &language)
4576            } else {
4577                full.clone()
4578            };
4579            jobs.push(SeatJob {
4580                spec,
4581                seat,
4582                prompt: text,
4583                cwd: root.join(format!("judge-{}", j + 1)),
4584                timeout,
4585                allow_write: false,
4586                sessions,
4587                artifacts: artifacts.clone(),
4588                stem: format!("vote-judge-{}", j + 1),
4589                handover: Some(full),
4590            });
4591            seats_at.push(j);
4592        }
4593
4594        self.state.event(
4595            "vote",
4596            format!(
4597                "collecting {} final votes one by one, privately",
4598                jobs.len()
4599            ),
4600        );
4601        let allowed = viable.clone();
4602        let mut quota_losses = Vec::new();
4603        let cache = self.state.config.cache_dir();
4604        let ctx = WaveCtx {
4605            carry_seats: false,
4606            pauses: Some((&self.pause, &self.interrupt)),
4607            run: &run_id,
4608            node: "vote",
4609            prompts: &prompts,
4610            cache: cache.as_deref(),
4611            round: None,
4612        };
4613        let results = ask_json_wave::<FinalVote>(
4614            jobs,
4615            Arc::clone(&self.sem),
4616            self.state.config.graph.retries,
4617            &self.roles.judge_roster,
4618            &ctx,
4619            &mut quota_losses,
4620            &mut self.state,
4621            &move |v: &FinalVote| match v.label() {
4622                Some(c) if allowed.contains(&c) => Ok(()),
4623                other => bail!("vote {other:?} is not one of {allowed:?}"),
4624            },
4625        )
4626        .await;
4627        if self.state.resource_block.is_some() {
4628            return self.stop_for_resource();
4629        }
4630        self.state.quota.extend(quota_losses);
4631
4632        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4633            let agent_id = seat.agent.clone();
4634            self.state.seats.insert(seat.key.clone(), seat);
4635            let initial = self
4636                .state
4637                .judgements
4638                .get(j)
4639                .and_then(|r| r.ranking.first().copied());
4640            let mut record = VoteRecord {
4641                judge: j + 1,
4642                agent: agent_id,
4643                vote: None,
4644                reason: String::new(),
4645                changed: false,
4646            };
4647            match res {
4648                Ok((v, _)) => {
4649                    record.vote = v.label();
4650                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4651                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4652                    self.state.event(
4653                        "vote",
4654                        format!(
4655                            "judge {} voted {}{}",
4656                            j + 1,
4657                            record.vote.unwrap_or('?'),
4658                            if record.changed { " (changed)" } else { "" }
4659                        ),
4660                    );
4661                }
4662                Err(e) => {
4663                    self.state
4664                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4665                }
4666            }
4667            self.state.votes.push(record);
4668            self.state.save()?;
4669        }
4670        Ok(())
4671    }
4672
4673    // --------------------------------------------------------------- tally
4674
4675    fn tally(&mut self) -> Result<()> {
4676        if self.state.tally.is_some() {
4677            return Ok(());
4678        }
4679        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4680        let tops: Vec<char> = self
4681            .state
4682            .judgements
4683            .iter()
4684            .filter_map(|j| j.ranking.first().copied())
4685            .collect();
4686        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4687
4688        // A judge whose private vote failed still counted once, in the initial
4689        // ranking; using it beats discarding a whole seat.
4690        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4691        let mut cast: Vec<char> = Vec::new();
4692        for (i, j) in self.state.judgements.iter().enumerate() {
4693            let vote = self
4694                .state
4695                .votes
4696                .iter()
4697                .find(|v| v.judge == i + 1)
4698                .and_then(|v| v.vote)
4699                .or_else(|| j.ranking.first().copied());
4700            if let Some(v) = vote {
4701                *first_choice.entry(v).or_insert(0) += 1;
4702                cast.push(v);
4703            }
4704        }
4705
4706        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4707        for j in &self.state.judgements {
4708            let n = j.ranking.len();
4709            for (pos, label) in j.ranking.iter().enumerate() {
4710                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4711            }
4712        }
4713
4714        let best = first_choice.values().copied().max().unwrap_or(0);
4715        let mut leaders: Vec<char> = first_choice
4716            .iter()
4717            .filter(|(_, v)| **v == best)
4718            .map(|(k, _)| *k)
4719            .collect();
4720        let mut tie_break = None;
4721        if leaders.len() > 1 {
4722            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4723            let borda_leaders: Vec<char> = leaders
4724                .iter()
4725                .copied()
4726                .filter(|l| borda[l] == top_borda)
4727                .collect();
4728            tie_break = Some(if borda_leaders.len() == 1 {
4729                format!(
4730                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4731                    leaders.len()
4732                )
4733            } else {
4734                format!(
4735                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4736                    leaders.len()
4737                )
4738            });
4739            leaders = borda_leaders;
4740            leaders.sort_unstable();
4741        }
4742        let winner = *leaders
4743            .first()
4744            .or(viable.first())
4745            .context("no candidate to declare a winner from")?;
4746
4747        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4748        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4749        let deliberated = !self.state.deliberation.is_empty();
4750
4751        // Whose verdict is this? A rate-limited seat is absent even if it
4752        // ranked before the limit hit, so presence is measured against the
4753        // recorded losses, not just "did a ranking ever appear".
4754        let quota_seats: std::collections::BTreeSet<&str> =
4755            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4756        let mut present = 0usize;
4757        for (i, j) in self.state.judgements.iter().enumerate() {
4758            if quota_seats.contains(j.seat.as_str()) {
4759                continue;
4760            }
4761            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4762            let voted = self
4763                .state
4764                .votes
4765                .iter()
4766                .any(|v| v.judge == i + 1 && v.vote.is_some());
4767            if ranked || voted {
4768                present += 1;
4769            }
4770        }
4771        // Strict majority of the configured panel. A bare majority is real
4772        // signal we can act on, while a minority verdict must never stand in
4773        // for a healthy one. A one-candidate run needs no panel at all, and
4774        // `judges` stays `0` rather than the roster size a panel that never
4775        // sat would otherwise be credited with.
4776        let needs_quorum = viable.len() > 1;
4777        let judges_total = if needs_quorum {
4778            self.roles.judges.len()
4779        } else {
4780            0
4781        };
4782        let quorum = if needs_quorum {
4783            judges_total / 2 + 1
4784        } else {
4785            0
4786        };
4787        let met_quorum = !needs_quorum || present >= quorum;
4788        let uncontested = (!needs_quorum).then(|| {
4789            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4790        });
4791
4792        self.state.event(
4793            "tally",
4794            match &uncontested {
4795                Some(reason) => format!("winner {winner} — {reason}"),
4796                None => format!(
4797                    "winner {winner} — votes {} | initial {} | {} changed | \
4798                     {present}/{judges_total} judges{}",
4799                    first_choice
4800                        .iter()
4801                        .map(|(k, v)| format!("{k}:{v}"))
4802                        .collect::<Vec<_>>()
4803                        .join(" "),
4804                    if unanimous_initial {
4805                        "unanimous"
4806                    } else {
4807                        "split"
4808                    },
4809                    changed_votes,
4810                    if met_quorum {
4811                        String::new()
4812                    } else {
4813                        format!(" — below quorum ({quorum} required)")
4814                    },
4815                ),
4816            },
4817        );
4818        if !met_quorum {
4819            self.state.event(
4820                "stall",
4821                format!(
4822                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4823                     the run stops here, resumable"
4824                ),
4825            );
4826        }
4827        self.state.tally = Some(Tally {
4828            first_choice,
4829            borda,
4830            winner,
4831            rankings: tops.len(),
4832            unanimous_initial,
4833            deliberated,
4834            changed_votes,
4835            unanimous_final,
4836            tie_break,
4837            judges: judges_total,
4838            present,
4839            quorum,
4840            met_quorum,
4841            uncontested,
4842        });
4843        self.state.status = if met_quorum {
4844            RunStatus::Reviewing
4845        } else {
4846            RunStatus::Stalled
4847        };
4848        self.state.save()?;
4849        Ok(())
4850    }
4851
4852    // ------------------------------------------------------------- recover
4853
4854    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4855    /// resumed toward completion once the transient cause clears.
4856    ///
4857    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4858    /// it toward the quorum, which is exactly the set of seats whose absence
4859    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4860    /// not depend on which node happened to hit the limit), or an ordinary
4861    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4862    /// seat is never disturbed.
4863    ///
4864    /// A seat that now answers with a usable ranking is "recovered": its
4865    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4866    /// `tally` counts it present again), and its vote re-collected. A seat that
4867    /// still fails keeps its loss and stays absent.
4868    ///
4869    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4870    /// to review/gate/merge), `false` when it is still below quorum (the run
4871    /// stays `Stalled`, still resumable for a later retry).
4872    #[allow(clippy::too_many_lines)]
4873    async fn recover_stall(&mut self) -> Result<bool> {
4874        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4875        // agent files with `magi task add` name the run that paid for it. The
4876        // prompt overlay is cloned alongside it because the waves borrow it
4877        // while `self` is mutably borrowed by the node's own bookkeeping.
4878        let run_id = self.state.id.clone();
4879        let prompts = self.state.config.prompts.clone();
4880        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4881        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4882        // is what keeps a non-quota collapse — or a quota loss recorded at the
4883        // deliberate node — from being a permanent dead-end on `--resume`.
4884        let quota_seats: BTreeSet<&str> =
4885            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4886        let absent: Vec<String> = self
4887            .state
4888            .judgements
4889            .iter()
4890            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4891            .map(|j| j.seat.clone())
4892            .collect();
4893        if absent.is_empty() {
4894            return Ok(false);
4895        }
4896        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4897        if viable.len() <= 1 {
4898            return Ok(false);
4899        }
4900        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4901        let language = self.state.config.graph.language.clone();
4902        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4903        let sessions = self.state.config.graph.sessions;
4904        let artifacts = agent::artifacts_dir(&self.state.dir());
4905        let root = self.state.worktree_root();
4906        let base_short = short(&self.state.base_commit);
4907        let candidates: Vec<Candidate> = viable.clone();
4908
4909        // Map each absent seat key to its 0-based position in `roles.judges`.
4910        let mut positions: Vec<usize> = absent
4911            .iter()
4912            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4913            .collect();
4914        if positions.is_empty() {
4915            return Ok(false);
4916        }
4917        positions.sort_unstable();
4918        positions.dedup();
4919
4920        // Re-rank the lost seats, one blind prompt each.
4921        let mut judge_jobs = Vec::new();
4922        for &j in &positions {
4923            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4924            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4925            let seat_key = format!("judge-{}", j + 1);
4926            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4927            let seat = self.seat(&seat_key, &spec.id);
4928            judge_jobs.push(SeatJob {
4929                spec,
4930                seat,
4931                prompt: prompt::judge(
4932                    &self.state.instruction,
4933                    &views,
4934                    self.roles.judges.len(),
4935                    &base_short,
4936                    &language,
4937                ),
4938                cwd: root.join(seat_key),
4939                timeout,
4940                allow_write: false,
4941                sessions,
4942                artifacts: artifacts.clone(),
4943                stem: format!("judge-{}-recover", j + 1),
4944                handover: None,
4945            });
4946        }
4947
4948        let labels_for_check = labels.clone();
4949        let mut judge_losses = Vec::new();
4950        let retries = self.state.config.graph.retries;
4951        let cache = self.state.config.cache_dir();
4952        let ctx = WaveCtx {
4953            carry_seats: false,
4954            pauses: Some((&self.pause, &self.interrupt)),
4955            run: &run_id,
4956            node: "judge",
4957            prompts: &prompts,
4958            cache: cache.as_deref(),
4959            round: None,
4960        };
4961        let results = ask_json_wave::<Ranking>(
4962            judge_jobs,
4963            Arc::clone(&self.sem),
4964            retries,
4965            &self.roles.judge_roster,
4966            &ctx,
4967            &mut judge_losses,
4968            &mut self.state,
4969            &move |r: &Ranking| r.validate(&labels_for_check),
4970        )
4971        .await;
4972        if self.state.resource_block.is_some() {
4973            self.stop_for_resource()?;
4974            return Ok(false);
4975        }
4976
4977        // Refresh the judgement of every seat that ranked again.
4978        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4979        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4980            let agent_id = seat.agent.clone();
4981            self.state.seats.insert(seat.key.clone(), seat);
4982            let record = &mut self.state.judgements[j];
4983            match res {
4984                Ok((ranking, out)) => {
4985                    record.agent = agent_id;
4986                    record.ranking = ranking.normalized();
4987                    record.reasons = ranking.reasons;
4988                    record.strengths = ranking.strengths;
4989                    record.confidence = ranking.confidence;
4990                    record.failed = None;
4991                    record.duration_ms = out.duration_ms;
4992                    recovered.insert(j);
4993                    self.state.event(
4994                        "recover",
4995                        format!("judge {} ranked again after the limit", j + 1),
4996                    );
4997                }
4998                Err(e) => {
4999                    self.state
5000                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5001                }
5002            }
5003        }
5004
5005        // Re-ask the votes of the seats that recovered a ranking.
5006        let mut vote_jobs = Vec::new();
5007        let mut vote_pos: Vec<usize> = Vec::new();
5008        for &j in &recovered {
5009            let seat_key = format!("judge-{}", j + 1);
5010            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5011            let seat = self.seat(&seat_key, &spec.id);
5012            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5013            let text = if has_context(&spec, &seat, sessions) {
5014                prompt::final_vote(&labels, &language)
5015            } else {
5016                full.clone()
5017            };
5018            vote_jobs.push(SeatJob {
5019                spec,
5020                seat,
5021                prompt: text,
5022                cwd: root.join(seat_key),
5023                timeout,
5024                allow_write: false,
5025                sessions,
5026                artifacts: artifacts.clone(),
5027                stem: format!("vote-judge-{}-recover", j + 1),
5028                handover: Some(full),
5029            });
5030            vote_pos.push(j);
5031        }
5032        let allowed = labels.clone();
5033        let mut vote_losses = Vec::new();
5034        let vote_retries = self.state.config.graph.retries;
5035        let vote_cache = self.state.config.cache_dir();
5036        let ctx = WaveCtx {
5037            carry_seats: false,
5038            pauses: Some((&self.pause, &self.interrupt)),
5039            run: &run_id,
5040            node: "vote",
5041            prompts: &prompts,
5042            cache: vote_cache.as_deref(),
5043            round: None,
5044        };
5045        let votes = ask_json_wave::<FinalVote>(
5046            vote_jobs,
5047            Arc::clone(&self.sem),
5048            vote_retries,
5049            &self.roles.judge_roster,
5050            &ctx,
5051            &mut vote_losses,
5052            &mut self.state,
5053            &move |v: &FinalVote| match v.label() {
5054                Some(c) if allowed.contains(&c) => Ok(()),
5055                other => bail!("vote {other:?} is not one of {allowed:?}"),
5056            },
5057        )
5058        .await;
5059        if self.state.resource_block.is_some() {
5060            self.stop_for_resource()?;
5061            return Ok(false);
5062        }
5063        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5064            let agent_id = seat.agent.clone();
5065            self.state.seats.insert(seat.key.clone(), seat);
5066            match res {
5067                Ok((v, _)) => {
5068                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5069                        rec.vote = v.label();
5070                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5071                    } else {
5072                        self.state.votes.push(VoteRecord {
5073                            judge: j + 1,
5074                            agent: agent_id,
5075                            vote: v.label(),
5076                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5077                            changed: false,
5078                        });
5079                    }
5080                    self.state.event(
5081                        "recover",
5082                        format!("judge {} voted again after the limit", j + 1),
5083                    );
5084                }
5085                Err(e) => {
5086                    self.state
5087                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5088                }
5089            }
5090        }
5091
5092        // A seat that ranked again is present even if its re-vote failed —
5093        // `tally` falls back to the initial ranking's first choice — so clear
5094        // its quota loss. Seats that still fail keep theirs and stay absent.
5095        let recovered_keys: BTreeSet<String> = recovered
5096            .iter()
5097            .map(|&j| format!("judge-{}", j + 1))
5098            .collect();
5099        self.state
5100            .quota
5101            .retain(|q| !recovered_keys.contains(&q.seat));
5102        // A seat that hit the limit again is a fresh loss, not the old one:
5103        // replace the stale entry so the history stays one-per-seat and the
5104        // daemon can tell this attempt's loss from a previous session's.
5105        for loss in judge_losses.into_iter().chain(vote_losses) {
5106            if recovered_keys.contains(&loss.seat) {
5107                continue;
5108            }
5109            self.state.quota.retain(|q| q.seat != loss.seat);
5110            self.state.quota.push(loss);
5111        }
5112
5113        // Recompute the verdict from the refreshed panel.
5114        self.state.tally = None;
5115        self.tally()?;
5116        Ok(self
5117            .state
5118            .tally
5119            .as_ref()
5120            .map(|t| t.met_quorum)
5121            .unwrap_or(false))
5122    }
5123
5124    // ---------------------------------------------------------------- graft
5125
5126    /// Port the strengths the judges attributed to the losing candidates onto
5127    /// the winner, once, between the tally and the review loop.
5128    ///
5129    /// Best-effort by construction: it returns nothing and fails nothing. A
5130    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5131    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5132    /// the run carries on as if the phase were off. See [`graft`] for the
5133    /// decisions and `AGENTS.md` for the invariants.
5134    ///
5135    /// The one exception is a rollback that could not be confirmed: the
5136    /// rejected commit may still be the winner's tip, so the run is blocked
5137    /// (resumable; the record stays `Running`, which makes a resume retry the
5138    /// restore) instead of reviewing, gating and merging it.
5139    async fn graft(&mut self) -> Result<()> {
5140        let Err(e) = self.graft_inner().await else {
5141            return Ok(());
5142        };
5143        if e.is::<crate::repo_lock::ResourceBlocked>() {
5144            return Err(e);
5145        }
5146        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5147            self.state.status = RunStatus::Blocked;
5148            self.state.event("graft", format!("blocked: {e:#}"));
5149            self.state.save()?;
5150            return Err(e);
5151        }
5152        // An error after the `Running` record was saved may have left the
5153        // fixer's work in the tree: the record must not stay unsettled
5154        // (a later resume would reset past the review fixes), so confirm the
5155        // restore now, or block.
5156        if let Some(rec) = self.state.graft.clone()
5157            && !rec.outcome.settled()
5158        {
5159            if let Some(winner) = self.state.winner().cloned() {
5160                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5161                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5162                        return Err(re);
5163                    }
5164                    self.state.status = RunStatus::Blocked;
5165                    self.state.event("graft", format!("blocked: {re:#}"));
5166                    self.state.save()?;
5167                    return Err(re);
5168                }
5169            }
5170            if let Some(g) = self.state.graft.as_mut() {
5171                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5172            }
5173        }
5174        self.state.event("graft", format!("skipped: {e:#}"));
5175        if let Err(e) = self.state.save() {
5176            tracing::warn!("save after graft: {e:#}");
5177        }
5178        Ok(())
5179    }
5180
5181    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5182    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5183    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5184        let _coordination = self.coordinate(wt).await?;
5185        crate::recovery::restore_repair(wt, pre)
5186            .await
5187            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5188    }
5189
5190    /// A skip is a run event, recorded once however often the node is re-entered.
5191    fn graft_skipped(&mut self, why: &str) {
5192        let message = format!("skipped: {why}");
5193        if !self
5194            .state
5195            .events
5196            .iter()
5197            .any(|e| e.node == "graft" && e.message == message)
5198        {
5199            self.state.event("graft", message);
5200        }
5201    }
5202
5203    async fn graft_inner(&mut self) -> Result<()> {
5204        // A round that was started and never finished (crash, kill): the
5205        // fixer may have left anything in the tree, so put the winner back.
5206        if let Some(rec) = self.state.graft.clone()
5207            && !rec.outcome.settled()
5208        {
5209            // Reviews exist only if the graft ended without its record being
5210            // settled (a swallowed error): the tree has moved on since, and
5211            // a reset to `pre` would discard the review fixes.
5212            if self.state.reviews.is_empty()
5213                && let Some(winner) = self.state.winner().cloned()
5214            {
5215                self.graft_restore(&winner.worktree, &rec.pre).await?;
5216            }
5217            if rec.outcome == GraftOutcome::WaitingForRestore {
5218                self.state.graft = None;
5219                self.state.save()?;
5220            } else {
5221                if let Some(g) = self.state.graft.as_mut() {
5222                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5223                }
5224                self.state.event(
5225                    "graft",
5226                    "rolled back: the previous round was interrupted; the winner is untouched",
5227                );
5228                self.state.save()?;
5229                return Ok(());
5230            }
5231        }
5232        let plan = match graft::plan(&self.state) {
5233            Ok(plan) => plan,
5234            Err(skip) => {
5235                if skip != graft::Skip::AlreadyDone {
5236                    self.graft_skipped(skip.reason());
5237                    self.state.save()?;
5238                }
5239                return Ok(());
5240            }
5241        };
5242        let Some(winner) = self.state.winner().cloned() else {
5243            return Ok(());
5244        };
5245        let wt = winner.worktree.clone();
5246        if !git::is_clean(&wt).await? {
5247            self.graft_skipped("the winner's worktree has uncommitted changes");
5248            self.state.save()?;
5249            return Ok(());
5250        }
5251        let pre = git::rev_parse(&wt, "HEAD").await?;
5252        // Saved before the fixer is called: a stop from here on is repaired
5253        // by the branch above on the next entry.
5254        self.state.graft = Some(GraftRecord {
5255            pre: pre.clone(),
5256            post: None,
5257            lines: None,
5258            limit: None,
5259            agent: None,
5260            outcome: GraftOutcome::Running,
5261            requested: graft::requested(&plan),
5262            adoption: None,
5263            adoption_error: None,
5264        });
5265        self.state.event(
5266            "graft",
5267            format!(
5268                "porting strengths of candidate(s) {} onto {}",
5269                plan.strengths
5270                    .iter()
5271                    .map(|(l, _, _)| l.to_string())
5272                    .collect::<Vec<_>>()
5273                    .join(", "),
5274                plan.winner
5275            ),
5276        );
5277        self.state.save()?;
5278
5279        let fix_prompt = prompt::graft(
5280            &self.state.instruction,
5281            plan.winner,
5282            &plan.strengths,
5283            &self.state.config.graph.language,
5284        );
5285        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5286        let sessions = self.state.config.graph.sessions;
5287        let artifacts = agent::artifacts_dir(&self.state.dir());
5288        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5289        let (_, seat, out) = self
5290            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5291                SeatJob {
5292                    prompt: fix_prompt.clone(),
5293                    spec,
5294                    seat,
5295                    cwd: wt.clone(),
5296                    timeout,
5297                    allow_write: true,
5298                    sessions,
5299                    artifacts: artifacts.clone(),
5300                    stem: "graft".to_owned(),
5301                    handover: None,
5302                }
5303            })
5304            .await;
5305        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5306            // Preserve the need to restore earlier fallback edits without
5307            // confusing an unstarted seat with an interrupted invocation.
5308            self.state.graft.as_mut().expect("graft record").outcome =
5309                GraftOutcome::WaitingForRestore;
5310            return self.stop_for_resource();
5311        }
5312        let mut why: Option<String> = None;
5313        match &out {
5314            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5315                why = Some("the fixer produced nothing usable".to_owned());
5316            }
5317            AgentOutcome::Ok(_) => {}
5318            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5319            AgentOutcome::Quota(o) => {
5320                self.state.quota.push(QuotaLoss::from_report(
5321                    seat.key.clone(),
5322                    "graft",
5323                    o.quota.as_ref(),
5324                ));
5325                why = Some("rate limited (quota)".to_owned());
5326            }
5327            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5328                why = Some(format!(
5329                    "the fixer failed: {}",
5330                    e.lines()
5331                        .next()
5332                        .unwrap_or("")
5333                        .chars()
5334                        .take(160)
5335                        .collect::<String>()
5336                ));
5337            }
5338        }
5339        let agent_id = seat.agent.clone();
5340        self.state.seats.insert(seat.key.clone(), seat);
5341
5342        let mut post = None;
5343        let mut lines = None;
5344        let _coordination = self.coordinate(&wt).await?;
5345        if why.is_none() {
5346            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5347            if let Ok(r) = &rescued {
5348                self.state.note_withheld("graft", &r.withheld);
5349            }
5350            let head = git::rev_parse(&wt, "HEAD").await?;
5351            // What is measured must be what gets reviewed and gated: a failed
5352            // rescue, or anything still uncommitted (withheld lockfiles
5353            // aside, which are never part of the tree), rejects the graft.
5354            let dirty = match &rescued {
5355                Ok(r) => git::status_porcelain(&wt)
5356                    .await
5357                    .map(|st| {
5358                        st.lines().any(|l| {
5359                            !r.withheld
5360                                .iter()
5361                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5362                        })
5363                    })
5364                    .unwrap_or(true),
5365                Err(_) => true,
5366            };
5367            if dirty {
5368                why = Some("the fixer left changes that could not be committed".to_owned());
5369            } else if head == pre {
5370                why = Some("the fixer changed nothing".to_owned());
5371            } else {
5372                lines = git::changed_lines(&wt, &pre, &head).await;
5373                post = Some(head);
5374            }
5375        }
5376        let (adoption, adoption_error) = match &out {
5377            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5378            _ => (None, None),
5379        };
5380        let requested = graft::requested(&plan);
5381        let outcome = match why {
5382            None => {
5383                self.state.event(
5384                    "graft",
5385                    format!(
5386                        "applied: {}",
5387                        lines.map_or_else(
5388                            || "changed lines unavailable".to_owned(),
5389                            |n| format!("{n} changed lines")
5390                        )
5391                    ),
5392                );
5393                GraftOutcome::Applied
5394            }
5395            Some(why) => {
5396                // Not settled until the restore is confirmed: the record
5397                // stays `Running`, so a resume retries it.
5398                crate::recovery::restore_repair(&wt, &pre)
5399                    .await
5400                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5401                self.state.event(
5402                    "graft",
5403                    format!("rolled back: {why}; the winner is untouched"),
5404                );
5405                GraftOutcome::RolledBack(why)
5406            }
5407        };
5408        self.state.graft = Some(GraftRecord {
5409            pre,
5410            post,
5411            lines,
5412            limit: None,
5413            agent: Some(agent_id),
5414            outcome,
5415            requested,
5416            adoption,
5417            adoption_error,
5418        });
5419        self.state.save()?;
5420        Ok(())
5421    }
5422
5423    // ----------------------------------------------------------------- fold
5424
5425    async fn fold_losers(&mut self) -> Result<()> {
5426        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5427            return Ok(());
5428        };
5429        if !self.state.candidate_preservation.is_empty() {
5430            bail!("candidate preservation incomplete; refusing cleanup");
5431        }
5432        let repo = self.state.repo.clone();
5433        let _coordination = self.coordinate(&repo).await?;
5434        let home = crate::run::home();
5435        let root = self.state.worktree_root();
5436        let isolated = crate::build_target::isolated(&self.state.config);
5437        let mut folded = Vec::new();
5438        for i in 0..self.state.candidates.len() {
5439            let c = &self.state.candidates[i];
5440            if c.label == winner || c.folded {
5441                continue;
5442            }
5443            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5444            let target = fold_target(&home, &root, &wt, isolated);
5445            remove_preserved_worktree(&repo, &wt).await?;
5446            reclaim_fold_target(&home, target);
5447            if git::branch_exists(&repo, &branch).await?
5448                && !git::branch_delete(&repo, &branch).await?
5449            {
5450                bail!("candidate branch removal refused");
5451            }
5452            self.state.candidates[i].folded = true;
5453            self.state.save()?;
5454            folded.push(label.to_string());
5455        }
5456        // The judges are finished; their checkouts are pure cost from here.
5457        for j in 1..=self.roles.judges.len() {
5458            let wt = root.join(format!("judge-{j}"));
5459            if wt.exists() {
5460                let target = fold_target(&home, &root, &wt, isolated);
5461                remove_read_seat_worktree(&mut self.state, &wt).await?;
5462                reclaim_fold_target(&home, target);
5463                self.state.save()?;
5464            }
5465        }
5466        // The design-deliberation stage is finished by the time a tally
5467        // exists — same reasoning as the judges above.
5468        if self.state.config.graph.advise {
5469            for k in 1..=self.state.config.graph.advisors {
5470                let wt = root.join(format!("advisor-{k}"));
5471                if wt.exists() {
5472                    let target = fold_target(&home, &root, &wt, isolated);
5473                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5474                    reclaim_fold_target(&home, target);
5475                    self.state.save()?;
5476                }
5477            }
5478        }
5479        if !folded.is_empty() {
5480            self.state
5481                .event("fold", format!("folded candidates {}", folded.join(", ")));
5482            self.state.save()?;
5483        }
5484        Ok(())
5485    }
5486
5487    // ------------------------------------------------------------ base sync
5488
5489    async fn hold_base_sync(&mut self) -> Result<bool> {
5490        self.hold_base_sync_as(None).await
5491    }
5492
5493    async fn hold_base_sync_kind(
5494        &mut self,
5495        kind: crate::base_sync_recovery::StopKind,
5496    ) -> Result<()> {
5497        self.hold_base_sync_as(Some(kind)).await?;
5498        Ok(())
5499    }
5500
5501    async fn hold_base_sync_as(
5502        &mut self,
5503        kind: Option<crate::base_sync_recovery::StopKind>,
5504    ) -> Result<bool> {
5505        if !self.state.base_sync_blocked() {
5506            self.state.base_sync_recovery.stop = None;
5507            return Ok(false);
5508        }
5509        let head = match self.state.winner() {
5510            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5511                .await
5512                .unwrap_or_default(),
5513            None => String::new(),
5514        };
5515        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5516            && !authorization.consumed
5517            && authorization.stop.head != head
5518        {
5519            authorization.refuse(format!(
5520                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5521                authorization.stop.head
5522            ));
5523        }
5524        self.state.record_base_sync_stop(&head);
5525        if let Some(kind) = kind {
5526            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5527            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5528                stop.kind = kind;
5529            }
5530        }
5531        self.state.save()?;
5532        Ok(true)
5533    }
5534
5535    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5536    /// anything verifies it.
5537    ///
5538    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5539    /// read whatever is checked out in the winner's worktree. Left alone that
5540    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5541    /// it when the run *branched* - and a run takes long enough that the base
5542    /// has usually moved by the time it gets here. A gate that ran there
5543    /// answers "green on the commit this run started from", not "green on
5544    /// what is about to land", and the difference showed up three times in
5545    /// one day as a green run whose merge would have reverted a file another
5546    /// pull request had already landed.
5547    ///
5548    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5549    /// `land::Step::Rebase` calls, rather than a second implementation of the
5550    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5551    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5552    /// doc warns about ("two answers to a question nobody notices until a
5553    /// diff is wrong").
5554    ///
5555    /// Foreign-checkout reviews instead merge the base into the owned shadow
5556    /// worktree, preserving the ancestry required for fast-forward delivery.
5557    /// A conflicting merge is aborted and held for operator resolution.
5558    ///
5559    /// A conflict is not the end of the road: the standing rebase is handed
5560    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5561    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5562    /// land). Once it finishes, review and the gate run as usual on the
5563    /// rebased tree, which is where a breakage the new base caused is caught
5564    /// by the ordinary gate-fix round. magi resolves nothing itself.
5565    ///
5566    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5567    /// the current durable recovery interval, bounds how often the base is
5568    /// synchronized during active recovery (lifetime attempts remain evidence).
5569    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5570    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5571    /// what was tried (rounds spent, paths still conflicted) and the branch
5572    /// and worktree stay exactly as they were - untouched, for a person to
5573    /// look at - which is also what makes re-entering this function
5574    /// afterwards a no-op instead of a second attempt at the same wall. A
5575    /// push failure ends the same way.
5576    async fn sync_to_base(&mut self) -> Result<()> {
5577        if self.state.status == RunStatus::AlreadyInBase {
5578            return Ok(());
5579        }
5580        self.hold_base_sync().await?;
5581        let conflicted = self
5582            .state
5583            .base_sync
5584            .as_ref()
5585            .is_some_and(|s| s.conflict.is_some());
5586        let Some(winner) = self.state.winner().cloned() else {
5587            return Ok(());
5588        };
5589
5590        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5591
5592        let repo = self.state.repo.clone();
5593        let remote = self.state.config.merge.remote.clone();
5594        let base_branch = self.state.base_branch.clone();
5595        let tracking = format!("{remote}/{base_branch}");
5596
5597        let fetched_base =
5598            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5599        // No network, or the remote never had this branch: the run already
5600        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5601        // otherwise), and one that got this far is not blocked by a fetch
5602        // that fails now. It just has no newer tip to compare against.
5603        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5604            return Ok(());
5605        };
5606
5607        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5608        self.state.ensure_base_episode();
5609        let mut pending = self
5610            .state
5611            .base_sync_recovery
5612            .operations
5613            .last()
5614            .filter(|o| !o.finished)
5615            .cloned();
5616        let scratch = self.state.dir().join("base-sync");
5617        if git::rebase_in_progress(&scratch).await {
5618            // Older resource stops predate operation reservations. Import the
5619            // standing Git operation, never retarget it to today's main.
5620            if pending.is_none()
5621                && self.state.base_sync_recovery.operations.is_empty()
5622                && !conflicted
5623                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5624                    .await
5625                    .ok()
5626                    .as_deref()
5627                    == Some(head.as_str())
5628                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5629                && git::is_clean(&winner.worktree).await?
5630            {
5631                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5632                if self.state.base_sync.is_none() {
5633                    self.state.base_sync = Some(BaseSync {
5634                        tip: saved_tip.clone(),
5635                        behind: 0,
5636                        attempts: 0,
5637                        conflict: None,
5638                        already_in: None,
5639                    });
5640                }
5641                self.state.reserve_base_operation(&head, &saved_tip);
5642                self.state.event(
5643                    "base-recovery",
5644                    "imported standing legacy rebase as a spent synchronization reservation",
5645                );
5646                self.state.save()?;
5647                pending = self.state.base_sync_recovery.operations.last().cloned();
5648            }
5649            let expected = pending.as_ref().map(|op| op.tip.as_str());
5650            if expected.is_none()
5651                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5652            {
5653                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5654                if self.state.base_sync.is_none() {
5655                    self.state.base_sync = Some(BaseSync {
5656                        tip: tip.clone(),
5657                        behind: 0,
5658                        attempts: 0,
5659                        conflict: None,
5660                        already_in: None,
5661                    });
5662                }
5663                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5664                self.state.event("land", why);
5665                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5666                    .await?;
5667                return Ok(());
5668            }
5669        }
5670        if let Some(op) = &pending {
5671            // A replay may add the pinned base's commits, never foreign work.
5672            let mut replay_proven =
5673                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5674            if !replay_proven && scratch.exists() && !git::rebase_in_progress(&scratch).await {
5675                let wait = repository_wait(&self.state, None);
5676                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5677                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5678                    Ok(true) => {
5679                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5680                        self.state.save()?;
5681                        git::worktree_remove(&repo, &scratch).await.ok();
5682                        replay_proven = true;
5683                    }
5684                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5685                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5686                }
5687            }
5688            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5689                if self.state.foreign_checkout.is_some() {
5690                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5691                        .await
5692                        .ok()
5693                        .as_deref()
5694                        == Some(op.head.as_str())
5695                        && git::rev_parse(&repo, &format!("{head}^2"))
5696                            .await
5697                            .ok()
5698                            .as_deref()
5699                            == Some(op.tip.as_str());
5700                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5701                    .await
5702                    .is_ok_and(|m| m.is_empty())
5703                    && let Ok(added) =
5704                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5705                {
5706                    replay_proven = true;
5707                    for commit in added {
5708                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5709                            replay_proven = false;
5710                            break;
5711                        }
5712                    }
5713                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5714                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5715                }
5716            }
5717            // Never retarget an operation across a crash, even if main moved.
5718            // sync_to_head resets and cleans with -x, so even ignored untracked
5719            // files must stop recovery independently of the old tracked tree.
5720            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5721                || (head != op.head
5722                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5723                        .await?
5724                        .is_empty())
5725                || (!git::is_clean(&winner.worktree).await?
5726                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5727                        .await
5728                        .is_ok_and(|o| o.ok()))
5729                || !replay_proven
5730            {
5731                let why = format!(
5732                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5733                    op.id
5734                );
5735                let sync = self
5736                    .state
5737                    .base_sync
5738                    .as_mut()
5739                    .context("reserved synchronization has no lifetime accounting")?;
5740                sync.conflict = Some(why.clone());
5741                self.state.event("land", why);
5742                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5743                    .await?;
5744                return Ok(());
5745            }
5746            if head != op.head {
5747                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5748            }
5749            tip = op.tip.clone();
5750        }
5751        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5752        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5753        if pending.is_none()
5754            && !conflicted
5755            && fetched_base
5756            && self
5757                .state
5758                .base_sync_recovery
5759                .episodes
5760                .last()
5761                .is_some_and(|e| e.boundary.is_some())
5762            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5763            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5764            && owner.execution_runs().last() == Some(&self.state.id)
5765            && owner.status != crate::queue::TaskStatus::Done
5766            && !owner.fresh_start
5767            && owner.review_branch.is_none()
5768            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5769            && let Some(approval) = owner.resumption.as_ref()
5770            && approval.instruction == owner.instruction
5771            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5772            && git::is_clean(&winner.worktree).await?
5773            && self.state.renew_base_episode(&task, approval, &head, &tip)
5774        {
5775            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5776            self.state.save()?;
5777        }
5778
5779        // Before any rebase, and before a recorded conflict is honoured: a
5780        // branch whose change reached the base under other commit ids has
5781        // nothing to rebase and nothing to conflict with, and a run that
5782        // already stopped on that phantom conflict recovers here on resume.
5783        // `behind == 0` with head == tip is a branch the base has since taken
5784        // in whole, whether or not a conflict was ever recorded: the ancestry
5785        // proof must still run (`classify` ignores a head still on the start
5786        // commit).
5787        if (behind > 0 || conflicted || head == tip)
5788            && self
5789                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5790                .await?
5791        {
5792            return Ok(());
5793        }
5794        if conflicted && self.state.base_recovery_pending() {
5795            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5796            let owner =
5797                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5798            let owner_valid = owner.as_ref().is_ok_and(|t| {
5799                t.execution_runs().last() == Some(&self.state.id)
5800                    && t.status != crate::queue::TaskStatus::Done
5801                    && !t.fresh_start
5802                    && t.review_branch.is_none()
5803            });
5804            let invalidation = if !owner_valid {
5805                Some("latest task ownership changed")
5806            } else if !owner.as_ref().is_ok_and(|t| {
5807                authorization
5808                    .generation
5809                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5810            }) {
5811                Some("owner approval generation changed")
5812            } else if authorization.question.as_ref().is_some_and(|question| {
5813                !crate::base_recovery_control::decision_current(
5814                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5815                    &self.state,
5816                    &authorization.task,
5817                    question,
5818                )
5819            }) {
5820                Some("recovery decision ownership, routing or stop evidence changed")
5821            } else if authorization.request.is_some()
5822                && !owner
5823                    .as_ref()
5824                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5825            {
5826                Some("owner decision changed")
5827            } else if let Some(scope) = &authorization.scope {
5828                if scope.tip != tip {
5829                    Some("fetched base changed")
5830                } else if !self
5831                    .state
5832                    .base_sync_recovery
5833                    .episodes
5834                    .last()
5835                    .is_some_and(|e| e.id == scope.episode)
5836                {
5837                    Some("active synchronization interval changed")
5838                } else if !owner
5839                    .as_ref()
5840                    .is_ok_and(|t| t.instruction == scope.instruction)
5841                {
5842                    Some("task instruction changed")
5843                } else {
5844                    None
5845                }
5846            } else {
5847                None
5848            };
5849            if let Some(reason) = invalidation {
5850                let authorization = self
5851                    .state
5852                    .base_sync_recovery
5853                    .authorizations
5854                    .last_mut()
5855                    .unwrap();
5856                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5857                self.state.save()?;
5858                return Ok(());
5859            }
5860            if !fetched_base
5861                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5862                || !git::is_clean(&winner.worktree).await?
5863                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5864            {
5865                return Ok(());
5866            }
5867        }
5868        let recovery = conflicted && self.state.consume_base_recovery(&head);
5869        if conflicted {
5870            // Consumption (including a refused changed HEAD) is durable before Git.
5871            self.state.save()?;
5872            if !recovery {
5873                return Ok(());
5874            }
5875        }
5876
5877        if behind == 0 {
5878            // A fixer-finished rebase moves the branch ref before the
5879            // winner's worktree is told (`sync_to_head` below). A run that
5880            // died in between resumes here with `behind == 0` and a tree still
5881            // holding the pre-rebase files, which review and the gate would
5882            // then read. That state is exactly: HEAD moved off the tip the
5883            // rebase started from, yet the tree is still identical to that
5884            // tip. A tree with edits of its own differs from it, so nothing
5885            // is thrown away.
5886            if let Some(from) = self
5887                .state
5888                .rebase_fixes
5889                .iter()
5890                .rev()
5891                .find_map(|r| r.from.clone())
5892                && from != head
5893                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
5894                    .await
5895                    .is_ok_and(|o| o.ok())
5896            {
5897                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5898            }
5899            // An earlier attempt may have rebased the branch locally and died
5900            // before pushing it (only the fresh-rebase arm below pushes).
5901            // Publish it now, so the plain push at PR time is not refused as
5902            // a non-fast-forward. A run already holding a recorded conflict
5903            // never reaches here; that case is out of scope.
5904            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
5905            if let Some(why) = &conflict {
5906                self.state.status = RunStatus::Blocked;
5907                self.state.event("land", why.clone());
5908            }
5909            self.state.base_sync = Some(BaseSync {
5910                tip,
5911                behind: 0,
5912                attempts,
5913                conflict,
5914                already_in: None,
5915            });
5916            if pending.is_some() {
5917                self.state.finish_base_operation(Some(&head));
5918            }
5919            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
5920                .await?;
5921            self.state.save()?;
5922            return Ok(());
5923        }
5924
5925        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
5926            let why = format!(
5927                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
5928                 synchronization(s); synchronizing again would only race it",
5929                winner.branch
5930            );
5931            self.state.status = RunStatus::Blocked;
5932            self.state.base_sync = Some(BaseSync {
5933                tip,
5934                behind,
5935                attempts,
5936                conflict: Some(why.clone()),
5937                already_in: None,
5938            });
5939            self.state.event("land", why);
5940            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
5941                .await?;
5942            self.state.save()?;
5943            return Ok(());
5944        }
5945
5946        if self.state.foreign_checkout.is_some() {
5947            // Delivery to the operator's checkout is fast-forward only. A
5948            // rebase here would discard its saved head from our ancestry.
5949            let wait = repository_wait(&self.state, None);
5950            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5951            if self.state.base_sync.is_none() {
5952                self.state.base_sync = Some(BaseSync {
5953                    tip: tip.clone(),
5954                    behind,
5955                    attempts: 0,
5956                    conflict: None,
5957                    already_in: None,
5958                });
5959            }
5960            self.state.reserve_base_operation(&head, &tip);
5961            self.state.save()?;
5962            let merged = git::git_raw(
5963                &winner.worktree,
5964                &[
5965                    "-c",
5966                    "core.hooksPath=/dev/null",
5967                    "merge",
5968                    "--no-ff",
5969                    "--no-autostash",
5970                    "--no-edit",
5971                    "-m",
5972                    &format!("Merge {tracking} before verifying"),
5973                    &tip,
5974                ],
5975            )
5976            .await?;
5977            let conflict = if merged.ok() {
5978                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5979                self.state.event(
5980                    "land",
5981                    format!("merged {tracking} into {} before verifying", winner.branch),
5982                );
5983                None
5984            } else {
5985                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
5986                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
5987                }
5988                let why = format!(
5989                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
5990                    winner.branch,
5991                    merged.stderr.chars().take(600).collect::<String>()
5992                );
5993                self.state.status = RunStatus::Blocked;
5994                self.state.event("land", &why);
5995                Some(why)
5996            };
5997            let synced = conflict.is_none();
5998            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
5999            self.state
6000                .finish_base_operation(synced.then_some(fresh.as_str()));
6001            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6002            self.state.base_sync = Some(BaseSync {
6003                tip,
6004                behind: if synced { 0 } else { behind },
6005                attempts,
6006                conflict,
6007                already_in: None,
6008            });
6009            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6010                .await?;
6011            self.state.save()?;
6012            return Ok(());
6013        }
6014
6015        self.state.event(
6016            "land",
6017            format!(
6018                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6019                winner.branch
6020            ),
6021        );
6022        self.state.save()?;
6023
6024        // The remote's copy of the branch, read now and only if the fetch
6025        // really succeeded (a stale tracking ref must never pin a lease). It is
6026        // pushed over after a rebase only when it is a commit this branch
6027        // already contains, by ancestry or by patch (an earlier rebase of ours
6028        // that never reached the remote): anything else is somebody else's work.
6029        let branch_tracking = format!("{remote}/{}", winner.branch);
6030        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6031        let remote_tip = if self.state.task_pr_branch().is_none()
6032            && matches!(&fetched_branch, Ok(o) if o.ok())
6033        {
6034            git::rev_parse(&repo, &branch_tracking).await.ok()
6035        } else {
6036            None
6037        };
6038        // A remote tip this branch does not contain is somebody else's work:
6039        // rebasing would leave a local tip that can never be pushed. Stop
6040        // before touching anything and say so.
6041        if let Some(theirs) = &remote_tip
6042            && !git::is_ancestor(&repo, theirs, &head).await
6043            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6044                .await
6045                .is_ok_and(|missing| missing.is_empty())
6046        {
6047            let why = format!(
6048                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6049                 them",
6050                short(theirs),
6051                winner.branch
6052            );
6053            self.state.status = RunStatus::Blocked;
6054            self.state.base_sync = Some(BaseSync {
6055                tip,
6056                behind,
6057                attempts,
6058                conflict: Some(why.clone()),
6059                already_in: None,
6060            });
6061            self.state.event("land", why);
6062            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6063                .await?;
6064            self.state.save()?;
6065            return Ok(());
6066        }
6067
6068        if self.state.base_sync.is_none() {
6069            self.state.base_sync = Some(BaseSync {
6070                tip: tip.clone(),
6071                behind,
6072                attempts: 0,
6073                conflict: None,
6074                already_in: None,
6075            });
6076        }
6077        let scratch = self.state.dir().join("base-sync");
6078        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6079        {
6080            if error.is::<crate::repo_lock::ResourceBlocked>() {
6081                return Ok(());
6082            }
6083            return Err(error);
6084        }
6085        self.state.reserve_base_operation(&head, &tip);
6086        self.state.save()?;
6087        let rebased =
6088            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6089                .await
6090            {
6091                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6092                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6093                Err(e) => Err(e),
6094            };
6095        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6096        let stop_kind = match &rebased {
6097            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6098            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6099            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6100        };
6101        match rebased {
6102            Ok(None) => {
6103                // The branch ref moved, but a worktree that already had it
6104                // checked out (the winner's) was not told; sync its index and
6105                // files before anything reads them.
6106                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6107                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6108                self.state.finish_base_operation(Some(&fresh));
6109                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6110                let mut conflict = None;
6111                if let Some(pinned) = &remote_tip {
6112                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6113                    match pushed {
6114                        Ok(o) if o.ok() => self.state.event(
6115                            "land",
6116                            format!("pushed rebased {} to {remote}", winner.branch),
6117                        ),
6118                        Ok(o) => {
6119                            conflict = Some(format!(
6120                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6121                                winner.branch,
6122                                short(pinned),
6123                                o.stderr.chars().take(600).collect::<String>()
6124                            ));
6125                        }
6126                        Err(e) => {
6127                            conflict = Some(format!(
6128                                "rebased {} locally but could not push it: {e:#}",
6129                                winner.branch
6130                            ));
6131                        }
6132                    }
6133                }
6134                if let Some(why) = &conflict {
6135                    self.state.status = RunStatus::Blocked;
6136                    self.state.event("land", why.clone());
6137                }
6138                self.state.base_sync = Some(BaseSync {
6139                    tip: tip.clone(),
6140                    behind: 0,
6141                    attempts,
6142                    conflict,
6143                    already_in: None,
6144                });
6145                self.state
6146                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6147            }
6148            Ok(Some(conflict)) => {
6149                self.state.finish_base_operation(None);
6150                let why = format!(
6151                    "{} conflicts with {tracking} and did not rebase: {}",
6152                    winner.branch,
6153                    conflict.chars().take(600).collect::<String>()
6154                );
6155                self.state.status = RunStatus::Blocked;
6156                self.state.base_sync = Some(BaseSync {
6157                    tip,
6158                    behind,
6159                    attempts,
6160                    conflict: Some(why.clone()),
6161                    already_in: None,
6162                });
6163                self.state.event("land", why);
6164            }
6165            // A refused Git write or a busy repository: nothing is wrong with
6166            // the branch. The scratch rebase stays standing and the run
6167            // resumes into it (`base_sync` must not claim a conflict).
6168            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6169                self.state.save()?;
6170                return Ok(());
6171            }
6172            Err(e) => {
6173                self.state.finish_base_operation(None);
6174                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6175                self.state.status = RunStatus::Blocked;
6176                self.state.base_sync = Some(BaseSync {
6177                    tip,
6178                    behind,
6179                    attempts,
6180                    conflict: Some(why.clone()),
6181                    already_in: None,
6182                });
6183                self.state.event("land", why);
6184            }
6185        }
6186        if !self.state.base_sync_blocked() {
6187            self.state.base_sync_recovery.stop = None;
6188        }
6189        self.hold_base_sync_kind(stop_kind).await?;
6190        self.state.save()?;
6191        Ok(())
6192    }
6193
6194    /// Push a branch an earlier attempt rebased locally but never published,
6195    /// pinned to the remote tip read right after a successful fetch. Returns
6196    /// the reason when the run must stop; `None` when there was nothing to do
6197    /// (no remote copy, the same tip, or a remote copy this branch already
6198    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6199    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6200        // Task competitions publish only after the PR text gate, to their
6201        // public head; never resurrect a candidate branch on the remote.
6202        if self.state.task_pr_branch().is_some() {
6203            return None;
6204        }
6205        let repo = self.state.repo.clone();
6206        let remote = self.state.config.merge.remote.clone();
6207        let fetched = git::fetch(&repo, &remote, branch).await;
6208        if !matches!(&fetched, Ok(o) if o.ok()) {
6209            return None;
6210        }
6211        let branch_tracking = format!("{remote}/{branch}");
6212        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6213        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6214            return None;
6215        }
6216        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6217            .await
6218            .is_ok_and(|missing| missing.is_empty())
6219        {
6220            return Some(format!(
6221                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6222                 them",
6223                short(&theirs)
6224            ));
6225        }
6226        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6227            Ok(o) if o.ok() => {
6228                self.state
6229                    .event("land", format!("pushed rebased {branch} to {remote}"));
6230                None
6231            }
6232            Ok(o) => Some(format!(
6233                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6234                 someone may have pushed): {}",
6235                short(&theirs),
6236                o.stderr.chars().take(600).collect::<String>()
6237            )),
6238            Err(e) => Some(format!(
6239                "{branch} is rebased locally but could not be pushed: {e:#}"
6240            )),
6241        }
6242    }
6243
6244    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6245    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6246    /// whether it did.
6247    ///
6248    /// Checked only when the base is ahead of the branch. A failing check is
6249    /// "not proven" - the ordinary rebase path then decides - never a reason to
6250    /// stop the run.
6251    ///
6252    /// The remote copy of the branch is held to the same standard as the local
6253    /// one: if it carries a tip this worktree does not, that tip must itself be
6254    /// proven in the base, or nothing is settled (a pull request would
6255    /// otherwise be closed over commits nobody checked). The pull request is
6256    /// closed *before* the terminal status is saved; if that fails for a
6257    /// reason other than a refusal (no network, a `gh` error) the run is left
6258    /// `Blocked` with the reason as its conflict, which a resume retries -
6259    /// the same recovery a phantom conflict gets.
6260    async fn settle_already_in(
6261        &mut self,
6262        branch: &str,
6263        tip: &str,
6264        head: &str,
6265        attempts: usize,
6266        behind: usize,
6267    ) -> Result<bool> {
6268        let repo = self.state.repo.clone();
6269        let remote = self.state.config.merge.remote.clone();
6270        let start = self.state.base_commit.clone();
6271        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6272            Ok(Some(e)) => e,
6273            Ok(None) => return Ok(false),
6274            Err(e) => {
6275                tracing::warn!("already-in-base check for {branch}: {e:#}");
6276                return Ok(false);
6277            }
6278        };
6279        let mut verified = vec![head.to_owned()];
6280        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6281        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6282        if matches!(&fetched, Ok(o) if o.ok())
6283            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await
6284            && theirs != head
6285        {
6286            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6287                Ok(Some(_)) => verified.push(theirs),
6288                _ => return Ok(false),
6289            }
6290        }
6291        let base_branch = self.state.base_branch.clone();
6292        let message = format!(
6293            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6294             land",
6295            evidence.names(),
6296            evidence.proof.as_str()
6297        );
6298        let closed =
6299            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6300                .await;
6301        match closed {
6302            Ok(Ok(url)) => self
6303                .state
6304                .event("land", format!("closed {url}: superseded on {base_branch}")),
6305            Ok(Err(why)) => self
6306                .state
6307                .event("land", format!("did not close a pull request: {why}")),
6308            Err(e) => {
6309                let why = format!(
6310                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6311                     not be closed ({e:#}); resume to retry"
6312                );
6313                self.state.status = RunStatus::Blocked;
6314                self.state.base_sync = Some(BaseSync {
6315                    tip: tip.to_owned(),
6316                    behind,
6317                    attempts,
6318                    conflict: Some(why.clone()),
6319                    already_in: None,
6320                });
6321                self.state.event("land", why);
6322                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6323                    .await?;
6324                self.state.save()?;
6325                return Ok(true);
6326            }
6327        }
6328        self.state.status = RunStatus::AlreadyInBase;
6329        self.state.base_sync_recovery.stop = None;
6330        self.state.base_sync = Some(BaseSync {
6331            tip: tip.to_owned(),
6332            behind,
6333            attempts,
6334            conflict: None,
6335            already_in: Some(evidence),
6336        });
6337        self.state.event("land", message);
6338        self.state.save()?;
6339        self.settle_questions();
6340        Ok(true)
6341    }
6342
6343    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6344    /// last landed the winner on, once it has run, else the commit the run
6345    /// branched from.
6346    ///
6347    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6348    /// and `vote` all happen before there is a winner to rebase, so they
6349    /// compare every candidate against the branch point on purpose, and a
6350    /// base that moves after they are already done cannot change an answer
6351    /// they already gave.
6352    fn landing_base(&self) -> String {
6353        self.state
6354            .base_sync
6355            .as_ref()
6356            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6357    }
6358
6359    // ------------------------------------------------------- operator fix
6360
6361    /// Route specific, already-recorded review findings to a fixer for a
6362    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6363    /// entry point.
6364    ///
6365    /// Distinct from `review_loop`'s own fix step in three ways: it never
6366    /// runs a reviewer wave, it never spends review-round budget, and what
6367    /// happened is recorded as an [`OperatorFixRequest`] appended to
6368    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6369    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6370    /// and vote must never be rewritten to look like a manufactured blocking
6371    /// verdict.
6372    ///
6373    /// Only meaningful once review has actually concluded: `Ready` (handed
6374    /// off with findings still open, or simply concluded clean while minor
6375    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6376    /// gate failed). Everything else is refused: a run still in progress
6377    /// should simply be resumed, and a `Merged` run's branch has already
6378    /// landed — reopening *this* run's own record cannot change that, so the
6379    /// answer there is a fresh `magi review <branch>`.
6380    ///
6381    /// A real commit here re-verifies through a fresh, ordinary review-only
6382    /// run on the same branch ([`Self::review`]) rather than reopening this
6383    /// run's own `review_loop`: once any round in this run's history went
6384    /// clean, `review_conclusion` treats that as permanent by design (the
6385    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6386    /// way to force one more genuine reviewer wave out of *this* run without
6387    /// either rewriting history or weakening that guarantee for every other
6388    /// caller. A review-only run costs nothing extra — no implementation, no
6389    /// judging, no vote — and exercises the exact same review → verify →
6390    /// gate → (human) merge path, unmodified.
6391    pub async fn fix_selected(
6392        &mut self,
6393        ids: &[String],
6394        reason: &str,
6395        allow_stale: bool,
6396    ) -> Result<()> {
6397        let reason = reason.trim();
6398        if reason.is_empty() {
6399            bail!("a fix request needs a reason — that is the operator's own record of why");
6400        }
6401        if ids.is_empty() {
6402            bail!("no finding id given");
6403        }
6404        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6405            bail!(
6406                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6407                 has already concluded — can be given a targeted fix. A run still \
6408                 in progress should simply be resumed; a `merged` run's branch has \
6409                 already landed, so its answer is a fresh `magi review <branch>`, \
6410                 not reopening this run's own record",
6411                self.state.id,
6412                self.state.status.as_str()
6413            );
6414        }
6415        // Reassignment shares this claim through its atomic task save. Check
6416        // the canonical run identity inside it, before preflight or any await.
6417        let _claim = FixClaim::acquire(&self.state.dir())?;
6418        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6419        let home = crate::run::home();
6420        // The ordinary driver takes these same locks at admission. Keep the
6421        // execution lease through the fix, but never the owner lock across Git
6422        // or agent awaits.
6423        let execution = {
6424            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6425            let disk = RunState::load(&self.state.id)?;
6426            crate::pr_head::ensure_owner(&disk)?;
6427            anyhow::ensure!(
6428                disk.status == self.state.status && disk.released_to.is_none(),
6429                "run changed since it was loaded; reload before fixing"
6430            );
6431            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6432            anyhow::ensure!(
6433                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6434                "run {} is currently being worked on or its ownership is unknown",
6435                disk.id
6436            );
6437            let lease = crate::driver::maintenance(&home, &disk.id).context(
6438                "run is currently being worked on or its execution lease is unavailable",
6439            )?;
6440            self.state = disk;
6441            lease
6442        };
6443        let Some(winner) = self.state.winner().cloned() else {
6444            bail!("run {} has no winning candidate to fix", self.state.id);
6445        };
6446        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6447            bail!(
6448                "branch `{}` no longer exists; this run cannot be extended",
6449                winner.branch
6450            );
6451        }
6452        // Resolve every id before spending anything — an unknown id refuses
6453        // the whole request rather than silently dropping it — and dedup
6454        // while keeping the operator's own order.
6455        let mut seen = BTreeSet::new();
6456        let mut findings = Vec::new();
6457        let mut missing = Vec::new();
6458        for id in ids {
6459            if !seen.insert(id.clone()) {
6460                continue;
6461            }
6462            match self.state.finding(id) {
6463                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6464                    id: f.id.clone(),
6465                    severity: f.severity,
6466                    reviewer_vote: rec.vote,
6467                    round: round.round,
6468                    round_head: round.head.clone(),
6469                    reviewer: rec.reviewer,
6470                    agent: rec.agent.clone(),
6471                    file: f.file.clone(),
6472                    line: f.line,
6473                    title: f.title.clone(),
6474                    detail: f.detail.clone(),
6475                    outcome: OperatorFixOutcome::Pending,
6476                }),
6477                None => missing.push(id.clone()),
6478            }
6479        }
6480        if !missing.is_empty() {
6481            bail!(
6482                "unknown finding id(s): {}; nothing was changed",
6483                missing.join(", ")
6484            );
6485        }
6486
6487        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6488        let stale_details: Vec<(String, String)> = findings
6489            .iter()
6490            .filter(|f| f.round_head != head_at_request)
6491            .map(|f| (f.id.clone(), f.round_head.clone()))
6492            .collect();
6493        let stale = !stale_details.is_empty();
6494        if stale && !allow_stale {
6495            bail!(
6496                "the branch has moved since some finding(s) were raised — {} — now \
6497                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6498                stale_details
6499                    .iter()
6500                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6501                    .collect::<Vec<_>>()
6502                    .join(", "),
6503                short(&head_at_request)
6504            );
6505        }
6506
6507        let request = OperatorFixRequest {
6508            requested_at: Timestamp::now(),
6509            reason: reason.to_owned(),
6510            findings,
6511            head_at_request: head_at_request.clone(),
6512            allow_stale,
6513            stale,
6514            fix: None,
6515            result_head: None,
6516            follow_up_review_run: None,
6517        };
6518        self.state.event(
6519            "fix",
6520            format!(
6521                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6522                request.findings.len(),
6523                request
6524                    .findings
6525                    .iter()
6526                    .map(|f| f.id.as_str())
6527                    .collect::<Vec<_>>()
6528                    .join(", "),
6529            ),
6530        );
6531        // Recorded now, before any worktree work or the fixer call itself —
6532        // and re-saved at each checkpoint below: a crash at any point after
6533        // this (mid fixer call, mid follow-up review) must not lose the fact
6534        // that this was requested, for which findings, and why. Everything
6535        // past this point reads and writes through `request_index` rather
6536        // than a local variable, since `request` itself is moved here.
6537        self.state.operator_fixes.push(request);
6538        self.state.save()?;
6539        let request_index = self.state.operator_fixes.len() - 1;
6540
6541        // A fresh, dedicated worktree for this one call, never the winner's
6542        // own worktree in place: that one may already be gone (folded away),
6543        // and reusing it in place would leave the branch checked out there
6544        // when the follow-up review below tries to check it out again. Freed
6545        // immediately after, either way — but only once confirmed clean:
6546        // `worktree_remove` is a `git worktree remove --force`, which would
6547        // otherwise discard uncommitted work left there by the operator or
6548        // another process before this had a chance to even look at it.
6549        let repo = self.state.repo.clone();
6550        let coordination = self.coordinate(&repo).await?;
6551        if winner.worktree.exists() {
6552            // Lockfiles a rescue commit withheld stay untracked on purpose and
6553            // are already recorded; they are not the operator's work to protect.
6554            let dirty = git::git(
6555                &winner.worktree,
6556                &["status", "--porcelain", "--untracked-files=all"],
6557            )
6558            .await?;
6559            let only_withheld = dirty.lines().all(|l| {
6560                l.strip_prefix("?? ")
6561                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6562            });
6563            if !only_withheld {
6564                bail!(
6565                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6566                     discard them first",
6567                    winner.worktree.display()
6568                );
6569            }
6570            git::worktree_remove(&self.state.repo, &winner.worktree)
6571                .await
6572                .ok();
6573        }
6574        let fix_worktree = self.state.worktree_root().join("operator-fix");
6575        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6576        git::git(
6577            &self.state.repo,
6578            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6579        )
6580        .await
6581        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6582        if !git::is_clean(&fix_worktree).await? {
6583            git::worktree_remove(&self.state.repo, &fix_worktree)
6584                .await
6585                .ok();
6586            bail!(
6587                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6588                winner.branch
6589            );
6590        }
6591        let repo_for_setup = self.state.repo.clone();
6592        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6593            Ok(()) => {
6594                worktree_setup::prepare_with(
6595                    &self.state.config,
6596                    &repo_for_setup,
6597                    &fix_worktree,
6598                    crate::build_target::Coordination::Held(coordination.as_ref()),
6599                )
6600                .await
6601            }
6602            Err(e) => Err(e),
6603        };
6604        if let Err(e) = setup {
6605            git::worktree_remove(&self.state.repo, &fix_worktree)
6606                .await
6607                .ok();
6608            return Err(e);
6609        }
6610
6611        // This explicit operator request retries availability independently
6612        // of execute(); the previous call has already saved and cleaned up.
6613        self.state.resource_block = None;
6614
6615        let run_id = self.state.id.clone();
6616        let prompts = self.state.config.prompts.clone();
6617        let language = self.state.config.graph.language.clone();
6618        let sessions = self.state.config.graph.sessions;
6619        let artifacts = agent::artifacts_dir(&self.state.dir());
6620        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6621            .findings
6622            .iter()
6623            .map(|f| Finding {
6624                id: f.id.clone(),
6625                severity: f.severity,
6626                file: f.file.clone(),
6627                line: f.line,
6628                title: f.title.clone(),
6629                detail: f.detail.clone(),
6630            })
6631            .collect();
6632        let fix_prompt = prompt::operator_fix_in(
6633            &self.state.instruction,
6634            &finding_list,
6635            reason,
6636            &stale_details,
6637            &head_at_request,
6638            &language,
6639            &self.state.config.graph.github_language,
6640        );
6641        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6642        drop(coordination);
6643        let (job, seat, out) = self
6644            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6645                prompt: fix_prompt.clone(),
6646                spec,
6647                seat,
6648                cwd: fix_worktree.clone(),
6649                timeout,
6650                allow_write: true,
6651                sessions,
6652                artifacts: artifacts.clone(),
6653                stem: "operator-fix".to_owned(),
6654                handover: None,
6655            })
6656            .await;
6657        let agent_id = seat.agent.clone();
6658
6659        let mut fix = FixRecord {
6660            agent: agent_id,
6661            addressed: Vec::new(),
6662            rejected: Vec::new(),
6663            notes: String::new(),
6664            committed: false,
6665            failed: None,
6666            duration_ms: 0,
6667            continuation: None,
6668        };
6669        let mut final_seat = seat.clone();
6670        match out {
6671            AgentOutcome::Ok(o) => {
6672                fix.duration_ms = o.duration_ms;
6673                let parsed = verdict::extract_json::<FixReport>(&o.text);
6674                let incomplete_reason = match &parsed {
6675                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6676                        "the reply parsed, but it reported a command whose own CLI \
6677                         never confirmed an exit status"
6678                            .to_owned(),
6679                    ),
6680                    Ok(_) => None,
6681                    Err(e) => Some(e.to_string()),
6682                };
6683                match incomplete_reason {
6684                    None => {
6685                        let report = parsed.expect("checked Ok above");
6686                        fix.addressed = report.addressed;
6687                        fix.rejected = report.rejected;
6688                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6689                    }
6690                    Some(reason) => {
6691                        let (resumed_seat, resolved, failure, cont) = self
6692                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6693                            .await;
6694                        fix.duration_ms += cont.cumulative_wait_ms;
6695                        fix.continuation = Some(cont);
6696                        final_seat = resumed_seat;
6697                        match resolved {
6698                            Some(report) => {
6699                                fix.addressed = report.addressed;
6700                                fix.rejected = report.rejected;
6701                                fix.notes =
6702                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6703                            }
6704                            None => fix.failed = failure,
6705                        }
6706                    }
6707                }
6708            }
6709            AgentOutcome::Dropped(o) => {
6710                fix.duration_ms = o.duration_ms;
6711                let why = o
6712                    .dropped
6713                    .as_ref()
6714                    .map(|d| d.why.as_str())
6715                    .unwrap_or("the CLI ended the stream without delivering its answer");
6716                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6717            }
6718            AgentOutcome::Quota(o) => {
6719                self.state.quota.push(QuotaLoss::from_report(
6720                    final_seat.key.clone(),
6721                    "fix",
6722                    o.quota.as_ref(),
6723                ));
6724                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6725            }
6726            AgentOutcome::Failed(e) => fix.failed = Some(e),
6727            AgentOutcome::ResourceBlocked(e) => {
6728                fix.failed = Some(format!("the fixer was not started: {e}"));
6729            }
6730        }
6731        // Even a deferred call must rescue edits, release the worktree and
6732        // finalize its record below so an explicit `magi fix` can retry.
6733        if fix.continuation.is_none() {
6734            fix.continuation = Some(ContinuationRecord::not_needed());
6735        }
6736        self.state.seats.insert(final_seat.key.clone(), final_seat);
6737
6738        let rescue_message = format!(
6739            "magi: operator-selected fix ({}) (uncommitted work)",
6740            self.state.operator_fixes[request_index]
6741                .findings
6742                .iter()
6743                .map(|f| f.id.as_str())
6744                .collect::<Vec<_>>()
6745                .join(", ")
6746        );
6747        let repo = self.state.repo.clone();
6748        let coordination = self.coordinate(&repo).await?;
6749        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6750            self.state.note_withheld("fix", &r.withheld);
6751        }
6752        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6753        fix.committed = after != head_at_request;
6754        git::worktree_remove(&self.state.repo, &fix_worktree)
6755            .await
6756            .ok();
6757        drop(coordination);
6758
6759        self.state.event(
6760            "fix",
6761            match &fix.failed {
6762                Some(reason) => format!(
6763                    "operator fix: adoption report was lost ({reason}); {}",
6764                    if fix.committed {
6765                        "committed"
6766                    } else {
6767                        "NO new commit"
6768                    }
6769                ),
6770                None => format!(
6771                    "operator fix: {} addressed, {} rejected, {}",
6772                    fix.addressed.len(),
6773                    fix.rejected.len(),
6774                    if fix.committed {
6775                        "committed"
6776                    } else {
6777                        "NO new commit"
6778                    }
6779                ),
6780            },
6781        );
6782
6783        // Every selected finding gets an outcome — never left `Pending` once
6784        // the fixer's own turn is over. A report that never came back at all
6785        // marks every one of them `Unreported`, not silently "not addressed":
6786        // quota, a dropped stream, or an exhausted continuation are gaps in
6787        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6788        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6789        for f in &mut self.state.operator_fixes[request_index].findings {
6790            f.outcome = if fix.failed.is_some() {
6791                OperatorFixOutcome::Unreported
6792            } else if fix.addressed.contains(&f.id) {
6793                OperatorFixOutcome::Addressed
6794            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6795                OperatorFixOutcome::Rejected { why: r.why.clone() }
6796            } else {
6797                OperatorFixOutcome::Unreported
6798            };
6799        }
6800
6801        let committed = fix.committed;
6802        if committed {
6803            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6804        }
6805        self.state.operator_fixes[request_index].fix = Some(fix);
6806        // Saved again now that the fixer's own outcome is final, on top of
6807        // the save right after the request was first pushed above.
6808        self.state.save()?;
6809        if self.state.resource_block.is_some() {
6810            return self.stop_for_resource();
6811        }
6812
6813        if committed {
6814            self.state.event(
6815                "fix",
6816                format!(
6817                    "operator fix committed {}; opening a follow-up review-only run",
6818                    short(&after)
6819                ),
6820            );
6821            self.state.save()?;
6822            drop(execution);
6823            // The new review owns its own execution. Update only its audit link
6824            // afterwards, since publication may have changed the old record.
6825            let event_count = self.state.events.len();
6826            let save_follow_up = |state: &mut RunState| -> Result<()> {
6827                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
6828                let _execution = crate::driver::maintenance(&home, &state.id)?;
6829                let mut disk = RunState::load(&state.id)?;
6830                disk.events.extend(state.events.drain(event_count..));
6831                let follow_up = state.operator_fixes[request_index]
6832                    .follow_up_review_run
6833                    .clone();
6834                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
6835                disk.save()?;
6836                *state = disk;
6837                Ok(())
6838            };
6839            // The operator asked for the fix, and the follow-up serves whatever
6840            // task the run it follows served.
6841            let origin =
6842                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6843            match Self::review(
6844                &self.state.repo,
6845                &winner.branch,
6846                self.state.config.clone(),
6847                origin,
6848            )
6849            .await
6850            {
6851                Ok(mut follow_up) => {
6852                    follow_up.state.event(
6853                        "start",
6854                        format!(
6855                            "requested by an operator fix on run {} for finding(s) {}",
6856                            self.state.id,
6857                            self.state.operator_fixes[request_index]
6858                                .findings
6859                                .iter()
6860                                .map(|f| f.id.as_str())
6861                                .collect::<Vec<_>>()
6862                                .join(", "),
6863                        ),
6864                    );
6865                    follow_up.state.save()?;
6866                    let follow_up_id = follow_up.state.id.clone();
6867                    // The follow-up is a run like any other: it belongs to the
6868                    // task of the run it follows, or to one filed for it.
6869                    let adopted = match crate::direct::adopt(
6870                        &follow_up.state,
6871                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
6872                    ) {
6873                        Ok(a) => a,
6874                        Err(e) => {
6875                            // An ownerless run must not spend agent calls; it
6876                            // stays saved, and `magi run --resume` adopts it.
6877                            self.state.event(
6878                                "fix",
6879                                format!(
6880                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
6881                                ),
6882                            );
6883                            save_follow_up(&mut self.state)?;
6884                            return Ok(());
6885                        }
6886                    };
6887                    let executed = follow_up.execute().await;
6888                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
6889                    if let Some(a) = adopted {
6890                        a.finish(&follow_up.state, executed);
6891                    }
6892                    if let Some(e) = failure {
6893                        self.state.event(
6894                            "fix",
6895                            format!(
6896                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
6897                            ),
6898                        );
6899                    }
6900                    self.state.operator_fixes[request_index].follow_up_review_run =
6901                        Some(follow_up_id);
6902                }
6903                Err(e) => {
6904                    self.state.event(
6905                        "fix",
6906                        format!("committed the fix but could not open a follow-up review: {e:#}"),
6907                    );
6908                }
6909            }
6910            save_follow_up(&mut self.state)?;
6911        }
6912
6913        Ok(())
6914    }
6915
6916    // --------------------------------------------------------------- review
6917
6918    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
6919    /// names, in order, each at most once, moving on only when the call
6920    /// advances (an error, a quota hit or nothing usable - the same decision
6921    /// point `agent::chain_advances` is for the other chained roles).
6922    ///
6923    /// Each agent gets its own seat from `Runner::seat`: the same agent
6924    /// continues its conversation (the winner's own implementer seat when it
6925    /// is the winner's author, now that the competition is over), another
6926    /// takes a fresh one so the full prompt is sent again. A handover is
6927    /// recorded under `node`, which is what makes the fallback stick for the
6928    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
6929    /// is returned, so an exhausted chain reads exactly like a single failed
6930    /// fixer: one quota loss, the same wording, the same refund. An earlier
6931    /// attempt's edits are left in the tree and judged, with the final
6932    /// attempt's, by what git says afterwards.
6933    ///
6934    /// Returns the job that produced the outcome, for `continue_fix_report`.
6935    async fn ask_fixer(
6936        &mut self,
6937        winner: &Candidate,
6938        node: &'static str,
6939        round: Option<usize>,
6940        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6941    ) -> (SeatJob, SeatState, AgentOutcome) {
6942        let attempts = fixer::attempts(&self.state, &self.roles, winner);
6943        self.ask_fixer_among(attempts, node, round, None, build)
6944            .await
6945    }
6946
6947    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
6948    /// worktree and a commit: before the next agent is asked after one that
6949    /// did not satisfy the call, the worktree is put back on that commit, so
6950    /// a failed agent's partial edits are not carried into the next one.
6951    async fn ask_fixer_among(
6952        &mut self,
6953        attempts: Vec<(AgentSpec, String)>,
6954        node: &'static str,
6955        round: Option<usize>,
6956        restore: Option<(&Path, &str)>,
6957        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6958    ) -> (SeatJob, SeatState, AgentOutcome) {
6959        let run_id = self.state.id.clone();
6960        let prompts = self.state.config.prompts.clone();
6961        let cache = self.state.config.cache_dir();
6962        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6963        let mut last = None;
6964        for (i, (spec, key)) in attempts.into_iter().enumerate() {
6965            let seat = self.seat(&key, &spec.id);
6966            let mut job = build(spec.clone(), seat);
6967            if i > 0 {
6968                job.stem = format!("{}-{}", job.stem, spec.id);
6969            }
6970            let ctx = WaveCtx {
6971                carry_seats: false,
6972                pauses: Some((&self.pause, &self.interrupt)),
6973                run: &run_id,
6974                node,
6975                prompts: &prompts,
6976                cache: cache.as_deref(),
6977                round,
6978            };
6979            let (seat, out) =
6980                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
6981            // A resource block never advances the chain: the chosen agent
6982            // was not asked, so it must be the one asked again on resume.
6983            let advances = match &out {
6984                AgentOutcome::Ok(o) => agent::output_advances(o),
6985                AgentOutcome::ResourceBlocked(_) => false,
6986                _ => true,
6987            };
6988            if let Some(next) = ids.get(i + 1)
6989                && advances
6990            {
6991                self.state.seats.insert(seat.key.clone(), seat.clone());
6992                let class =
6993                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
6994                let reason = match &out {
6995                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
6996                    other => fail_reason(other),
6997                };
6998                // A failed agent's edits must not reach the next one, and a
6999                // restore that did not work ends the chain: the call fails
7000                // and the caller's own (confirmed) restore decides.
7001                if let Some((wt, rev)) = restore
7002                    && let Err(e) = self.graft_restore(wt, rev).await
7003                {
7004                    let why =
7005                        format!("could not restore the worktree before the next fixer: {e:#}");
7006                    tracing::warn!("{why}");
7007                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7008                        AgentOutcome::ResourceBlocked(why)
7009                    } else {
7010                        AgentOutcome::Failed(why)
7011                    };
7012                    last = Some((job, seat, out));
7013                    break;
7014                }
7015                record_handover(
7016                    &mut self.state,
7017                    node,
7018                    &seat.key,
7019                    &spec.id,
7020                    next,
7021                    &class,
7022                    &reason,
7023                );
7024                continue;
7025            }
7026            last = Some((job, seat, out));
7027            break;
7028        }
7029        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7030        if let AgentOutcome::Quota(output) = &out
7031            && node != "graft"
7032        {
7033            // Graft is best effort: its caller records the loss and restores
7034            // the pre-graft tree, then proceeds to review and gate.
7035            // Every fallback was tried. Machine outages cannot be repaired by
7036            // spending a fix round; use each caller's resumable resource path.
7037            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7038            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7039            self.state.quota.push(loss);
7040            self.state.seats.insert(seat.key.clone(), seat.clone());
7041            self.state.status = RunStatus::Blocked;
7042            return (
7043                job,
7044                seat,
7045                AgentOutcome::ResourceBlocked(
7046                    "fixer unavailable; restore agent availability and resume".into(),
7047                ),
7048            );
7049        }
7050        (job, seat, out)
7051    }
7052
7053    /// The one repair a verification-only failure earns (see
7054    /// [`crate::recovery`]), before the first review round of a run that took
7055    /// a branch over.
7056    ///
7057    /// Saved as started *before* the fixer is called, so a resume never
7058    /// repairs twice; a start found on re-entry is rolled back to the commit
7059    /// it began from. A failed or unusable fixer leaves the tree as it was and
7060    /// the review goes on over it, so the first round's own verification
7061    /// reports the failure again. The failure is never carried into a round as
7062    /// a result: verification is re-run on whatever commit this leaves.
7063    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7064        use crate::recovery::{Mode, Repair};
7065        if !self.state.reviews.is_empty() {
7066            return Ok(());
7067        }
7068        let Some(mut rec) = self.state.recovery.clone() else {
7069            return Ok(());
7070        };
7071        if rec.mode != Mode::VerifyRepair {
7072            return Ok(());
7073        }
7074        let wt = winner.worktree.clone();
7075        let mut head = git::rev_parse(&wt, "HEAD").await?;
7076        match rec.repair.clone() {
7077            Repair::Done { .. } => return Ok(()),
7078            Repair::WaitingForRestore { before } => {
7079                self.graft_restore(&wt, &before).await?;
7080                head = before;
7081                rec.repair = Repair::NotStarted;
7082                self.state.recovery = Some(rec.clone());
7083                self.state.save()?;
7084            }
7085            Repair::Started { before } => {
7086                // Interrupted: the unfinished edits are not trusted.
7087                // An unconfirmed rollback blocks the run with `Started` kept,
7088                // so a resume retries it; the tree is never reviewed as is.
7089                if let Err(e) = self.graft_restore(&wt, &before).await {
7090                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7091                        return Err(e);
7092                    }
7093                    return self
7094                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7095                        .await;
7096                }
7097                rec.repair = Repair::Done {
7098                    before: before.clone(),
7099                    after: before,
7100                    committed: false,
7101                    failed: Some("interrupted; rolled back".to_owned()),
7102                };
7103                self.state
7104                    .event("recovery", "the repair was interrupted and rolled back");
7105                self.state.recovery = Some(rec);
7106                self.state.save()?;
7107                return Ok(());
7108            }
7109            Repair::NotStarted => {}
7110        }
7111        if crate::recovery::recheck(&mut rec, &head) {
7112            self.state.event("recovery", rec.summary());
7113            self.state.recovery = Some(rec);
7114            self.state.save()?;
7115            return Ok(());
7116        }
7117        rec.repair = Repair::Started {
7118            before: head.clone(),
7119        };
7120        self.state.recovery = Some(rec.clone());
7121        self.state.save()?;
7122
7123        let language = self.state.config.graph.language.clone();
7124        let sessions = self.state.config.graph.sessions;
7125        let artifacts = agent::artifacts_dir(&self.state.dir());
7126        let fix_prompt = prompt::recovery_fix(
7127            &self.state.instruction,
7128            &rec,
7129            self.state.config.graph.review_rounds,
7130            &language,
7131        );
7132        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7133        self.state.event(
7134            "recovery",
7135            format!(
7136                "repair: the fixer starts from the failed verification on {}",
7137                short(&head)
7138            ),
7139        );
7140        let (_job, seat, out) = self
7141            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7142                prompt: fix_prompt.clone(),
7143                spec,
7144                seat,
7145                cwd: wt.clone(),
7146                timeout,
7147                allow_write: true,
7148                sessions,
7149                artifacts: artifacts.clone(),
7150                stem: "fix-recovery".to_owned(),
7151                handover: None,
7152            })
7153            .await;
7154        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7155            rec.repair = Repair::WaitingForRestore { before: head };
7156            self.state.recovery = Some(rec);
7157            return self.stop_for_resource();
7158        }
7159        let failed = match &out {
7160            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7161            AgentOutcome::Quota(o) => {
7162                self.state.quota.push(QuotaLoss::from_report(
7163                    seat.key.clone(),
7164                    "fix",
7165                    o.quota.as_ref(),
7166                ));
7167                Some("rate limited (quota); the fixer could not run".to_owned())
7168            }
7169            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7170            AgentOutcome::Failed(e) => Some(e.clone()),
7171        };
7172        self.state.seats.insert(seat.key.clone(), seat);
7173        let coordination = self.coordinate(&wt).await?;
7174        let failed = match failed {
7175            // The agent's partial edits are not kept.
7176            Some(why) => {
7177                if let Err(e) = git::restore_to(&wt, &head).await {
7178                    return self
7179                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7180                        .await;
7181                }
7182                Some(why)
7183            }
7184            None => {
7185                if let Ok(r) = git::rescue_commit(
7186                    &wt,
7187                    "magi: recovery repair of the failed verification (uncommitted work)",
7188                )
7189                .await
7190                {
7191                    self.state.note_withheld("fix", &r.withheld);
7192                }
7193                None
7194            }
7195        };
7196        let after = git::rev_parse(&wt, "HEAD").await?;
7197        drop(coordination);
7198        self.state.event(
7199            "recovery",
7200            match &failed {
7201                Some(why) => format!("repair: nothing kept ({why})"),
7202                None if after != head => {
7203                    format!("repair: committed {}", short(&after))
7204                }
7205                None => "repair: the fixer made no commit".to_owned(),
7206            },
7207        );
7208        rec.repair = Repair::Done {
7209            before: head.clone(),
7210            committed: after != head,
7211            after,
7212            failed,
7213        };
7214        self.state.recovery = Some(rec);
7215        self.state.save()?;
7216        Ok(())
7217    }
7218
7219    /// A repair whose rollback could not be confirmed: the run is blocked and
7220    /// resumable, and the unconfirmed state is never reviewed.
7221    async fn stop_recovery(
7222        &mut self,
7223        mut rec: crate::recovery::RecoveryRecord,
7224        head: &str,
7225        why: String,
7226    ) -> Result<()> {
7227        // `Started` stays recorded: a resume retries the restore.
7228        rec.repair = crate::recovery::Repair::Started {
7229            before: head.to_owned(),
7230        };
7231        self.state.recovery = Some(rec);
7232        self.state
7233            .event("recovery", format!("repair could not be undone: {why}"));
7234        self.state.status = RunStatus::Blocked;
7235        self.state.save()?;
7236        bail!("recovery repair could not be rolled back: {why}")
7237    }
7238
7239    async fn review_loop(&mut self) -> Result<()> {
7240        if self.hold_base_sync().await? {
7241            return Ok(());
7242        }
7243        loop {
7244            if self
7245                .state
7246                .base_sync
7247                .as_ref()
7248                .is_some_and(|s| s.conflict.is_some())
7249            {
7250                return Ok(());
7251            }
7252            if self.catchup_repairable() {
7253                let record = self.state.reviews.last().expect("repairable round").clone();
7254                let winner = self
7255                    .state
7256                    .winner()
7257                    .cloned()
7258                    .context("catch-up repair has no winner")?;
7259                if !self.fix_review_round(&winner, record).await? {
7260                    return Ok(());
7261                }
7262            }
7263            self.review_loop_pass().await?;
7264            if !self.catchup_repairable() {
7265                return Ok(());
7266            }
7267        }
7268    }
7269
7270    /// Derive an owed catch-up repair from durable round evidence, including
7271    /// reentry after a crash before the fixer was dispatched.
7272    fn catchup_repairable(&self) -> bool {
7273        self.state.reviews.len() < self.state.config.graph.review_rounds
7274            && self.state.reviews.last().is_some_and(|r| {
7275                !r.clean
7276                    && r.blocking == 0
7277                    && r.fix.is_none()
7278                    && r.e2e_status() == E2eStatus::Failed
7279            })
7280    }
7281
7282    async fn review_loop_pass(&mut self) -> Result<()> {
7283        // A base that would not rebase is a person's decision, not a review
7284        // round: nothing here would change the answer, and reviewers and a
7285        // fixer would be spending real budget on a tree that cannot land
7286        // regardless of what they find.
7287        if self
7288            .state
7289            .base_sync
7290            .as_ref()
7291            .is_some_and(|s| s.conflict.is_some())
7292        {
7293            return Ok(());
7294        }
7295        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7296        // agent files with `magi task add` name the run that paid for it. The
7297        // prompt overlay is cloned alongside it because the waves borrow it
7298        // while `self` is mutably borrowed by the node's own bookkeeping.
7299        let run_id = self.state.id.clone();
7300        let prompts = self.state.config.prompts.clone();
7301        let Some(winner) = self.state.winner().cloned() else {
7302            return Ok(());
7303        };
7304        let granted_review = self
7305            .state
7306            .repair_grants
7307            .last()
7308            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7309            .cloned();
7310        let fresh_review = granted_review
7311            .as_ref()
7312            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7313        let max_rounds = granted_review
7314            .as_ref()
7315            .map_or(self.state.config.graph.review_rounds, |g| {
7316                g.review_start.saturating_add(1)
7317            });
7318        // A clean round, an exhausted round budget, or a stalled tree (see
7319        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7320        // they are recorded — recomputed here, not read off `status`, so a
7321        // reentry into a run that already stopped restates the identical
7322        // verdict instead of silently handing back whatever an earlier node
7323        // in this same walk clobbered `status` to (a solo-candidate
7324        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7325        // below runs an empty range once the budget is spent, and would
7326        // otherwise fall through without touching `status` at all.
7327        if let Some(status) =
7328            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7329        {
7330            // A reentry after a crash between the last round's save and
7331            // `stop_reviewing` reaches the hand-off here, not there.
7332            if status == RunStatus::Gating {
7333                self.record_contested_handoff();
7334            }
7335            self.state.status = status;
7336            self.state.save()?;
7337            return Ok(());
7338        }
7339        self.state.status = RunStatus::Reviewing;
7340        // A last recorded round whose own verification never resolved
7341        // (`ResourceBlocked` — the shared build cache, not the patch) is
7342        // never a concluded round, whatever the round budget says: starting
7343        // a fresh round on top of it would spend a whole new reviewer wave
7344        // re-reading an unchanged patch instead of just retrying the one
7345        // check that actually needs it, and once the budget is spent the
7346        // loop below has nothing left to do at all (its range is empty).
7347        // Retry that check directly instead, exactly the same retry
7348        // `stop_reviewing` already does for its own catch-up case.
7349        if !fresh_review
7350            && self.state.reviews.last().is_some_and(|r| {
7351                r.e2e_status() == E2eStatus::ResourceBlocked
7352                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7353            })
7354        {
7355            let shell = self.state.config.shell();
7356            return self
7357                .stop_unresolved_review(
7358                    "the last round's own verification never resolved",
7359                    &shell,
7360                    &winner.worktree,
7361                )
7362                .await;
7363        }
7364
7365        if granted_review.is_none() {
7366            self.recovery_repair(&winner).await?;
7367        }
7368        if self.resource_halt()? {
7369            return Ok(());
7370        }
7371
7372        let repo = self.state.repo.clone();
7373        let root = self.state.worktree_root();
7374        let language = self.state.config.graph.language.clone();
7375        let sessions = self.state.config.graph.sessions;
7376        let artifacts = self.merge_repair_artifacts();
7377        let base = self.landing_base();
7378        let base_short = short(&base);
7379        let reviewers = self.roles.reviewers.clone();
7380        let shell = self.state.config.shell();
7381
7382        for round in (self.state.reviews.len() + 1)..=max_rounds {
7383            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7384            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7385            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7386            // The prior round's own record, already persisted — never a
7387            // hand-carried variable of just its failing output: that is
7388            // exactly what let a round's e2e result drift out of sync with
7389            // which commit it was actually about (see `SCHEMA`'s doc for
7390            // schema 8). Judged against `head`, the commit reviewers are
7391            // about to look at now, so the summary always reads as "an
7392            // earlier head" here — this round's own patch has not been
7393            // checked yet.
7394            let prev_verification = self
7395                .state
7396                .reviews
7397                .last()
7398                .and_then(|r| r.verification_summary(&head));
7399            // Only the first round of a run that took a branch over: later
7400            // rounds have this run's own history.
7401            let prior_section = match (&self.state.recovery, round) {
7402                (Some(rec), 1) if self.state.reviews.is_empty() => {
7403                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7404                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7405                            Some(crate::recovery::head_of(
7406                                &git::diff(&winner.worktree, reviewed, "HEAD")
7407                                    .await
7408                                    .unwrap_or_default(),
7409                                crate::recovery::SINCE_DIFF_MAX,
7410                            ))
7411                        }
7412                        _ => None,
7413                    };
7414                    Some(prompt::recovery_review(rec, since.as_deref()))
7415                }
7416                _ => None,
7417            };
7418
7419            // Each reviewer gets its own detached checkout of exactly this
7420            // commit: nobody can perturb the winner's tree, and the fixer can
7421            // keep working without racing a reviewer.
7422            let mut jobs = Vec::new();
7423            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7424                self.coordinate(&repo).await?
7425            } else {
7426                None
7427            };
7428            for (r, spec) in reviewers.iter().cloned().enumerate() {
7429                let wt = root.join(format!("review-{}", r + 1));
7430                // `clean -fdx` in a reset wipes setup's products, so every
7431                // round sets the seat up again.
7432                if wt.exists() {
7433                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7434                } else {
7435                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7436                        None
7437                    } else {
7438                        self.coordinate(&repo).await?
7439                    };
7440                    git::worktree_add_detached(&repo, &wt, &head).await?;
7441                }
7442                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7443                    None
7444                } else {
7445                    self.coordinate(&repo).await?
7446                };
7447                self.setup_seat_worktree(
7448                    &repo,
7449                    &wt,
7450                    false,
7451                    coordination.as_ref().or(_setup_lease.as_ref()),
7452                )
7453                .await?;
7454                let seat_key = format!("review-{}", r + 1);
7455                // The seat starts the round on whoever answered it last, not
7456                // on the agent the spec names, so a failure is not re-paid.
7457                let spec = pick_start_spec(
7458                    &self.roles.reviewer_roster,
7459                    spec,
7460                    self.state.seat_history.get(&seat_key),
7461                );
7462                let seat = self.seat(&seat_key, &spec.id);
7463                jobs.push(SeatJob {
7464                    prompt: prompt::review(&prompt::ReviewCtx {
7465                        instruction: &self.state.instruction,
7466                        branch: &winner.branch,
7467                        base_short: &base_short,
7468                        stat: &stat,
7469                        patch: &patch,
7470                        verification: prev_verification.as_ref(),
7471                        prior: prior_section.as_deref(),
7472                        reviewers: reviewers.len(),
7473                        round,
7474                        rounds: max_rounds,
7475                        // A review-only run has no rankings, so nothing
7476                        // competed for this patch and the reviewer is told so.
7477                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7478                        lens: Lens::for_seat(r),
7479                        language: &language,
7480                        github_language: &self.state.config.graph.github_language,
7481                    }),
7482                    spec,
7483                    seat,
7484                    cwd: wt,
7485                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7486                    allow_write: false,
7487                    sessions,
7488                    artifacts: artifacts.clone(),
7489                    stem: format!("review-{round}-{}", r + 1),
7490                    handover: None,
7491                });
7492            }
7493
7494            drop(coordination);
7495            self.state.event(
7496                "review",
7497                format!(
7498                    "round {round}: {} reviewers on {}",
7499                    jobs.len(),
7500                    short(&head)
7501                ),
7502            );
7503            let mut quota_losses = Vec::new();
7504            let review_retries = self.state.config.graph.retries;
7505            let review_cache = self.state.config.cache_dir();
7506            let ctx = WaveCtx {
7507                carry_seats: true,
7508                pauses: Some((&self.pause, &self.interrupt)),
7509                run: &run_id,
7510                node: "review",
7511                prompts: &prompts,
7512                cache: review_cache.as_deref(),
7513                round: Some(round),
7514            };
7515            let results = ask_json_wave::<Review>(
7516                jobs,
7517                Arc::clone(&self.sem),
7518                review_retries,
7519                &self.roles.reviewer_roster,
7520                &ctx,
7521                &mut quota_losses,
7522                &mut self.state,
7523                &|_: &Review| Ok(()),
7524            )
7525            .await;
7526            if self.state.resource_block.is_some() {
7527                return self.stop_for_resource();
7528            }
7529            // Counted before the move below: how many of *this* round's
7530            // reviewer seats were lost to their own rate limit, as opposed to
7531            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7532            let round_quota_missing = quota_losses.len();
7533            self.state.quota.extend(quota_losses);
7534
7535            let mut records = Vec::new();
7536            let mut all_findings = Vec::new();
7537            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7538                let agent_id = seat.agent.clone();
7539                self.state.seats.insert(seat.key.clone(), seat);
7540                let mut record = ReviewRecord {
7541                    reviewer: r + 1,
7542                    agent: agent_id,
7543                    summary: String::new(),
7544                    findings: Vec::new(),
7545                    vote: None,
7546                    failed: None,
7547                    duration_ms: 0,
7548                    // Set for both outcomes: `failed: Some(_)` with
7549                    // `attempts > 0` is a seat every retry still lost, not a
7550                    // recovered one — only `failed: None` with `attempts > 0`
7551                    // reads as "answered after a nudge" (see this field's own
7552                    // doc).
7553                    attempts,
7554                };
7555                match res {
7556                    Ok((review, out)) => {
7557                        // Sanitized here, at the point every other piece of
7558                        // agent prose in this file is (candidate summaries,
7559                        // deliberation turns, vote reasons): a reviewer's own
7560                        // words are the one thing about it that could name
7561                        // it, and reconsideration below broadcasts this same
7562                        // summary and these same findings to every other
7563                        // seat on the panel.
7564                        record.summary =
7565                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7566                        record.vote = Some(review.vote);
7567                        record.duration_ms = out.duration_ms;
7568                        for (n, mut f) in review.findings.into_iter().enumerate() {
7569                            // ids are magi's, never the agent's: the fixer's
7570                            // adoption report is keyed by them.
7571                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7572                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7573                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7574                            // `file` is agent-supplied prose too, never
7575                            // checked against the real tree — the same
7576                            // exposure `title`/`detail` above have, just in
7577                            // a field easy to forget because it looks like a
7578                            // path rather than free text.
7579                            f.file = f
7580                                .file
7581                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7582                            all_findings.push(f.clone());
7583                            record.findings.push(f);
7584                        }
7585                        self.state.event(
7586                            "review",
7587                            format!(
7588                                "round {round}: reviewer {} voted {} with {} finding(s)",
7589                                r + 1,
7590                                review.vote.label(),
7591                                record.findings.len()
7592                            ),
7593                        );
7594                    }
7595                    Err(e) => {
7596                        record.failed = Some(e.to_string());
7597                        self.state.event(
7598                            "review",
7599                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7600                        );
7601                    }
7602                }
7603                records.push(record);
7604            }
7605
7606            // Tally the round's votes and, if they split, spend the one
7607            // round of reconsideration the split -> deliberate -> revote
7608            // shape `judge`/`vote` use for the panel, sized down to what a
7609            // read-only review round can afford: one round, and a revote
7610            // rather than an argument, because the panel already wrote its
7611            // reasoning down as findings the first time around.
7612            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7613            let vote_split =
7614                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7615            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7616            if vote_split {
7617                self.state.event(
7618                    "review",
7619                    format!(
7620                        "round {round}: votes split ({}) — one round of reconsideration",
7621                        initial_votes
7622                            .iter()
7623                            .map(|v| v.label())
7624                            .collect::<Vec<_>>()
7625                            .join(", ")
7626                    ),
7627                );
7628                // Seats read every seat's findings and votes, still numbered
7629                // and never named — the same anonymity `review` itself keeps.
7630                let panel: Vec<ReviewSeatReport<'_>> = records
7631                    .iter()
7632                    .filter_map(|r| {
7633                        r.vote.map(|vote| ReviewSeatReport {
7634                            reviewer: r.reviewer,
7635                            vote,
7636                            summary: &r.summary,
7637                            findings: &r.findings,
7638                        })
7639                    })
7640                    .collect();
7641
7642                let mut jobs = Vec::new();
7643                let mut seats_at = Vec::new();
7644                for (r, spec) in reviewers.iter().cloned().enumerate() {
7645                    // A seat with no initial vote has nothing to reconsider
7646                    // from and stays absent, the same as it stayed absent
7647                    // from `panel` above.
7648                    if records[r].vote.is_none() {
7649                        continue;
7650                    }
7651                    let wt = root.join(format!("review-{}", r + 1));
7652                    let seat_key = format!("review-{}", r + 1);
7653                    let spec = self.occupant(&seat_key, spec);
7654                    let seat = self.seat(&seat_key, &spec.id);
7655                    // A seat with no live session has already forgotten the
7656                    // initial review's prompt — restate the patch it is
7657                    // voting on, the same as `deliberate`/`vote` do for a
7658                    // judge in the same position.
7659                    // The panel already carries this seat's own review and
7660                    // vote, so restating the patch makes the prompt whole for
7661                    // a seat handed to another agent.
7662                    let build = |with_patch: bool| {
7663                        prompt::review_reconsider(&ReviewReconsiderCtx {
7664                            instruction: &self.state.instruction,
7665                            reviewer: r + 1,
7666                            lens: Lens::for_seat(r),
7667                            panel: &panel,
7668                            patch: with_patch.then_some(ReviewPatch {
7669                                branch: &winner.branch,
7670                                base_short: &base_short,
7671                                stat: &stat,
7672                                patch: &patch,
7673                            }),
7674                            round,
7675                            rounds: max_rounds,
7676                            language: &language,
7677                        })
7678                    };
7679                    let full = build(true);
7680                    let prompt = if has_context(&spec, &seat, sessions) {
7681                        build(false)
7682                    } else {
7683                        full.clone()
7684                    };
7685                    jobs.push(SeatJob {
7686                        prompt,
7687                        spec,
7688                        seat,
7689                        cwd: wt,
7690                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7691                        allow_write: false,
7692                        sessions,
7693                        artifacts: artifacts.clone(),
7694                        stem: format!("review-{round}-reconsider-{}", r + 1),
7695                        handover: Some(full),
7696                    });
7697                    seats_at.push(r);
7698                }
7699
7700                let mut recon_quota_losses = Vec::new();
7701                let recon_cache = self.state.config.cache_dir();
7702                let recon_ctx = WaveCtx {
7703                    carry_seats: true,
7704                    pauses: Some((&self.pause, &self.interrupt)),
7705                    run: &run_id,
7706                    node: "review",
7707                    prompts: &prompts,
7708                    cache: recon_cache.as_deref(),
7709                    round: Some(round),
7710                };
7711                let recon_results = ask_json_wave::<ReviewRevote>(
7712                    jobs,
7713                    Arc::clone(&self.sem),
7714                    review_retries,
7715                    &self.roles.reviewer_roster,
7716                    &recon_ctx,
7717                    &mut recon_quota_losses,
7718                    &mut self.state,
7719                    &|_: &ReviewRevote| Ok(()),
7720                )
7721                .await;
7722                if self.state.resource_block.is_some() {
7723                    return self.stop_for_resource();
7724                }
7725                self.state.quota.extend(recon_quota_losses);
7726
7727                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7728                    let agent_id = seat.agent.clone();
7729                    self.state.seats.insert(seat.key.clone(), seat);
7730                    let mut rec = ReviewRevoteRecord {
7731                        reviewer: r + 1,
7732                        agent: agent_id,
7733                        vote: None,
7734                        reason: String::new(),
7735                        failed: None,
7736                    };
7737                    match res {
7738                        Ok((rv, _)) => {
7739                            rec.vote = Some(rv.vote);
7740                            rec.reason =
7741                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7742                            self.state.event(
7743                                "review",
7744                                format!(
7745                                    "round {round}: reviewer {} revoted {}",
7746                                    r + 1,
7747                                    rv.vote.label()
7748                                ),
7749                            );
7750                        }
7751                        Err(e) => {
7752                            rec.failed = Some(e.to_string());
7753                            self.state.event(
7754                                "review",
7755                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7756                            );
7757                        }
7758                    }
7759                    reconsideration.push(rec);
7760                }
7761            } else if initial_votes.len() > 1 {
7762                self.state.event(
7763                    "review",
7764                    format!(
7765                        "round {round}: votes agreed ({}) — no reconsideration",
7766                        initial_votes[0].label()
7767                    ),
7768                );
7769            }
7770
7771            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7772            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7773            // A round that already has a blocking finding and a round left to
7774            // try is going back to the fixer no matter what `verify.e2e`
7775            // says, so running it first only spends the loop's slowest step
7776            // (minutes, for a Rust repo's full test suite) on a head about
7777            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7778            // runs once a round has no blocking findings left (see
7779            // `round_is_clean`, which a deferred — empty — `e2e` can never
7780            // satisfy since `blocking` is nonzero whenever this branch is
7781            // taken), and `stop_reviewing` forces a real run before it will
7782            // ever read a deferred round as green.
7783            let defer_e2e =
7784                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7785            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7786                let reason =
7787                    format!("{blocking} blocking finding(s) already required a fix this round");
7788                self.state.event(
7789                    "verify",
7790                    format!(
7791                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7792                         {}); it will run once a round has none left",
7793                        short(&head)
7794                    ),
7795                );
7796                (Vec::new(), false, true, Some(reason))
7797            } else {
7798                let e2e_commands = self.state.config.verify.e2e.clone();
7799                let cache_dir = self.state.config.cache_dir();
7800                let context = format!("round {round}");
7801                let wait = self.repository_wait();
7802                let (e2e, verify_retried) = with_cache_lease(
7803                    &mut self.state,
7804                    cache_dir.as_deref(),
7805                    "e2e",
7806                    "e2e",
7807                    &winner.worktree,
7808                    &head,
7809                    verify_timeout,
7810                    &context,
7811                    &wait,
7812                    |state, budget| {
7813                        let shell = shell.clone();
7814                        let e2e_commands = e2e_commands.clone();
7815                        let worktree = winner.worktree.clone();
7816                        let context = context.clone();
7817                        let winner = winner.clone();
7818                        async move {
7819                            if !e2e_commands.is_empty() {
7820                                // The suite certifies one SHA. Format before it
7821                                // runs, or the commit `pre_gate` makes at the
7822                                // gate owes the whole suite again.
7823                                Self::run_pre_gate(state, &winner).await;
7824                            }
7825                            run_e2e_with_retry(
7826                                state,
7827                                &shell,
7828                                &e2e_commands,
7829                                &worktree,
7830                                budget,
7831                                &context,
7832                                Some(round),
7833                            )
7834                            .await
7835                        }
7836                    },
7837                )
7838                .await?;
7839                (e2e, verify_retried, false, None)
7840            };
7841
7842            let expected = records.len();
7843            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7844            let incomplete = answered < expected;
7845            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7846            let policy = self.state.config.graph.incomplete_review;
7847            let clean = round_is_clean(
7848                blocking,
7849                e2e_ok,
7850                answered,
7851                expected,
7852                round_quota_missing,
7853                policy,
7854            );
7855
7856            let mut round_record = ReviewRound {
7857                round,
7858                head: head.clone(),
7859                verified_head: None,
7860                verified_at: None,
7861                reviews: records,
7862                e2e,
7863                verify_retried,
7864                e2e_deferred,
7865                e2e_defer_reason,
7866                fix: None,
7867                blocking,
7868                answered,
7869                expected,
7870                clean,
7871                progressed: false,
7872                vote_split,
7873                reconsideration,
7874                verdict: None,
7875            };
7876            // The final vote per seat is its revote where reconsideration
7877            // ran and answered, its initial vote otherwise — the same
7878            // fallback `tally` uses for a judge whose private vote failed.
7879            round_record.verdict = ReviewVote::worst(
7880                round_record
7881                    .final_votes()
7882                    .into_iter()
7883                    .map(|(_, _, vote)| vote),
7884            );
7885            // Which commit and when magi actually attempted to check —
7886            // known the moment a command was dispatched against `head`,
7887            // whether or not it finished: a resource-blocked attempt still
7888            // targeted a specific commit at a specific time, and leaving
7889            // that unrecorded is exactly what made `verification_summary`
7890            // report a fresh attempt as "commit unknown ... recorded before
7891            // this was tracked", indistinguishable from a genuinely old,
7892            // untracked record. Only a deferred or unconfigured round never
7893            // ran at all and has nothing to record — see
7894            // `ReviewRound::verified_head`'s own doc.
7895            if !matches!(
7896                round_record.e2e_status(),
7897                E2eStatus::Deferred | E2eStatus::NotConfigured
7898            ) {
7899                // HEAD, not the reviewed `head`: `pre_gate` may have committed
7900                // mechanical fixes before the commands ran.
7901                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
7902                round_record.verified_at = Some(Timestamp::now());
7903            }
7904
7905            if incomplete {
7906                let missing: Vec<String> = round_record
7907                    .reviews
7908                    .iter()
7909                    .filter(|r| r.failed.is_some())
7910                    .map(|r| format!("review-{}", r.reviewer))
7911                    .collect();
7912                self.state.event(
7913                    "review",
7914                    format!(
7915                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
7916                        missing.join(", ")
7917                    ),
7918                );
7919            }
7920
7921            if clean {
7922                self.state.event(
7923                    "review",
7924                    if incomplete && policy == IncompleteReviewPolicy::Warn {
7925                        format!(
7926                            "round {round}: clean (warn policy, incomplete panel) — no \
7927                             blocking findings from the seats that answered, verification green"
7928                        )
7929                    } else if incomplete {
7930                        format!(
7931                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
7932                             quorum) — no blocking findings from the seats that answered, \
7933                             verification green",
7934                            expected - answered
7935                        )
7936                    } else {
7937                        format!("round {round}: clean — no blocking findings, verification green")
7938                    },
7939                );
7940                self.state.reviews.push(round_record);
7941                self.state.status = RunStatus::Gating;
7942                self.state.save()?;
7943                return Ok(());
7944            }
7945
7946            // Nothing was raised and verification passed, but not every seat
7947            // answered and `round_is_clean` still refused to call it clean —
7948            // either a seat is missing for a reason other than its own quota
7949            // (a crash, a timeout, unparsable output — worth another try), or
7950            // every seat that could have answered lost its quota and nobody
7951            // is left to decide on: re-review rather than send the fixer
7952            // after a round with nothing to fix.
7953            if incomplete && blocking == 0 && e2e_ok {
7954                self.state.reviews.push(round_record);
7955                self.state.save()?;
7956                if round == max_rounds {
7957                    self.state.status = RunStatus::Blocked;
7958                    self.state.event(
7959                        "review",
7960                        format!(
7961                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
7962                             refusing to call it clean",
7963                            expected - answered
7964                        ),
7965                    );
7966                    return Ok(());
7967                }
7968                continue;
7969            }
7970
7971            // Nothing for the fixer to act on (`blocking == 0`) and the only
7972            // reason this round is not clean is that magi itself never got
7973            // a command to run — the shared build cache, not the patch (see
7974            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
7975            // the fixer would invite a change to appease contention that has
7976            // nothing to do with the diff, and would leave this attempt
7977            // sitting in the next round's prompt as if it were about an
7978            // earlier, superseded commit rather than what it actually is:
7979            // the same head, still waiting to be checked. Wait for it the
7980            // same way the final round's own contention is already handled,
7981            // whatever round this happens to be.
7982            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
7983                self.state.reviews.push(round_record);
7984                return self
7985                    .stop_unresolved_review(
7986                        "the round's own verification could not run",
7987                        &shell,
7988                        &winner.worktree,
7989                    )
7990                    .await;
7991            }
7992
7993            if round == max_rounds {
7994                self.state.reviews.push(round_record);
7995                return self
7996                    .stop_reviewing(
7997                        &format!(
7998                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
7999                        ),
8000                        &shell,
8001                        &winner.worktree,
8002                    )
8003                    .await;
8004            }
8005
8006            if !self.fix_review_round(&winner, round_record).await? {
8007                return Ok(());
8008            }
8009        }
8010        Ok(())
8011    }
8012
8013    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8014    /// False means admission or continuation policy stopped the review loop.
8015    async fn fix_review_round(
8016        &mut self,
8017        winner: &Candidate,
8018        mut round_record: ReviewRound,
8019    ) -> Result<bool> {
8020        let round = round_record.round;
8021        let shell = self.state.config.shell();
8022        let step = self.run_fix_round(winner, &mut round_record).await?;
8023        if matches!(step, FixStep::Resource) {
8024            self.stop_for_resource()?;
8025            return Ok(false);
8026        }
8027        if self.state.reviews.len() < round {
8028            self.state.reviews.push(round_record);
8029        } else {
8030            self.state.reviews[round - 1] = round_record;
8031        }
8032        self.state.save()?;
8033
8034        // The fixer's own report never came back this round, even after
8035        // `continue_fix_report`'s own budget was spent on it — not an
8036        // ordinary "no report" (dropped stream, quota, plain failure),
8037        // which already reads that way and is left to the existing round
8038        // budget. Stopping here, rather than opening another round, is
8039        // what keeps a next reviewer/fixer wave from ever being
8040        // dispatched onto `winner.worktree` while whatever the seat's
8041        // last call may still have running there is unaccounted for: no
8042        // process liveness check exists (and none is being added — see
8043        // AGENTS.md/this task's own scope), so the only way to honour
8044        // "nothing starts before a valid report returns" is to not start
8045        // anything further on this worktree from this run at all.
8046        if matches!(step, FixStep::Recorded { report_lost: true }) {
8047            self.stop_reviewing(
8048                "the fixer's adoption report never came back, even after resuming its \
8049                         own seat; refusing to start another round against the same worktree \
8050                         while that is unresolved",
8051                &shell,
8052                &winner.worktree,
8053            )
8054            .await?;
8055            return Ok(false);
8056        }
8057
8058        let streak = self
8059            .state
8060            .reviews
8061            .iter()
8062            .rev()
8063            .take_while(|r| !r.progressed)
8064            .count();
8065        if streak >= STAGNANT_LIMIT {
8066            self.stop_reviewing(
8067                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8068                &shell,
8069                &winner.worktree,
8070            )
8071            .await?;
8072            return Ok(false);
8073        }
8074        Ok(true)
8075    }
8076
8077    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8078    async fn run_fix_round(
8079        &mut self,
8080        winner: &Candidate,
8081        round_record: &mut ReviewRound,
8082    ) -> Result<FixStep> {
8083        let round = round_record.round;
8084        let max_rounds = self.state.config.graph.review_rounds;
8085        let run_id = self.state.id.clone();
8086        let prompts = self.state.config.prompts.clone();
8087        let language = self.state.config.graph.language.clone();
8088        let sessions = self.state.config.graph.sessions;
8089        let artifacts = self.merge_repair_artifacts();
8090        let base = self.landing_base();
8091        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8092        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8093        let this_round_verification = round_record.verification_summary(&head);
8094        let all_findings: Vec<_> = round_record
8095            .reviews
8096            .iter()
8097            .flat_map(|r| r.findings.iter().cloned())
8098            .collect();
8099        // Fix. The winner's own implementer seat continues its conversation:
8100        // the competition is over, so context is pure benefit now.
8101        let blocking_findings: Vec<_> = all_findings
8102            .iter()
8103            .filter(|f| f.severity.blocks())
8104            .cloned()
8105            .collect();
8106        let fix_prompt = prompt::fix_in(
8107            &self.state.instruction,
8108            &blocking_findings,
8109            this_round_verification.as_ref(),
8110            round,
8111            max_rounds,
8112            &language,
8113            &self.state.config.graph.github_language,
8114        );
8115        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8116        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8117        let (job, seat, out) = self
8118            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8119                prompt: fix_prompt.clone(),
8120                spec,
8121                seat,
8122                cwd: winner.worktree.clone(),
8123                timeout,
8124                allow_write: true,
8125                sessions,
8126                artifacts: artifacts.clone(),
8127                stem: format!("fix-{round}"),
8128                handover: None,
8129            })
8130            .await;
8131        // Not asked: the round is not recorded (so a resume repeats it),
8132        // no fixer was handed over to, and the seat is left as it was.
8133        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8134            return Ok(FixStep::Resource);
8135        }
8136        let agent_id = seat.agent.clone();
8137
8138        let mut fix = FixRecord {
8139            agent: agent_id,
8140            addressed: Vec::new(),
8141            rejected: Vec::new(),
8142            notes: String::new(),
8143            committed: false,
8144            failed: None,
8145            duration_ms: 0,
8146            continuation: None,
8147        };
8148        let mut continuation = ContinuationRecord::not_needed();
8149        let mut final_seat = seat.clone();
8150        match out {
8151            AgentOutcome::Ok(o) => {
8152                fix.duration_ms = o.duration_ms;
8153                let parsed = verdict::extract_json::<FixReport>(&o.text);
8154                // A parsed report standing next to a command this same
8155                // reply's own CLI never confirmed the exit status of is
8156                // not a resolved answer — the identical `CommandEvidence`
8157                // `state.jobs` renders, read here instead of only on
8158                // display, per the completion judgment and the shown
8159                // record needing to agree.
8160                let incomplete_reason = match &parsed {
8161                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8162                        "the reply parsed, but it reported a command whose own CLI never \
8163                             confirmed an exit status"
8164                            .to_owned(),
8165                    ),
8166                    Ok(_) => None,
8167                    Err(e) => Some(e.to_string()),
8168                };
8169                match incomplete_reason {
8170                    None => {
8171                        let report = parsed.expect("checked Ok above");
8172                        fix.addressed = report.addressed;
8173                        fix.rejected = report.rejected;
8174                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8175                    }
8176                    Some(reason) => {
8177                        let (resumed_seat, resolved, failure, cont) = self
8178                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8179                            .await;
8180                        fix.duration_ms += cont.cumulative_wait_ms;
8181                        continuation = cont;
8182                        final_seat = resumed_seat;
8183                        match resolved {
8184                            Some(report) => {
8185                                fix.addressed = report.addressed;
8186                                fix.rejected = report.rejected;
8187                                fix.notes =
8188                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8189                            }
8190                            None => fix.failed = failure,
8191                        }
8192                    }
8193                }
8194            }
8195            // The CLI's raw error JSON is not a fix report to parse.
8196            AgentOutcome::Dropped(o) => {
8197                fix.duration_ms = o.duration_ms;
8198                let why = o
8199                    .dropped
8200                    .as_ref()
8201                    .map(|d| d.why.as_str())
8202                    .unwrap_or("the CLI ended the stream without delivering its answer");
8203                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8204            }
8205            AgentOutcome::Quota(o) => {
8206                self.state.quota.push(QuotaLoss::from_report(
8207                    final_seat.key.clone(),
8208                    "fix",
8209                    o.quota.as_ref(),
8210                ));
8211                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8212            }
8213            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8214        }
8215        if self.state.resource_block.is_some() {
8216            self.state.seats.insert(final_seat.key.clone(), final_seat);
8217            return Ok(FixStep::Resource);
8218        }
8219        fix.continuation = Some(continuation);
8220        self.state.seats.insert(final_seat.key.clone(), final_seat);
8221        let coordination = self.coordinate(&winner.worktree).await?;
8222        if let Ok(r) = git::rescue_commit(
8223            &winner.worktree,
8224            &format!("magi: review round {round} fixes (uncommitted work)"),
8225        )
8226        .await
8227        {
8228            self.state.note_withheld("fix", &r.withheld);
8229        }
8230        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8231        fix.committed = after != before;
8232        // Judged by what `git` says moved against base, never by the
8233        // fixer's own `addressed`/`rejected` count — see
8234        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8235        // `patch` snapshot above: swallowing this error would default
8236        // `diff_after` to empty, which almost always differs from a
8237        // non-empty `patch` and reads as "progressed" — exactly backwards
8238        // for a `git` failure the stagnation check cannot see through.
8239        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8240        drop(coordination);
8241        let progressed = diff_after != patch;
8242        let commit_note = if fix.committed {
8243            "committed"
8244        } else {
8245            "NO new commit"
8246        };
8247        let tree_note = if progressed {
8248            "changed vs base"
8249        } else {
8250            "unchanged vs base"
8251        };
8252        self.state.event(
8253            "fix",
8254            match &fix.failed {
8255                // Distinct on purpose from "0 addressed, 0 rejected": the
8256                // fixer's own diff still landed (blocking counts do keep
8257                // falling round over round), only its adoption report did
8258                // not come back, so this must never read like every
8259                // finding was reviewed and declined.
8260                Some(reason) => {
8261                    format!(
8262                        "round {round}: fixer's adoption report was lost ({reason}); \
8263                             {commit_note}, tree {tree_note}"
8264                    )
8265                }
8266                None => format!(
8267                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8268                         {tree_note}{}",
8269                    fix.addressed.len(),
8270                    fix.rejected.len(),
8271                    if continuation.outcome == ContinuationOutcome::Resumed {
8272                        format!(
8273                            " (adoption report recovered after {} continuation(s))",
8274                            continuation.attempts
8275                        )
8276                    } else {
8277                        String::new()
8278                    },
8279                ),
8280            },
8281        );
8282        round_record.fix = Some(fix);
8283        round_record.progressed = progressed;
8284        Ok(FixStep::Recorded {
8285            report_lost: matches!(
8286                continuation.outcome,
8287                ContinuationOutcome::Exhausted
8288                    | ContinuationOutcome::QuotaLost
8289                    | ContinuationOutcome::NoSession
8290            ),
8291        })
8292    }
8293
8294    /// Decide, from the last recorded round's own verification, whether
8295    /// stopping the review loop is a hand-off or a genuine block.
8296    ///
8297    /// Called once the loop has given up trying — the round budget is spent,
8298    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8299    /// findings still open, never while a round is still clean or the
8300    /// incomplete-panel case handled inline above. Gate and e2e are facts
8301    /// about the tree; a lingering review finding is an opinion, and this
8302    /// workload's own `magi stats` puts reviewer precision low enough
8303    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8304    /// must not by itself stand between a green, verified change and the
8305    /// human who decides what to do with it. A red e2e is not an opinion, so
8306    /// that case still blocks, with the failing command and a tail of its
8307    /// output recorded here rather than left in `run.json` for someone to go
8308    /// find.
8309    ///
8310    /// A round that deferred its own e2e (see [`Config::graph`]'s
8311    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8312    /// only because nothing ran, and treating an empty list as a passing one
8313    /// here is exactly the "deferred painted green" bug this function exists
8314    /// to not have. When the last round's own verification never resolved —
8315    /// deferred on purpose, or a real attempt the shared build cache blocked
8316    /// — this makes (or retries) the real run, on the actual worktree this
8317    /// loop is about to stop touching, before deciding anything. A
8318    /// resource-blocked attempt is likewise never read as either green or
8319    /// red: it is evidence about the machine, not the patch (see
8320    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8321    /// blocked cache leaves this call without deciding rather than guessing
8322    /// — the caller retries on a later reentry.
8323    /// Record, once, that the review loop handed off over a blocking finding
8324    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8325    /// `land` asks the owner even with `land_approval` off. Called from every
8326    /// path that concludes `Gating`; a reentry keeps the first record.
8327    fn record_contested_handoff(&mut self) {
8328        if self.state.contested_handoff.is_some() {
8329            return;
8330        }
8331        let Some(contested) = self
8332            .state
8333            .reviews
8334            .last()
8335            .and_then(ReviewRound::contested_handoff)
8336        else {
8337            return;
8338        };
8339        self.state.event(
8340            "review",
8341            format!(
8342                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8343                 wait for the owner's approval",
8344                contested.findings.len(),
8345                contested.rejecters.len()
8346            ),
8347        );
8348        self.state.contested_handoff = Some(contested);
8349    }
8350
8351    async fn stop_unresolved_review(
8352        &mut self,
8353        why: &str,
8354        shell: &[String],
8355        worktree: &Path,
8356    ) -> Result<()> {
8357        self.stop_reviewing_inner(why, shell, worktree, true).await
8358    }
8359
8360    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8361        self.stop_reviewing_inner(why, shell, worktree, false).await
8362    }
8363
8364    async fn stop_reviewing_inner(
8365        &mut self,
8366        why: &str,
8367        shell: &[String],
8368        worktree: &Path,
8369        repairable: bool,
8370    ) -> Result<()> {
8371        let round_idx = self.state.reviews.len() - 1;
8372        // A deferred round and a resource-blocked one are the same shape
8373        // here: neither has a real result yet, and both get one more
8374        // attempt. Read off `e2e_status` — the single source for this —
8375        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8376        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8377        // still retries instead of being read as a settled result the
8378        // instant it stops being empty.
8379        let needs_catchup_run = matches!(
8380            self.state.reviews[round_idx].e2e_status(),
8381            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8382        );
8383        if needs_catchup_run {
8384            let round = self.state.reviews[round_idx].round;
8385            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8386            let commands = self.state.config.verify.e2e.clone();
8387            let before_head = git::rev_parse(worktree, "HEAD").await?;
8388            let winner = self.state.winner().cloned();
8389            let cache_dir = self.state.config.cache_dir();
8390            let context = format!(
8391                "round {round}: verification unresolved, catching up before the final decision"
8392            );
8393            let wait = self.repository_wait();
8394            let (outcomes, verify_retried) = with_cache_lease(
8395                &mut self.state,
8396                cache_dir.as_deref(),
8397                "e2e",
8398                "e2e",
8399                worktree,
8400                &before_head,
8401                timeout,
8402                &context,
8403                &wait,
8404                |state, budget| {
8405                    let shell = shell.to_vec();
8406                    let commands = commands.clone();
8407                    let context = context.clone();
8408                    async move {
8409                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8410                            // Same reason as in the round itself: format before
8411                            // the suite, not after it.
8412                            Self::run_pre_gate(state, &winner).await;
8413                        }
8414                        run_e2e_with_retry(
8415                            state,
8416                            &shell,
8417                            &commands,
8418                            worktree,
8419                            budget,
8420                            &context,
8421                            Some(round),
8422                        )
8423                        .await
8424                    }
8425                },
8426            )
8427            .await?;
8428            // After `pre_gate`: the commit the commands actually ran against.
8429            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8430            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8431                self.state.record_base_progress(&attempted_head);
8432            }
8433            let last = &mut self.state.reviews[round_idx];
8434            last.e2e = outcomes;
8435            last.verify_retried = verify_retried;
8436            // Always the commit and time this attempt actually targeted,
8437            // whether or not it happens to equal the reviewed `head` and
8438            // whether or not a command finished — see
8439            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8440            // attempt is recorded too, so a later reader sees "attempted
8441            // again at T2" rather than silence.
8442            last.verified_head = Some(attempted_head);
8443            last.verified_at = Some(Timestamp::now());
8444            if verify_inconclusive(&last.e2e) {
8445                // Still not a real result: `e2e_deferred` is left exactly
8446                // as it was, so `needs_catchup_run` above reads
8447                // `ResourceBlocked` (via `e2e_status`, which checks
8448                // `resource_blocked` before `e2e_deferred`) and retries
8449                // again on the next reentry, rather than recording
8450                // contention as a red e2e and blocking the run on it.
8451                self.state.save()?;
8452                return Ok(());
8453            }
8454            last.e2e_deferred = false;
8455            // A complete panel may have been saved as unclean solely because
8456            // verification could not run. Refresh that verdict with the new
8457            // outcomes before a granted repair consumes the round's result.
8458            // Incomplete panels retain their original policy/quota decision.
8459            if last.answered == last.expected {
8460                last.clean = round_is_clean(
8461                    last.blocking,
8462                    last.e2e.iter().all(CommandOutcome::ok),
8463                    last.answered,
8464                    last.expected,
8465                    0,
8466                    self.state.config.graph.incomplete_review,
8467                );
8468            }
8469        }
8470        let last = &self.state.reviews[round_idx];
8471        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8472
8473        match last.e2e_status() {
8474            E2eStatus::Failed => {
8475                let red: Vec<String> = last
8476                    .e2e
8477                    .iter()
8478                    .filter(|o| !o.ok())
8479                    .map(|o| {
8480                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8481                            .map(|c| format!(" ({c})"))
8482                            .unwrap_or_default();
8483                        format!(
8484                            "`{}` -> {:?}{comparison}\n{}",
8485                            o.command,
8486                            o.code,
8487                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8488                        )
8489                    })
8490                    .collect();
8491                let can_repair = last.blocking == 0 && last.fix.is_none();
8492                self.state.reviews[round_idx].clean = false;
8493                self.state
8494                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8495                self.state.status = RunStatus::Blocked;
8496                if repairable
8497                    && can_repair
8498                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8499                {
8500                    self.state.status = RunStatus::Reviewing;
8501                }
8502            }
8503            // `needs_catchup_run` above already retried once this call; if
8504            // it is still blocked, this is magi's own admission it could
8505            // not get a command to run, never a verdict on the patch — the
8506            // run is left exactly where a later reentry can retry again.
8507            E2eStatus::ResourceBlocked => {
8508                self.state.event(
8509                    "review",
8510                    format!(
8511                        "{why}; e2e could not run (resource unavailable); not \
8512                         deciding yet"
8513                    ),
8514                );
8515            }
8516            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8517                self.state.event(
8518                    "review",
8519                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8520                );
8521                self.record_contested_handoff();
8522                self.state.status = RunStatus::Gating;
8523            }
8524        }
8525        self.state.save()?;
8526        Ok(())
8527    }
8528
8529    // ----------------------------------------------------------------- gate
8530
8531    async fn gate(&mut self) -> Result<()> {
8532        if self.hold_base_sync().await? {
8533            return Ok(());
8534        }
8535        // Judged by the review record itself, not by `status`: a solo
8536        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8537        // reentry (see `judge`), and trusting it here is exactly how a run
8538        // that exhausted its review budget got gated and merged a second
8539        // time around. `review_conclusion` recomputes the review loop's own
8540        // verdict from the round records themselves — `Gating` for a clean
8541        // round or a hand-off (see `stop_reviewing`), anything else means the
8542        // loop is still going or genuinely blocked.
8543        // A base the winner could not be replayed onto is a decision, not a
8544        // round: there is no landing tree to gate. Read as its own record for
8545        // the same reason the review verdict is.
8546        if self.state.status == RunStatus::Failed
8547            || self
8548                .state
8549                .base_sync
8550                .as_ref()
8551                .is_some_and(|s| s.conflict.is_some())
8552            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8553                != Some(RunStatus::Gating)
8554        {
8555            return Ok(());
8556        }
8557        let Some(winner) = self.state.winner().cloned() else {
8558            return Ok(());
8559        };
8560        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8561        self.state.reconcile_verification_head(&head);
8562        self.state.save()?;
8563        let wait = self.repository_wait();
8564        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8565            return Ok(());
8566        }
8567        if self.state.gate_ran {
8568            // `review_loop` derives its conclusion from the clean review
8569            // record on every reentry and therefore puts a completed run back
8570            // in `Gating`. A recorded gate is a stronger, terminal fact:
8571            // retain its original command output (or lack of any, for a repo
8572            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8573            // doc) and restore `Blocked` on a real failure rather than
8574            // pretending the command is still running or running it a second
8575            // time. `gate_ran == false` remains the only shape — unattempted,
8576            // or a resource-blocked retry — that may still need to execute a
8577            // command.
8578            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8579                self.state.status = RunStatus::Blocked;
8580                self.state.save()?;
8581            }
8582            return Ok(());
8583        }
8584        self.state.status = RunStatus::Gating;
8585        let mut outcomes = self.run_gate(&winner).await?;
8586        let mut attempted_head = self.state.gate_head.clone();
8587        loop {
8588            // A resource-blocked outcome means the gate command never actually
8589            // ran - the shared build cache could not be acquired or confirmed
8590            // fresh in time - which is evidence about the machine, not about
8591            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8592            // Recording it as a red gate would mark a run `Blocked` on nothing
8593            // but contention magi has already logged; leaving `self.state.gate`
8594            // empty and `self.state.gate_ran` false instead keeps the shape
8595            // this function already treats as "still needs to run" (see the
8596            // early-return above), so the next call retries the command
8597            // rather than concluding anything.
8598            if verify_inconclusive(&outcomes) {
8599                self.state.save()?;
8600                return Ok(());
8601            }
8602            if outcomes.iter().all(CommandOutcome::ok) {
8603                break;
8604            }
8605            let fixes_before = self.state.gate_fixes.len();
8606            match self.gate_fix_round(&winner, &outcomes).await? {
8607                GateFix::Retry => {
8608                    outcomes = self.run_gate(&winner).await?;
8609                    attempted_head = self.state.gate_head.clone();
8610                }
8611                GateFix::Stop => {
8612                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8613                    if self.state.gate_fixes.len() > fixes_before
8614                        && attempted_head.as_deref() != Some(current.as_str())
8615                        && verify_current_head(&mut self.state, &winner, &wait).await?
8616                    {
8617                        // A new SHA owes a gate even when a spent fixer changed only
8618                        // commit metadata. This does not grant another repair round.
8619                        outcomes = self.run_gate(&winner).await?;
8620                        attempted_head = self.state.gate_head.clone();
8621                    } else {
8622                        break;
8623                    }
8624                }
8625                GateFix::Defer => {
8626                    self.state.save()?;
8627                    return Ok(());
8628                }
8629            }
8630        }
8631        let passed = outcomes.iter().all(CommandOutcome::ok);
8632        self.state.gate = outcomes;
8633        self.state.gate_ran = true;
8634        self.state.gate_head = attempted_head;
8635        if !self.state.gate.is_empty()
8636            && !verify_inconclusive(&self.state.gate)
8637            && let Some(head) = self.state.gate_head.clone()
8638        {
8639            self.state.record_base_progress(&head);
8640        }
8641        self.state.save()?;
8642        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8643            return Ok(());
8644        }
8645        if !passed {
8646            self.state.status = RunStatus::Blocked;
8647            let spent = self.state.gate_fixes.len();
8648            self.state.event(
8649                "gate",
8650                if spent == 0 {
8651                    "gate failed; not merging".to_owned()
8652                } else {
8653                    format!("gate failed after {spent} gate-fix round(s); not merging")
8654                },
8655            );
8656        }
8657        self.state.save()?;
8658        Ok(())
8659    }
8660
8661    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8662    /// changed into one commit. Runs before `verify.e2e` in the review loop
8663    /// and again before the gate commands, always on the winner and never on
8664    /// a candidate awaiting judging.
8665    ///
8666    /// Before e2e as well as before the gate because command evidence belongs
8667    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8668    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8669    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8670    /// own call then finds nothing left to change. The commands must be
8671    /// idempotent; one that is not makes a commit per call.
8672    ///
8673    /// Never fails the run: a non-zero exit or timeout is a warning and a
8674    /// recorded outcome, and the gate remains the single arbiter. Nothing
8675    /// configured means nothing happens - no event, no commit. `commit_all`
8676    /// commits any leftover change under the neutral identity and returns
8677    /// `false` when the tree is clean, so no empty commit is ever made.
8678    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8679        let commands = state.config.verify.pre_gate.clone();
8680        if commands.is_empty() {
8681            return;
8682        }
8683        let shell = state.config.shell();
8684        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8685        let (outcomes, _) = run_commands(
8686            state,
8687            "pre_gate",
8688            "pre_gate",
8689            0,
8690            &shell,
8691            &commands,
8692            &winner.worktree,
8693            timeout,
8694        )
8695        .await;
8696        for o in &outcomes {
8697            if !o.ok() {
8698                tracing::warn!(
8699                    "pre_gate `{}` failed ({:?}); the gate decides",
8700                    o.command,
8701                    o.code
8702                );
8703            }
8704            state.event(
8705                "pre_gate",
8706                format!(
8707                    "`{}` -> {}",
8708                    o.command,
8709                    if o.ok() {
8710                        "pass".to_owned()
8711                    } else {
8712                        format!(
8713                            "FAIL ({:?})\n{}",
8714                            o.code,
8715                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8716                        )
8717                    }
8718                ),
8719            );
8720        }
8721        state.pre_gate = outcomes;
8722        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8723            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8724                Ok(head) => {
8725                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8726                    state.pre_gate_commit = Some(head);
8727                }
8728                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8729            },
8730            Ok(false) => {}
8731            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8732        }
8733        if let Err(e) = state.save() {
8734            tracing::warn!("could not persist the pre_gate record: {e:#}");
8735        }
8736    }
8737
8738    /// Run `verify.gate` once against the winner's current tree, logging one
8739    /// event per command. Empty when nothing is configured.
8740    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8741        let wait = self.repository_wait();
8742        run_landing_gate(&mut self.state, winner, &wait).await
8743    }
8744
8745    /// One bounded fix round for a failing gate.
8746    ///
8747    /// The fixer is told the failure came from the gate itself, not from a
8748    /// reviewer, and is shown the failed commands, their exit codes and a tail
8749    /// of their output - whatever `[verify].gate` holds, nothing here knows
8750    /// what those commands run. Only a normal non-zero exit that printed
8751    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8752    /// command or a full disk says nothing about the code, and a fixer sent
8753    /// after it can only appease the machine. The round is judged by what git
8754    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8755    /// again before the gate does, so a fix cannot trade a green gate for a
8756    /// red e2e unnoticed.
8757    async fn gate_fix_round(
8758        &mut self,
8759        winner: &Candidate,
8760        outcomes: &[CommandOutcome],
8761    ) -> Result<GateFix> {
8762        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8763            g.phase == crate::repair_budget::Phase::Fixing
8764                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8765        }) {
8766            self.state.gate_fixes.len().saturating_add(1)
8767        } else {
8768            self.state.config.graph.gate_fix_rounds
8769        };
8770        let spent = self.state.gate_fixes.len();
8771        if spent >= cap {
8772            if cap > 0 {
8773                self.state.event(
8774                    "gate",
8775                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8776                );
8777            }
8778            return Ok(GateFix::Stop);
8779        }
8780        if !gate_fixable(outcomes) {
8781            self.state.event(
8782                "gate",
8783                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8784                 command or similar); not spending a fix round on it",
8785            );
8786            return Ok(GateFix::Stop);
8787        }
8788        let min_free = self.state.config.disk.min_free_bytes;
8789        if min_free > 0 {
8790            match crate::disk::free_bytes(&winner.worktree) {
8791                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8792                Ok(free) => {
8793                    self.state.event(
8794                        "gate",
8795                        format!(
8796                            "only {free} bytes free ({min_free} required by `[disk] \
8797                             min_free_bytes`); not spending a fix round on a failure the disk \
8798                             may explain"
8799                        ),
8800                    );
8801                    return Ok(GateFix::Stop);
8802                }
8803                Err(e) => {
8804                    self.state.event(
8805                        "gate",
8806                        format!("free disk space could not be measured ({e:#}); no fix round"),
8807                    );
8808                    return Ok(GateFix::Stop);
8809                }
8810            }
8811        }
8812
8813        let attempt = spent + 1;
8814        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8815        let base = self.landing_base();
8816        let fix_prompt = prompt::gate_fix_in(
8817            &self.state.instruction,
8818            &failed,
8819            attempt,
8820            cap,
8821            &self.state.config.graph.language,
8822            &self.state.config.graph.github_language,
8823        );
8824        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8825        let sessions = self.state.config.graph.sessions;
8826        let artifacts = self.merge_repair_artifacts();
8827        self.state.event(
8828            "gate",
8829            format!("gate failed; gate-fix round {attempt} of {cap}"),
8830        );
8831        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8832        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8833        // Persist before invoking the fixer: it may commit and then be
8834        // interrupted before its result (or the following e2e) is saved.
8835        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8836            head: before.clone(),
8837            passed: false,
8838            outcomes: Vec::new(),
8839        });
8840        self.state.save()?;
8841        let (_, seat, out) = self
8842            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8843                prompt: fix_prompt.clone(),
8844                spec,
8845                seat,
8846                cwd: winner.worktree.clone(),
8847                timeout,
8848                allow_write: true,
8849                sessions,
8850                artifacts: artifacts.clone(),
8851                stem: format!("gate-fix-{attempt}"),
8852                handover: None,
8853            })
8854            .await;
8855        // The fixer was never asked: no round is spent (nothing is recorded)
8856        // and a later reentry asks the same agent again.
8857        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8858            return Ok(GateFix::Defer);
8859        }
8860        let mut record = GateFixRecord {
8861            agent: seat.agent.clone(),
8862            failed,
8863            notes: String::new(),
8864            committed: false,
8865            error: None,
8866        };
8867        match out {
8868            AgentOutcome::Ok(o) => {
8869                // A missing report is not a failed fix: the round is judged
8870                // by the tree below, and the report only carries prose.
8871                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
8872                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8873                }
8874            }
8875            AgentOutcome::Dropped(_) => {
8876                record.error = Some("the CLI dropped the stream".to_owned());
8877            }
8878            AgentOutcome::Quota(o) => {
8879                self.state.quota.push(QuotaLoss::from_report(
8880                    seat.key.clone(),
8881                    "gate-fix",
8882                    o.quota.as_ref(),
8883                ));
8884                record.error = Some("rate limited (quota); fixer could not run".to_owned());
8885            }
8886            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
8887        }
8888        self.state.seats.insert(seat.key.clone(), seat);
8889        let coordination = self.coordinate(&winner.worktree).await?;
8890        if let Ok(r) = git::rescue_commit(
8891            &winner.worktree,
8892            &format!("magi: gate fix {attempt} (uncommitted work)"),
8893        )
8894        .await
8895        {
8896            self.state.note_withheld("gate-fix", &r.withheld);
8897        }
8898        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8899        record.committed = after != before;
8900        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
8901        let note = record.error.clone();
8902        self.state.gate_fixes.push(record);
8903        self.state.save()?;
8904        if !changed {
8905            self.state.event(
8906                "gate",
8907                match note {
8908                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
8909                    None => format!("gate-fix round {attempt}: the tree did not change"),
8910                },
8911            );
8912            return Ok(GateFix::Stop);
8913        }
8914        self.state.event(
8915            "gate",
8916            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
8917        );
8918
8919        drop(coordination);
8920        let wait = self.repository_wait();
8921        check_gate_repair_e2e(&mut self.state, winner, &wait).await
8922    }
8923
8924    // ---------------------------------------------------------------- merge
8925
8926    /// One read-only rewrite by the summary's author; a text the gate still
8927    /// withholds goes to the owner (see `github_text`) and the fixed fallback
8928    /// applies on their word or on silence. `None` means the run is parked on
8929    /// that question and nothing may be pushed or opened yet.
8930    async fn guarded_pr_message(
8931        &mut self,
8932        winner: &Candidate,
8933        facts: Option<&BranchFacts>,
8934        posting: bool,
8935    ) -> Result<Option<PrMessage>> {
8936        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
8937        let head = match final_head.as_deref() {
8938            Some(h) => crate::pr_outcome::FinalHead::At(h),
8939            None => crate::pr_outcome::FinalHead::Unknown,
8940        };
8941        // Only a pull request that is about to be posted pays for a summary.
8942        let summarized = if posting {
8943            Some(self.summarize_change(winner, final_head.as_deref()).await)
8944        } else {
8945            None
8946        };
8947        // A busy shared resource is not a permanent cause: publishing an
8948        // "unavailable" description would stick (a later head move never
8949        // edits the body). Stop before anything is pushed or opened; the
8950        // run is `Blocked` and a resume asks the summary again.
8951        if self.state.resource_block.is_some() {
8952            self.state.event(
8953                "pr-summary",
8954                "a shared resource was busy; nothing was published, resume to summarize again",
8955            );
8956            return Ok(None);
8957        }
8958        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
8959            anyhow::bail!(
8960                "the final commit moved during public description generation; retry before publishing"
8961            );
8962        }
8963        let note = match (&summarized, &self.state.change_summary) {
8964            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
8965            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
8966            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
8967            (None, _) => ChangeNote::NotAsked,
8968        };
8969        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
8970        if !posting {
8971            let identity = crate::scrub::Identity::current();
8972            return Ok(Some(PrMessage {
8973                title: crate::scrub::scrub(&pr.title, &identity),
8974                body: crate::scrub::scrub(&pr.body, &identity),
8975            }));
8976        }
8977        // This very text was already rejected and asked about: no second
8978        // judge call, rewrite or question, just carry the record on.
8979        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
8980        if let Some(known) = self
8981            .state
8982            .github_text
8983            .clone()
8984            .filter(|g| g.fingerprint == raw_fp)
8985        {
8986            return self.settle_withheld(winner, &pr, known).await;
8987        }
8988        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
8989        let mut violations =
8990            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
8991        let identity = crate::scrub::Identity::current();
8992        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
8993            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
8994            && !violations.contains(&crate::github_text::Violation::SensitiveData)
8995        {
8996            violations.push(crate::github_text::Violation::SensitiveData);
8997        }
8998        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
8999        // only a language violation starts one; sensitive data alone goes
9000        // straight to the owner, with the redacted text as the fallback.
9001        let has_language = violations
9002            .iter()
9003            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9004        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9005            self.state.event(
9006                "github-text",
9007                if has_language {
9008                    format!("description rejected: {violations:?}; requesting one rewrite")
9009                } else {
9010                    format!("description rejected: {violations:?}; asking the owner")
9011                },
9012            );
9013            let mut rewritten = false;
9014            let mut rejected_rewrite = None;
9015            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9016            {
9017                let output = text;
9018                if let Some(title) = summary_title(&output) {
9019                    // Judge the redacted candidate that will actually be posted.
9020                    // Sensitive data alone must not discard a useful rewrite.
9021                    let raw_body = summary_without_title(&output);
9022                    let clean_title = crate::scrub::scrub(&title, &identity);
9023                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9024                    let redacted = clean_title != title || body != raw_body;
9025                    let title = clean_title;
9026                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9027                    if !complete {
9028                        self.state.event(
9029                            "github-text",
9030                            "description rewrite omitted required findings",
9031                        );
9032                    }
9033                    if !body.trim().is_empty() {
9034                        body.push_str("\n\n");
9035                        body.push_str(&public_pr_evidence(&self.state, head));
9036                    }
9037                    let marker = format!("magi:run/{}", self.state.id);
9038                    if !body.trim().is_empty() && !body.contains(&marker) {
9039                        body.push_str(&format!("\n\n{marker}"));
9040                    }
9041                    let rewrite = PrMessage {
9042                        title: title.clone(),
9043                        body: body.clone(),
9044                    };
9045                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9046                    let mut failed = crate::github_text::check_for(
9047                        &self.state.config.graph,
9048                        &title,
9049                        &body,
9050                        redecision,
9051                    );
9052                    if (!crate::github_text::shareable(&title)
9053                        || !crate::github_text::shareable(&body))
9054                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9055                    {
9056                        failed.push(crate::github_text::Violation::SensitiveData);
9057                    }
9058                    if complete
9059                        && !title.trim().is_empty()
9060                        && !body.trim().is_empty()
9061                        && !failed.is_empty()
9062                    {
9063                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9064                            title: title.clone(),
9065                            body: body.clone(),
9066                            failed: failed
9067                                .iter()
9068                                .map(|v| crate::github_text::category(*v).to_owned())
9069                                .collect(),
9070                        });
9071                    }
9072                    if complete
9073                        && !title.trim().is_empty()
9074                        && !raw_body.trim().is_empty()
9075                        && failed.is_empty()
9076                    {
9077                        decision = redecision;
9078                        pr = PrMessage { title, body };
9079                        rewritten = true;
9080                        self.state
9081                            .event("github-text", "description rewrite passed");
9082                        if redacted {
9083                            self.state.event(
9084                                "github-text",
9085                                "sensitive data removed from description rewrite",
9086                            );
9087                        }
9088                    }
9089                }
9090            }
9091            if !rewritten {
9092                self.state.event(
9093                    "github-text",
9094                    "description rewrite unavailable or rejected; asking the owner",
9095                );
9096                if let Some(w) =
9097                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9098                {
9099                    // A different text than the one asked about before: that
9100                    // question no longer describes anything.
9101                    self.retire_github_text_question("the withheld text changed");
9102                    let record = crate::run::GithubTextAsk {
9103                        rewrite: rejected_rewrite,
9104                        fingerprint: raw_fp,
9105                        title: w.title,
9106                        body: w.body,
9107                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9108                        question: None,
9109                        asks: 0,
9110                        resolved: false,
9111                        chosen_title: None,
9112                        choice: None,
9113                        publication: None,
9114                    };
9115                    return self.settle_withheld(winner, &pr, record).await;
9116                }
9117            }
9118        }
9119        let (title, body) =
9120            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9121        Ok(Some(PrMessage { title, body }))
9122    }
9123
9124    /// Describe the whole change from its final diff in either run mode.
9125    ///
9126    /// The summary is tied to the final commit and to the merge base of the
9127    /// resolved remote base; a record for any other pair is dropped and the
9128    /// agent asked again, so a description never outlives the diff it was
9129    /// written from. The seat is read-only and the prompt tells it to read the
9130    /// diff and the code around it. `[roles] synthesizer` selects the agents
9131    /// (unset: the default pick), each asked at most once, advancing on an
9132    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9133    /// carries the reason it is unavailable; nothing is invented then.
9134    async fn summarize_change(
9135        &mut self,
9136        winner: &Candidate,
9137        head: Option<&str>,
9138    ) -> std::result::Result<(), String> {
9139        let Some(head) = head else {
9140            return Err("the final commit could not be read".to_owned());
9141        };
9142        let remote = self.state.config.merge.remote.clone();
9143        let tracking = format!("{remote}/{}", self.state.base_branch);
9144        if !git::rev_exists(&winner.worktree, &tracking).await {
9145            return Err(format!("the remote base `{tracking}` could not be read"));
9146        }
9147        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9148            Ok(b) if !b.is_empty() => b,
9149            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9150        };
9151        let evidence = crate::pr_outcome::summary_evidence(
9152            &self.state,
9153            crate::pr_outcome::FinalHead::At(head),
9154        );
9155        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9156        if self
9157            .state
9158            .change_summary
9159            .as_ref()
9160            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9161        {
9162            return Ok(());
9163        }
9164        if self.state.change_summary.take().is_some() {
9165            self.state.event(
9166                "pr-summary",
9167                "the final diff or evidence changed; the earlier change summary was discarded",
9168            );
9169        }
9170        // Save the source snapshot even if no generation agent is available.
9171        if let Err(e) = write_artifact(
9172            &self.state,
9173            &format!("public-description-{fingerprint}.md"),
9174            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9175        ) {
9176            tracing::warn!("could not save public description evidence: {e:#}");
9177        }
9178        let chain = match agent::pick_chain(
9179            &self.state.config.agents,
9180            self.state.config.roles.synthesizer.as_ref(),
9181            &agent::installed,
9182            "synthesizer",
9183        ) {
9184            Ok(chain) => chain,
9185            Err(e) => {
9186                tracing::warn!("no agent for the change summary: {e:#}");
9187                self.state.event("pr-summary", "no summary agent available");
9188                return Err("no agent was available to summarize it".to_owned());
9189            }
9190        };
9191        let subjects = git::subjects(&winner.worktree, &base, head)
9192            .await
9193            .unwrap_or_default();
9194        let stat = git::diff_stat(&winner.worktree, &base, head)
9195            .await
9196            .unwrap_or_default();
9197        let stat: String = stat.chars().take(6_000).collect();
9198        let mut prompt = crate::prompt::change_summary_in(
9199            &base,
9200            head,
9201            &subjects,
9202            stat.trim(),
9203            &self.state.config.graph.github_language,
9204        );
9205        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."));
9206        let sessions = self.state.config.graph.sessions;
9207        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9208        let prompts = self.state.config.prompts.clone();
9209        let cache = self.state.config.cache_dir();
9210        let run = self.state.id.clone();
9211        for (i, spec) in chain.into_iter().enumerate() {
9212            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9213            let github_spec = match agent::for_github_text(
9214                &spec,
9215                &self.state.config.graph.github_language,
9216                &winner.worktree,
9217            ) {
9218                Ok(spec) => spec,
9219                Err(e) => {
9220                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9221                    continue;
9222                }
9223            };
9224            let job = SeatJob {
9225                spec: github_spec,
9226                seat,
9227                cwd: winner.worktree.clone(),
9228                prompt: prompt.clone(),
9229                timeout,
9230                allow_write: false,
9231                sessions,
9232                artifacts: agent::artifacts_dir(&self.state.dir()),
9233                stem: if i == 0 {
9234                    "change-summary".to_owned()
9235                } else {
9236                    format!("change-summary-{}", spec.id)
9237                },
9238                handover: None,
9239            };
9240            let ctx = WaveCtx {
9241                run: &run,
9242                node: "pr-summary",
9243                prompts: &prompts,
9244                cache: cache.as_deref(),
9245                round: None,
9246                carry_seats: false,
9247                pauses: Some((&self.pause, &self.interrupt)),
9248            };
9249            let (seat, outcome) =
9250                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9251            self.state.seats.insert(seat.key.clone(), seat);
9252            let text = match outcome {
9253                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9254                AgentOutcome::ResourceBlocked(why) => {
9255                    // No agent was asked: the run stops resumably before
9256                    // anything is published (see `guarded_pr_message`).
9257                    if self.state.resource_block.is_none() {
9258                        self.state.resource_block = Some(crate::run::ResourceBlock {
9259                            cause: crate::run::ResourceBlockCause::Other,
9260                            node: "pr-summary".to_owned(),
9261                            kind: "shared resource".to_owned(),
9262                            detail: why,
9263                            at: Timestamp::now(),
9264                        });
9265                    }
9266                    return Err("a shared resource was busy".to_owned());
9267                }
9268                _ => continue,
9269            };
9270            let blind = &self.state.config.blind;
9271            let Some(title) = summary_title(&text) else {
9272                continue;
9273            };
9274            let body: String = summary_without_title(&text)
9275                .lines()
9276                .filter(|l| !l.contains("magi:run/"))
9277                .collect::<Vec<_>>()
9278                .join("\n");
9279            let body = blind::sanitize_prose(body.trim(), blind);
9280            let title = blind::sanitize_prose(&title, blind);
9281            if body.trim().is_empty() || title.trim().is_empty() {
9282                continue;
9283            }
9284            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9285                continue;
9286            }
9287            // The branch must still be the one the agent was shown.
9288            if git::rev_parse(&winner.worktree, "HEAD")
9289                .await
9290                .ok()
9291                .as_deref()
9292                != Some(head)
9293            {
9294                return Err("the branch moved while the summary was written".to_owned());
9295            }
9296            if git::merge_base(&winner.worktree, &tracking, head)
9297                .await
9298                .ok()
9299                .as_deref()
9300                != Some(base.as_str())
9301                || crate::pr_outcome::summary_evidence(
9302                    &self.state,
9303                    crate::pr_outcome::FinalHead::At(head),
9304                ) != evidence
9305            {
9306                return Err("the summary evidence changed while it was written".to_owned());
9307            }
9308            self.state.change_summary = Some(crate::run::ChangeSummary {
9309                head: head.to_owned(),
9310                base,
9311                evidence: fingerprint,
9312                title,
9313                body,
9314            });
9315            self.state.event(
9316                "pr-summary",
9317                format!("change summary written by {} for the final diff", spec.id),
9318            );
9319            if let Err(e) = self.state.save() {
9320                tracing::warn!("could not save the change summary: {e:#}");
9321            }
9322            return Ok(());
9323        }
9324        self.state
9325            .event("pr-summary", "no agent produced a change summary");
9326        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9327    }
9328
9329    /// One read-only rewrite request for a withheld description. The
9330    /// implementer's own conversation is tried first when it exists and can be
9331    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9332    /// writes it in a separate conversation, skipping the implementer's agent.
9333    /// The prompt carries the whole text, so no agent needs any memory. Each
9334    /// agent is asked at most once and the chain advances on an error, quota,
9335    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9336    /// that has run out of quota must not end the rewrite. Nothing is recorded
9337    /// as a handover.
9338    async fn rewrite_pr_text(
9339        &mut self,
9340        winner: &Candidate,
9341        pr: &PrMessage,
9342        violations: &[crate::github_text::Violation],
9343    ) -> Option<String> {
9344        let prompt = format!(
9345            "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{}",
9346            pr.title, pr.body
9347        );
9348        let sessions = self.state.config.graph.sessions;
9349        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9350        // (spec, the resumed implementer's seat). A fallback seat is created
9351        // only when its turn comes, so an unused fallback leaves no record.
9352        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9353        let key = format!("impl-{}", winner.label);
9354        if let Some(spec) = self
9355            .state
9356            .config
9357            .agents
9358            .iter()
9359            .find(|a| a.id == winner.agent)
9360            .cloned()
9361            && let Some(existing) = self.state.seats.get(&key)
9362            && existing.agent == spec.id
9363            && agent::has_session(spec.kind, existing, sessions)
9364        {
9365            attempts.push((spec, Some(existing.clone())));
9366        }
9367        match agent::pick_chain(
9368            &self.state.config.agents,
9369            self.state.config.roles.language_judge.as_ref(),
9370            &agent::installed,
9371            "language_judge",
9372        ) {
9373            Ok(chain) => {
9374                for spec in chain {
9375                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9376                        continue;
9377                    }
9378                    attempts.push((spec, None));
9379                }
9380            }
9381            Err(e) if attempts.is_empty() => {
9382                tracing::warn!("no agent for the description rewrite: {e:#}");
9383                self.state
9384                    .event("github-text", "no rewrite agent available");
9385                return None;
9386            }
9387            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9388        }
9389        let prompts = self.state.config.prompts.clone();
9390        let cache = self.state.config.cache_dir();
9391        let run = self.state.id.clone();
9392        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9393            let resumed = resumed_seat.is_some();
9394            let seat = resumed_seat.unwrap_or_else(|| {
9395                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9396            });
9397            let github_spec = match agent::for_github_text(
9398                &spec,
9399                &self.state.config.graph.github_language,
9400                &winner.worktree,
9401            ) {
9402                Ok(spec) => spec,
9403                Err(e) => {
9404                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9405                    continue;
9406                }
9407            };
9408            let job = SeatJob {
9409                spec: github_spec,
9410                seat,
9411                cwd: winner.worktree.clone(),
9412                prompt: prompt.clone(),
9413                timeout: retry_budget(timeout_full, resumed),
9414                allow_write: false,
9415                sessions,
9416                artifacts: agent::artifacts_dir(&self.state.dir()),
9417                stem: if i == 0 {
9418                    "github-text-rewrite".to_owned()
9419                } else {
9420                    format!("github-text-rewrite-{}", spec.id)
9421                },
9422                handover: None,
9423            };
9424            let ctx = WaveCtx {
9425                run: &run,
9426                node: "github-text",
9427                prompts: &prompts,
9428                cache: cache.as_deref(),
9429                round: None,
9430                carry_seats: false,
9431                pauses: Some((&self.pause, &self.interrupt)),
9432            };
9433            let (seat, outcome) =
9434                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9435            self.state.seats.insert(seat.key.clone(), seat);
9436            match outcome {
9437                AgentOutcome::Ok(o)
9438                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9439                {
9440                    return Some(o.text);
9441                }
9442                AgentOutcome::ResourceBlocked(_) => return None,
9443                _ => {}
9444            }
9445        }
9446        None
9447    }
9448
9449    /// Abandon the standing posting-gate question, if any.
9450    fn retire_github_text_question(&mut self, why: &str) {
9451        let Some(id) = self
9452            .state
9453            .github_text
9454            .as_ref()
9455            .and_then(|g| g.question.clone())
9456        else {
9457            return;
9458        };
9459        let _ = ask::Questions::open().update(&id, |q| {
9460            q.abandon(why);
9461            Ok(())
9462        });
9463    }
9464
9465    /// Carry a withheld text to its end: file the question, park while it is
9466    /// open, and on an answer, silence or timeout pick the text to post. The
9467    /// decision is saved before it is used, so it applies once.
9468    async fn settle_withheld(
9469        &mut self,
9470        winner: &Candidate,
9471        pr: &PrMessage,
9472        mut g: crate::run::GithubTextAsk,
9473    ) -> Result<Option<PrMessage>> {
9474        use crate::github_text as gt;
9475        let store = ask::Questions::open();
9476        let timeout = self.state.config.graph.answer_timeout;
9477        if !g.resolved {
9478            let mut standing = g
9479                .question
9480                .as_ref()
9481                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9482            if let Some(q) = standing.as_ref()
9483                && q.status.open()
9484                && !store.held_reply(&q.id)
9485                && gt::expired(q, timeout)
9486            {
9487                let why = format!("no answer within {}s of asking", timeout.max(1));
9488                standing = store
9489                    .update(&q.id, |q| {
9490                        q.abandon(&why);
9491                        Ok(())
9492                    })
9493                    .ok()
9494                    .map(|(q, ())| q);
9495            }
9496            let mut ask_again: Option<Option<Vec<String>>> = None;
9497            match standing {
9498                // Recorded but never written (a stop between the two saves),
9499                // or removed: ask again without spending the retry.
9500                None if g.asks <= 1 => {
9501                    g.asks = 0;
9502                    ask_again = Some(None);
9503                }
9504                None => {
9505                    g.resolved = true;
9506                    g.chosen_title = None;
9507                    g.choice = Some(GithubTextChoice::Fallback);
9508                }
9509                Some(q) if q.status.open() => {
9510                    self.park_on_github_text(&g)?;
9511                    return Ok(None);
9512                }
9513                Some(q) => match gt::read_reply(&q) {
9514                    gt::Reply::Fallback => {
9515                        g.resolved = true;
9516                        g.chosen_title = None;
9517                        g.choice = Some(GithubTextChoice::Fallback);
9518                    }
9519                    gt::Reply::Original => {
9520                        g.resolved = true;
9521                        g.chosen_title = None;
9522                        g.choice = Some(GithubTextChoice::Original);
9523                    }
9524                    gt::Reply::Rewrite => {
9525                        g.resolved = true;
9526                        g.chosen_title = None;
9527                        g.choice = Some(if g.rewrite.is_some() {
9528                            GithubTextChoice::Rewrite
9529                        } else {
9530                            GithubTextChoice::Fallback
9531                        });
9532                    }
9533                    gt::Reply::Title(text) => {
9534                        let first = text
9535                            .lines()
9536                            .map(str::trim)
9537                            .find(|l| !l.is_empty())
9538                            .unwrap_or("");
9539                        let decision = if first.is_empty() {
9540                            None
9541                        } else {
9542                            let candidate = PrMessage {
9543                                title: first.to_owned(),
9544                                body: String::new(),
9545                            };
9546                            self.judge_pr_language(&winner.worktree, &candidate).await
9547                        };
9548                        match gt::vet_title(
9549                            &text,
9550                            decision,
9551                            self.state.config.graph.github_english(),
9552                        ) {
9553                            Ok(title) => {
9554                                g.resolved = true;
9555                                g.chosen_title = Some(title);
9556                                g.choice = Some(GithubTextChoice::MyTitle);
9557                            }
9558                            Err(cats) if g.asks < 2 => {
9559                                ask_again = Some(Some(
9560                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9561                                ))
9562                            }
9563                            Err(_) => {
9564                                g.resolved = true;
9565                                g.chosen_title = None;
9566                                g.choice = Some(GithubTextChoice::Fallback);
9567                            }
9568                        }
9569                    }
9570                },
9571            }
9572            if let Some(rejected) = ask_again {
9573                // A retry (after a rejected replacement title) is still about
9574                // the original text: the same ORIGINAL / FALLBACK comparison.
9575                let w = gt::Withheld {
9576                    title: g.title,
9577                    body: g.body,
9578                    categories: g.categories.clone(),
9579                };
9580                // Named by the original text's fingerprint alone, so a resume
9581                // rewrites the same file and the detail stays identical.
9582                let artifact = match crate::run::write_artifact(
9583                    &self.state,
9584                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9585                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9586                ) {
9587                    Ok(p) => Some(p),
9588                    Err(e) => {
9589                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9590                        None
9591                    }
9592                };
9593                let (detail, comparison) = gt::question_content(
9594                    &w,
9595                    &pr.title,
9596                    &pr.body,
9597                    &self.state.id,
9598                    rejected.as_deref(),
9599                    artifact.as_deref(),
9600                    g.rewrite.as_ref(),
9601                );
9602                let mut q = ask::Question::new(
9603                    self.state.id.clone(),
9604                    gt::ASK_NODE.to_owned(),
9605                    gt::ASK_SEAT.to_owned(),
9606                    gt::question_summary(&self.state.config.graph.language, &w),
9607                    detail,
9608                    gt::question_choices(&w, g.rewrite.as_ref()),
9609                );
9610                q.posting_comparison = Some(comparison);
9611                q.answer_timeout = timeout;
9612                // Recorded before it is written: a stop in between leaves a
9613                // record naming a question the resume then files again.
9614                g.question = Some(q.id.clone());
9615                g.asks += 1;
9616                self.state.github_text = Some(g.clone());
9617                self.state.event(
9618                    "github-text",
9619                    format!("asking the owner about the withheld text ({})", q.short()),
9620                );
9621                self.state.save()?;
9622                store
9623                    .put_executable(&mut q)
9624                    .context("file the posting-gate question")?;
9625                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9626                    tracing::warn!(
9627                        "could not notify about posting-gate question {}: {e:#}",
9628                        q.short()
9629                    );
9630                }
9631                self.park_on_github_text(&g)?;
9632                return Ok(None);
9633            }
9634        }
9635        let resolved = g.chosen_title.clone();
9636        let original = g.choice == Some(GithubTextChoice::Original);
9637        // Field names only: the event log never records the text.
9638        self.state.event(
9639            "github-text",
9640            if original {
9641                format!(
9642                    "posting the original text for: {}",
9643                    match (g.title, g.body) {
9644                        (true, true) => "title, description",
9645                        (true, false) => "title",
9646                        _ => "description",
9647                    }
9648                )
9649            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9650                "posting the saved rewrite title and description".to_owned()
9651            } else if resolved.is_some() {
9652                "posting the owner's replacement title".to_owned()
9653            } else {
9654                "posting the neutral text for the withheld fields".to_owned()
9655            },
9656        );
9657        self.state.github_text = Some(g.clone());
9658        self.state.save()?;
9659        if g.choice == Some(GithubTextChoice::Rewrite)
9660            && let Some(r) = g.rewrite.as_ref()
9661        {
9662            return Ok(Some(PrMessage {
9663                title: r.title.clone(),
9664                body: r.body.clone(),
9665            }));
9666        }
9667        let w = gt::Withheld {
9668            title: g.title,
9669            body: g.body,
9670            categories: g.categories.clone(),
9671        };
9672        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9673        if let Some(t) = resolved {
9674            title = t;
9675        }
9676        // Every withheld field is now neutral or vetted English.
9677        let english = gt::LanguageDecision {
9678            title_english: true,
9679            body_english: true,
9680            body_complete: true,
9681        };
9682        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9683        if original {
9684            // The owner's explicit choice overrides the gate for the fields it
9685            // was made for; the others keep what the gate produced.
9686            if g.title {
9687                title = pr.title.clone();
9688            }
9689            if g.body {
9690                body = pr.body.clone();
9691            }
9692        }
9693        Ok(Some(PrMessage { title, body }))
9694    }
9695
9696    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9697        self.state.github_text = Some(g.clone());
9698        self.state.end_pass_parked(ParkCause::Question);
9699        self.state.parked = true;
9700        self.state.event(
9701            "github-text",
9702            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9703        );
9704        self.state.save()
9705    }
9706
9707    /// Ask `[roles] language_judge` about this text and record which source
9708    /// decided; the text itself is never recorded.
9709    async fn judge_pr_language(
9710        &mut self,
9711        cwd: &Path,
9712        pr: &PrMessage,
9713    ) -> Option<crate::github_text::LanguageDecision> {
9714        self.state.config.roles.language_judge.as_ref()?;
9715        if !self.state.config.graph.language_gate() {
9716            return None;
9717        }
9718        let decision =
9719            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9720        self.state.event(
9721            "github-text",
9722            if decision.is_some() {
9723                "language decided by the language judge"
9724            } else {
9725                "language judge unavailable; using built-in heuristics"
9726            },
9727        );
9728        decision
9729    }
9730
9731    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9732        Box::pin(self.merge_inner())
9733    }
9734
9735    async fn merge_inner(&mut self) -> Result<()> {
9736        if self.resource_halt()? || self.hold_base_sync().await? {
9737            return Ok(());
9738        }
9739        // Same reasoning as `gate`: ask the review and gate records directly
9740        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9741        // skip can rewrite on reentry to something that no longer says
9742        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9743        // so a hand-off (open findings, green verification) reaches merge
9744        // exactly like a genuinely clean round does.
9745        //
9746        // A run resumed mid-`land` never reaches here at all: `execute`
9747        // recognises `RunStatus::Landing` before it even calls `prep`, and
9748        // routes straight to `run_land` instead. That has to happen a level
9749        // up from this function, not with a check in here, because
9750        // `review_loop`'s own status recomputation (see its doc) runs
9751        // *before* `merge` on every reentry and would otherwise overwrite
9752        // the `Landing` marker with `Gating` before this node ever saw it.
9753        if self
9754            .state
9755            .base_sync
9756            .as_ref()
9757            .is_some_and(|s| s.conflict.is_some())
9758            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9759                != Some(RunStatus::Gating)
9760            // `gate_ran == false` is not "passed" - `gate` leaves it false
9761            // both before it has ever run and when its last attempt was
9762            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9763            // permission to merge on nothing but the review record. Only a
9764            // gate that actually ran may proceed; an intentional local
9765            // review can also finish with verification explicitly not configured.
9766            // `RunState::gate_status` computes that distinction.
9767            || !self.state.gate_allows_progress()
9768        {
9769            return Ok(());
9770        }
9771        // This node's own record, not `status`: `status == Ready` is not
9772        // unique to the harmless `MergeMode::None` path this line was
9773        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9774        // run's PR was closed without merging — and on that run `mode` is
9775        // still `Pr`, so a reentry that fell through here would push and
9776        // open a second pull request. `self.state.merge` is set exactly once
9777        // this node (or `land`) has already produced a verdict, under every
9778        // mode, which is what "already done" actually means here.
9779        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9780            return Ok(());
9781        }
9782        let Some(winner) = self.state.winner().cloned() else {
9783            return Ok(());
9784        };
9785        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9786        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9787            self.state.status = RunStatus::Blocked;
9788            self.state.event(
9789                "gate",
9790                "winner changed after gate; fresh verification required",
9791            );
9792            self.state.save()?;
9793            return Ok(());
9794        }
9795        let wait = self.repository_wait();
9796        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9797            return Ok(());
9798        }
9799        let repo = self.state.repo.clone();
9800        let base = self.state.base_branch.clone();
9801        let mode = self.state.config.merge.mode;
9802        let style = self.state.config.merge.style;
9803        let facts = if is_review_run(&self.state) {
9804            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9805            let start = review_base(
9806                &repo,
9807                &self.state.config.merge.remote,
9808                &base,
9809                &self.state.base_commit,
9810                &winner.branch,
9811            )
9812            .await;
9813            branch_facts(&repo, &start, &winner.branch).await
9814        } else {
9815            None
9816        };
9817        // `None` when the base could not be freshly read: then an adopted
9818        // pull request's title is left alone.
9819        let leaked = if is_review_run(&self.state) {
9820            leaked_subjects(&self.state, &winner.branch).await
9821        } else {
9822            Some(Vec::new())
9823        };
9824        // `None`: parked on the owner's word about a withheld title or body.
9825        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9826        // the resume arrives here again.
9827        let Some(pr) = self
9828            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9829            .await?
9830        else {
9831            return Ok(());
9832        };
9833        let message = pr.commit_message();
9834
9835        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9836        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9837            return Ok(());
9838        }
9839        let outcome = match mode {
9840            MergeMode::None => MergeOutcome {
9841                mode,
9842                ok: true,
9843                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9844                empty: false,
9845            },
9846            MergeMode::Pr | MergeMode::Local
9847                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9848            {
9849                MergeOutcome {
9850                    mode,
9851                    ok: false,
9852                    detail: empty_candidate_detail(&self.state, &base),
9853                    empty: true,
9854                }
9855            }
9856            MergeMode::Local => {
9857                let on = git::current_branch(&repo).await?;
9858                if on.as_deref() != Some(base.as_str()) {
9859                    MergeOutcome {
9860                        mode,
9861                        ok: false,
9862                        detail: format!(
9863                            "{} has {} checked out, not the base branch {base}",
9864                            repo.display(),
9865                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
9866                        ),
9867                        empty: false,
9868                    }
9869                } else if !git::is_clean(&repo).await? {
9870                    MergeOutcome {
9871                        mode,
9872                        ok: false,
9873                        detail: format!("{} is dirty; refusing to merge", repo.display()),
9874                        empty: false,
9875                    }
9876                } else {
9877                    let out = match style {
9878                        MergeStyle::Merge => {
9879                            git::merge_no_ff(&repo, &winner.branch, &message).await?
9880                        }
9881                        MergeStyle::Squash => {
9882                            git::merge_squash(&repo, &winner.branch, &message).await?
9883                        }
9884                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
9885                    };
9886                    MergeOutcome {
9887                        mode,
9888                        ok: out.ok(),
9889                        detail: if out.ok() { out.stdout } else { out.stderr },
9890                        empty: false,
9891                    }
9892                }
9893            }
9894            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
9895                self.state.pr_publication_pending = true;
9896                self.state.save()?;
9897                let out =
9898                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
9899                self.state.pr_publication_pending = out.is_err();
9900                MergeOutcome {
9901                    mode,
9902                    ok: out.is_ok(),
9903                    detail: match out {
9904                        Ok(url) => url,
9905                        Err(e) => format!("{e:#}"),
9906                    },
9907                    empty: false,
9908                }
9909            }
9910            MergeMode::Pr => {
9911                let remote = self.state.config.merge.remote.clone();
9912                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
9913                let pushed = if self.state.foreign_checkout.is_some() {
9914                    let refspec = format!("{delivery_head}:refs/heads/{public}");
9915                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
9916                } else {
9917                    git::push(&winner.worktree, &remote, &winner.branch).await?
9918                };
9919                if !pushed.ok() {
9920                    MergeOutcome {
9921                        mode,
9922                        ok: false,
9923                        detail: pushed.stderr,
9924                        empty: false,
9925                    }
9926                } else {
9927                    if self.state.foreign_checkout.is_some() {
9928                        self.state.pr_pushed_head = Some(delivery_head.clone());
9929                    }
9930                    // A retry or resume of a run whose branch already has an
9931                    // open pull request adopts it rather than failing on a
9932                    // duplicate. Only this winner branch into this base:
9933                    // `branch_for` derives the name from the run id, so a
9934                    // different run's pull request never matches.
9935                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
9936                    let out = match pr_merge_plan(found) {
9937                        PrPlan::Create => {
9938                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
9939                                .await
9940                        }
9941                        PrPlan::Adopt { url, title } => {
9942                            self.state
9943                                .event("merge", format!("Pr: adopted open pull request {url}"));
9944                            if self.state.explicit_github_text_selection() {
9945                                // An explicit publication selection applies the prepared
9946                                // payload; acceptance alone is not publication proof.
9947                                land::set_pr_text_verbatim(
9948                                    &winner.worktree,
9949                                    &url,
9950                                    &pr.title,
9951                                    &pr.body,
9952                                )
9953                                .await
9954                                .map(|()| url)
9955                            } else {
9956                                if title != pr.title
9957                                    && (!is_review_run(&self.state)
9958                                        || leaked
9959                                            .as_deref()
9960                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
9961                                    && let Err(e) =
9962                                        if self.state.github_text.as_ref().is_some_and(|g| {
9963                                            g.resolved
9964                                                && g.title
9965                                                && g.choice == Some(GithubTextChoice::Original)
9966                                        }) {
9967                                            // The owner chose to post this title unmodified.
9968                                            land::set_pr_title_verbatim(
9969                                                &winner.worktree,
9970                                                &url,
9971                                                &pr.title,
9972                                            )
9973                                            .await
9974                                        } else {
9975                                            land::set_pr_title(
9976                                                &mut self.state,
9977                                                &winner.worktree,
9978                                                &url,
9979                                                &pr.title,
9980                                            )
9981                                            .await
9982                                        }
9983                                {
9984                                    tracing::warn!("could not refresh title of {url}: {e:#}");
9985                                    self.state
9986                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
9987                                }
9988                                Ok(url)
9989                            }
9990                        }
9991                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
9992                    };
9993                    match out {
9994                        Ok(url) => MergeOutcome {
9995                            mode,
9996                            ok: true,
9997                            detail: url,
9998                            empty: false,
9999                        },
10000                        Err(e) => MergeOutcome {
10001                            mode,
10002                            ok: false,
10003                            detail: e.to_string(),
10004                            empty: false,
10005                        },
10006                    }
10007                }
10008            }
10009        };
10010
10011        self.state.status = match (mode, outcome.ok) {
10012            (MergeMode::None, _) => RunStatus::Ready,
10013            (_, true) if outcome.empty => RunStatus::Ready,
10014            (MergeMode::Pr, true) => RunStatus::Ready,
10015            (_, true) => RunStatus::Merged,
10016            (_, false) => RunStatus::Blocked,
10017        };
10018        self.state.event(
10019            "merge",
10020            format!(
10021                "{:?}: {}",
10022                mode,
10023                outcome.detail.lines().next().unwrap_or("")
10024            ),
10025        );
10026        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10027            self.state.record_github_text_publication(&outcome.detail);
10028        }
10029        self.state.merge = Some(outcome);
10030        self.state.save()?;
10031
10032        // The PR is open and the run would historically stop here, leaving the
10033        // operator to watch checks, feed review comments back to a fixer, and
10034        // merge. That was done by hand six times in one session before this
10035        // existed. Opt-in, because merging is the one irreversible thing magi
10036        // can do to a repository.
10037        if self.state.config.graph.land
10038            && mode == MergeMode::Pr
10039            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10040        {
10041            self.run_land().await?;
10042        }
10043        // `run_land` may have left `status` at `Landing` - still waiting on
10044        // CI or the owner's approval, not actually settled - so this has to
10045        // read whatever `status` ended up as here, not the `Merged` this
10046        // function set a few lines up.
10047        self.settle_questions();
10048        Ok(())
10049    }
10050
10051    /// Enter `land`.
10052    ///
10053    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10054    /// a resumed run's re-entry. `land::land` itself is what serialises the
10055    /// two git-mutating moments inside the loop — the rebase push and
10056    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10057    /// to hold a lock across the whole call, and doing so would serialise
10058    /// this run's CI wait against a *different* run's land-approval resume
10059    /// in the same repository, which is exactly the "must not wait on
10060    /// another task" property the daemon's slot-freeing exists to give.
10061    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10062        Box::pin(self.run_land_inner())
10063    }
10064
10065    async fn run_land_inner(&mut self) -> Result<()> {
10066        crate::pr_head::ensure_owner(&self.state)?;
10067        let url = self
10068            .state
10069            .pr
10070            .as_ref()
10071            .map(|pr| pr.url.clone())
10072            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10073            .unwrap_or_default();
10074        let url = url.lines().next().unwrap_or("").trim().to_owned();
10075        if !url.starts_with("http") {
10076            return Ok(());
10077        }
10078        // A land failure is not a lost run: the work is on a branch and the
10079        // pull request is open, which is exactly where a human takes over.
10080        loop {
10081            match land::land(&mut self.state, &url).await {
10082                Ok(_)
10083                    if self
10084                        .state
10085                        .merge_repairs
10086                        .last()
10087                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10088                {
10089                    if self.repair_merge_review().await? {
10090                        continue;
10091                    }
10092                }
10093                Ok(_) if self.state.resource_block.is_some() => {
10094                    return self.stop_for_resource();
10095                }
10096                Ok(pr) if self.state.parked => {
10097                    // `land` already saved the parked marker; nothing here
10098                    // overrides `status` back to a terminal value while an
10099                    // approval is still outstanding.
10100                    let _ = pr;
10101                }
10102                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10103                    self.state.status = RunStatus::Superseded;
10104                    self.state.save()?;
10105                }
10106                Ok(pr) => {
10107                    self.state.status = match pr.state {
10108                        land::PrLifecycle::Merged => RunStatus::Merged,
10109                        _ => RunStatus::Blocked,
10110                    };
10111                    // Downstream of a confirmed merge only - see
10112                    // `bump::should_release_bump`'s own doc for why this one
10113                    // check covers all three of `land`'s success paths.
10114                    // Best-effort: the run already landed, so a failure here
10115                    // (the decision call, `gh`, `cargo`) is recorded and never
10116                    // turns a landed run into a failed one.
10117                    if bump::should_release_bump(self.state.status)
10118                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10119                    {
10120                        // The event is the run's own record. Not-eligible cases
10121                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10122                        // `Err` is a bump that was tried and failed:
10123                        // `after_merge` itself raises the operator notice for
10124                        // that, whether or not a release PR exists yet.
10125                        self.state
10126                            .event("bump", format!("release bump skipped: {e:#}"));
10127                    }
10128                    // Independent of the bump, and best-effort in the same way:
10129                    // findings the merge left open become follow-up tasks.
10130                    if self.state.status == RunStatus::Merged {
10131                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10132                    }
10133                    self.state.save()?;
10134                }
10135                Err(e) => {
10136                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10137                        return Err(e);
10138                    }
10139                    self.state.status = RunStatus::Blocked;
10140                    self.state.event("land", format!("gave up: {e}"));
10141                    self.state.save()?;
10142                }
10143            }
10144            break;
10145        }
10146        Ok(())
10147    }
10148
10149    /// One repair cycle stays under the existing driver/task claim. An
10150    /// interrupted fixer is rolled back and held rather than run twice.
10151    async fn repair_merge_review(&mut self) -> Result<bool> {
10152        use crate::run::MergeRepairPhase as Phase;
10153        crate::pr_head::ensure_owner(&self.state)?;
10154        let i = self.state.merge_repairs.len() - 1;
10155        let request = self.state.merge_repairs[i].clone();
10156        if request.phase == Phase::Fixing {
10157            let restored = match self.state.winner().cloned() {
10158                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10159                None => Err(anyhow::anyhow!("repair has no winning branch")),
10160            };
10161            let why = match restored {
10162                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10163                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10164                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10165            };
10166            self.hold_merge_repair(i, why)?;
10167            return Ok(false);
10168        }
10169        // A completed repair gate is a publication checkpoint. On reentry,
10170        // reject external changes before the ordinary gate path can replace
10171        // that evidence by verifying a new head. Requested repairs still
10172        // start their own review generation below.
10173        if request.phase == Phase::Reviewing && self.state.gate_ran {
10174            let winner = self
10175                .state
10176                .winner()
10177                .context("repair has no winning branch")?;
10178            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10179            if self.state.gate_head.as_deref() != Some(head.as_str())
10180                || !git::is_clean(&winner.worktree).await?
10181            {
10182                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())?;
10183                return Ok(false);
10184            }
10185        }
10186        let failure = if i >= self.state.config.graph.land_rounds
10187            || self.state.config.graph.review_rounds == 0
10188        {
10189            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10190        } else {
10191            None
10192        };
10193        if let Some(why) = failure {
10194            self.hold_merge_repair(i, why)?;
10195            return Ok(false);
10196        }
10197        if request.phase == Phase::Requested {
10198            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10199                Ok(pr) => pr,
10200                Err(e) => {
10201                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10202                    return Ok(false);
10203                }
10204            };
10205            self.state.merge_repairs[i].phase = Phase::Fixing;
10206            self.state.land_approval = None;
10207            self.state.land_armed_head = None;
10208            self.state.save()?;
10209            // Serialize the exact records, including finding ids/details,
10210            // reconsideration reasons, final votes and verification output.
10211            let evidence = serde_json::to_string_pretty(&request)?;
10212            let reason = format!(
10213                "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}"
10214            );
10215            let budget = self.state.config.graph.land_rounds;
10216            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10217            match result {
10218                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10219                Ok(land::Fixed::Deferred) => {
10220                    // An unavailable fixer did not spend this repair request.
10221                    // Restore partial fallback work before retrying it, as for
10222                    // an interrupted repair, without closing the request.
10223                    let worktree = self
10224                        .state
10225                        .winner()
10226                        .context("repair has no winning branch")?
10227                        .worktree
10228                        .clone();
10229                    self.graft_restore(&worktree, &request.head).await?;
10230                    self.state.merge_repairs[i].phase = Phase::Requested;
10231                    self.stop_for_resource()?;
10232                    return Ok(false);
10233                }
10234                Ok(land::Fixed::Failed(why)) => {
10235                    self.hold_merge_repair(
10236                        i,
10237                        format!(
10238                            "repair failed: {why}; inspect the branch and run an explicit review"
10239                        ),
10240                    )?;
10241                    return Ok(false);
10242                }
10243                Err(e) => {
10244                    self.hold_merge_repair(
10245                        i,
10246                        format!(
10247                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10248                        ),
10249                    )?;
10250                    return Ok(false);
10251                }
10252            }
10253            // Even no change gets a real new reviewer wave. The previous
10254            // evidence remains in the request; a former clean/concluded round
10255            // cannot short-circuit the new review or gate.
10256            self.begin_merge_repair_review(i)?;
10257        }
10258        self.review_loop().await?;
10259        self.gate().await?;
10260        if self.resource_halt()? || self.state.parked {
10261            return Ok(false);
10262        }
10263        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10264            != Some(RunStatus::Gating)
10265            || !self.state.gate_allows_progress()
10266        {
10267            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10268            return Ok(false);
10269        }
10270        // Review and gate may have added commits after the initial repair.
10271        // Publish exactly their final head to the existing PR, with a lease.
10272        let winner = self
10273            .state
10274            .winner()
10275            .cloned()
10276            .context("repair has no winning branch")?;
10277        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10278        if self.state.gate_head.as_deref() != Some(after.as_str())
10279            || !git::is_clean(&winner.worktree).await?
10280        {
10281            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())?;
10282            return Ok(false);
10283        }
10284        let expected = self
10285            .state
10286            .pr_pushed_head
10287            .as_deref()
10288            .unwrap_or(&request.head)
10289            .to_owned();
10290        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10291        // Push the checked commit itself: a local ref moving after the check
10292        // must not change which commit the forge receives.
10293        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10294            return Ok(false);
10295        }
10296        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10297        let refspec = format!("{after}:refs/heads/{public}");
10298        let push = git::git_raw(
10299            &winner.worktree,
10300            &["push", &lease, &self.state.config.merge.remote, &refspec],
10301        )
10302        .await;
10303        match push {
10304            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10305            Ok(out) => {
10306                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10307                return Ok(false);
10308            }
10309            Err(e) => {
10310                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10311                return Ok(false);
10312            }
10313        }
10314        self.state.merge_repairs[i].phase = Phase::Complete;
10315        self.state.status = RunStatus::Landing;
10316        self.state.event(
10317            "repair",
10318            "new review and gate completed; fresh owner merge decision required",
10319        );
10320        self.state.save()?;
10321        Ok(true)
10322    }
10323
10324    fn merge_repair_artifacts(&self) -> PathBuf {
10325        let artifacts = agent::artifacts_dir(&self.state.dir());
10326        match self
10327            .state
10328            .merge_repairs
10329            .last()
10330            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10331        {
10332            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10333            None => artifacts,
10334        }
10335    }
10336
10337    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10338        if let Some(e2e) = self.state.head_e2e.take() {
10339            self.state
10340                .verification_history
10341                .push(crate::run::VerificationEvidence {
10342                    superseded_by: None,
10343                    archived_at: Some(Timestamp::now()),
10344                    fixes_spent: Some(self.state.gate_fixes.len()),
10345                    gate_head: None,
10346                    gate_ran: false,
10347                    gate: Vec::new(),
10348                    e2e: Some(e2e),
10349                });
10350        }
10351        self.state.reviews.clear();
10352        self.state.gate.clear();
10353        self.state.gate_ran = false;
10354        self.state.gate_head = None;
10355        self.state.gate_fixes.clear();
10356        self.state.gate_repair_e2e = None;
10357        self.state.pre_gate.clear();
10358        self.state.pre_gate_commit = None;
10359        self.state.contested_handoff = None;
10360        self.state.land_reruns = None;
10361        self.state.land_approval = None;
10362        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10363        self.state.status = RunStatus::Reviewing;
10364        self.state.save()
10365    }
10366
10367    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10368        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10369        self.state.merge_repairs[index].failure = Some(why.clone());
10370        self.state.status = RunStatus::Blocked;
10371        self.state.event("repair", why);
10372        self.state.save()
10373    }
10374
10375    // -------------------------------------------------------------- helpers
10376
10377    /// Fetch or create a seat, keeping its conversation across nodes.
10378    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10379        if let Some(existing) = self.state.seats.get(key)
10380            && existing.agent == agent
10381        {
10382            return existing.clone();
10383        }
10384        // A seat that changes agent mints its session id from the agent too,
10385        // like a handover: the old agent's uuid is already taken by the CLI.
10386        let fresh = if self.state.seats.contains_key(key) {
10387            handover_seat(key, agent, self.state.next_seat_seed())
10388        } else {
10389            SeatState::new(key, agent, self.state.seed)
10390        };
10391        self.state.seats.insert(key.to_owned(), fresh.clone());
10392        fresh
10393    }
10394
10395    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10396    /// seat to another roster agent, in which case that agent. Nodes that
10397    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10398    /// reconsideration) must keep talking to whoever answered it, not slip
10399    /// back to the agent that failed it.
10400    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10401        match self.state.seats.get(key) {
10402            Some(s) if s.agent != spec.id => {
10403                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10404            }
10405            _ => spec,
10406        }
10407    }
10408
10409    /// A candidate rendered for judging, with the leak policy applied.
10410    fn view(&self, c: &Candidate) -> CandidateView {
10411        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10412            .unwrap_or_default();
10413        let (patch, _) = blind::sanitize_patch(
10414            &format!("candidate {} patch", c.label),
10415            &raw,
10416            &self.state.config.blind,
10417        );
10418        CandidateView {
10419            label: c.label,
10420            branch: c.branch.clone(),
10421            summary: c.summary.clone(),
10422            stat: c.stat.clone(),
10423            patch,
10424        }
10425    }
10426
10427    /// The full candidate set as prompt text, for seats with no live session.
10428    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10429        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10430        prompt::judge(
10431            "(see above)",
10432            &views,
10433            self.roles.judges.len(),
10434            base_short,
10435            "en",
10436        )
10437    }
10438
10439    /// The final-vote prompt with everything a seat that has no session of its
10440    /// own needs: the candidates, the seat's own ranking and reasons, and the
10441    /// anonymised deliberation it took part in (only when there was one, so a
10442    /// handed-over seat never sees more than the seat it replaces did). The
10443    /// `Final vote` heading stays first.
10444    fn vote_prompt_full(
10445        &self,
10446        j: usize,
10447        labels: &[char],
10448        language: &str,
10449        candidates: &[Candidate],
10450        base_short: &str,
10451    ) -> String {
10452        let mut text = format!(
10453            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10454            prompt::final_vote(labels, language),
10455            self.state.instruction,
10456            self.candidate_block(candidates, base_short)
10457        );
10458        if let Some(own) = self
10459            .state
10460            .judgements
10461            .get(j)
10462            .filter(|r| !r.ranking.is_empty())
10463        {
10464            let reasons = own
10465                .reasons
10466                .iter()
10467                .map(|(k, v)| format!("- {k}: {v}"))
10468                .collect::<Vec<_>>()
10469                .join("\n");
10470            text.push_str(&format!(
10471                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10472                own.ranking.iter().collect::<String>(),
10473                if reasons.is_empty() {
10474                    ""
10475                } else {
10476                    ", because:\n"
10477                }
10478            ));
10479        }
10480        if !self.state.deliberation.is_empty() {
10481            text.push_str("\n# What was argued before this vote\n");
10482            for t in self.transcript(&[], j) {
10483                text.push_str(&format!(
10484                    "\n## {}{}\n\n{}\n",
10485                    t.who,
10486                    if t.is_self { " (you)" } else { "" },
10487                    t.body.trim()
10488                ));
10489            }
10490        }
10491        text
10492    }
10493
10494    /// Anonymised transcript for judge `self_idx`.
10495    ///
10496    /// The initial rankings are always the opening statements. Seeding them
10497    /// only when no turn had been taken yet meant every judge after the first
10498    /// argued against a single voice instead of against the actual split — the
10499    /// disagreement is the information, so it is always on the table.
10500    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10501        let mut turns = Vec::new();
10502        for j in &self.state.judgements {
10503            if j.ranking.is_empty() {
10504                continue;
10505            }
10506            let reasons = j
10507                .reasons
10508                .iter()
10509                .map(|(k, v)| format!("- {k}: {v}"))
10510                .collect::<Vec<_>>()
10511                .join("\n");
10512            turns.push(Turn {
10513                who: format!("Judge {} (opening ranking)", j.judge),
10514                is_self: j.judge == self_idx + 1,
10515                body: format!(
10516                    "Ranked {}{}{reasons}",
10517                    j.ranking.iter().collect::<String>(),
10518                    if reasons.is_empty() {
10519                        ""
10520                    } else {
10521                        ", because:\n"
10522                    }
10523                ),
10524            });
10525        }
10526        for t in self
10527            .state
10528            .deliberation
10529            .iter()
10530            .flat_map(|r| r.turns.iter())
10531            .chain(current)
10532        {
10533            turns.push(Turn {
10534                who: format!("Judge {}", t.judge),
10535                is_self: t.judge == self_idx + 1,
10536                body: t.body.clone(),
10537            });
10538        }
10539        turns
10540    }
10541}
10542
10543/// Does this seat still hold the context a follow-up prompt would rely on?
10544fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10545    agent::has_session(spec.kind, seat, sessions)
10546}
10547
10548/// The next entry in `roster` after `start`, never wrapping back to the
10549/// front, whose id is not in `tried` yet.
10550///
10551/// Starts one past `start` rather than at the front of `roster`: `start` is
10552/// the seat's own original position, and a seat whose candidate slot already
10553/// sits on the roster's second entry must fall through to the third next, not
10554/// restart at the first — which is very likely a different candidate's own
10555/// agent already. Never wraps back past `start`, for the same reason: an
10556/// entry earlier in the roster than the seat's own position is almost
10557/// certainly some *other* candidate slot's own agent, and once the tail of
10558/// the roster is exhausted there are no more untried agents for *this* seat
10559/// to fall through to — the caller's fallback chain ends there, exactly as
10560/// "no further untried agents remain in the list for that seat" asks for.
10561///
10562/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10563/// the same id twice (an operator's `roles.implementers` typo, or a
10564/// `[[agents]]` list reused across roles) must not let
10565/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10566/// over `roster` either finds an untried id or runs out, so this always
10567/// terminates regardless of duplicates.
10568fn next_untried_in_roster<'a>(
10569    roster: &'a [AgentSpec],
10570    start: usize,
10571    tried: &BTreeSet<String>,
10572) -> Option<&'a AgentSpec> {
10573    roster
10574        .get(start + 1..)?
10575        .iter()
10576        .find(|s| !tried.contains(&s.id))
10577}
10578
10579/// The successor for a seat, shared by all four seat kinds (implement, judge,
10580/// review, advise). `others` holds the ids that *currently* occupy the other
10581/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10582/// sees them), so roster entries beyond the seat count act as spares: a failed
10583/// seat goes to an agent no other seat holds whenever the roster permits.
10584///
10585/// `carried` is `Some` only for the review loop's carried failure history.
10586/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10587/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10588/// whole roster: untried and not another seat's occupant; (3) the plain walk
10589/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10590/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10591/// a better outcome than an empty seat, and it keeps the answer to "is there
10592/// a successor at all" exactly what it was before occupants were considered,
10593/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10594/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10595/// carried failure is a cheaper bet than doubling an agent on the panel, and
10596/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10597/// the same round are handled one at a time, so a seat later in the batch
10598/// sees an earlier one's new occupant but not yet its own freed agent.
10599fn pick_successor<'a>(
10600    roster: &'a [AgentSpec],
10601    start: usize,
10602    tried: &BTreeSet<String>,
10603    carried: Option<&BTreeSet<String>>,
10604    others: &BTreeSet<String>,
10605) -> Option<&'a AgentSpec> {
10606    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10607    roster
10608        .get(start + 1..)
10609        .and_then(|tail| {
10610            tail.iter()
10611                .filter(free)
10612                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10613        })
10614        .or_else(|| {
10615            carried
10616                .is_some()
10617                .then(|| roster.iter().find(free))
10618                .flatten()
10619        })
10620        .or_else(|| match carried {
10621            Some(c) => next_for_seat(roster, start, tried, c),
10622            None => next_untried_in_roster(roster, start, tried),
10623        })
10624}
10625
10626/// The next agent for a seat that carries its failure history across rounds
10627/// (the review loop). `round_tried` is this round's own bound and starts
10628/// empty every round; `carried_failed` only decides priority.
10629///
10630/// First: an id walking forward from `start`, never wrapping, that is neither
10631/// tried this round nor failed in an earlier one. Only when that is exhausted
10632/// does it rescue: the first roster id (in roster order, so this one *does*
10633/// look before `start`) not yet tried this round, which is by then a carried
10634/// failure. Each id is rescued at most once per round, so it cannot loop.
10635fn next_for_seat<'a>(
10636    roster: &'a [AgentSpec],
10637    start: usize,
10638    round_tried: &BTreeSet<String>,
10639    carried_failed: &BTreeSet<String>,
10640) -> Option<&'a AgentSpec> {
10641    roster
10642        .get(start + 1..)?
10643        .iter()
10644        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10645        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10646}
10647
10648/// Where a reviewer seat starts a round: the agent that last answered it when
10649/// it is still on the roster and not marked failed, else the spec's own agent
10650/// unless it failed, else the next roster agent that has not failed, else the
10651/// spec's own agent again (the whole roster failed). Ids no longer on the
10652/// roster are ignored. An empty roster has no handover, so the spec stands.
10653fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10654    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10655        return spec;
10656    };
10657    let ok = |id: &str| !h.failed.contains(id);
10658    if let Some(last) = h.last_ok.as_deref()
10659        && ok(last)
10660        && let Some(s) = roster.iter().find(|s| s.id == last)
10661    {
10662        return s.clone();
10663    }
10664    if ok(&spec.id) {
10665        return spec;
10666    }
10667    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10668    roster
10669        .get(from + 1..)
10670        .into_iter()
10671        .flatten()
10672        .chain(roster.iter())
10673        .find(|s| ok(&s.id))
10674        .cloned()
10675        .unwrap_or(spec)
10676}
10677
10678/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10679/// seed so a CLI that mints its session id up front (`--session-id`) never
10680/// reuses the uuid the previous agent already opened under the same seat key.
10681pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10682    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10683}
10684
10685/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10686/// so the classifier below and the code that builds the message cannot drift.
10687const TIMED_OUT: &str = "timed out";
10688
10689impl FailClass {
10690    /// `None` for an answer; otherwise how the turn failed.
10691    fn of(out: &AgentOutcome) -> Option<Self> {
10692        match out {
10693            AgentOutcome::Ok(_) => None,
10694            AgentOutcome::Quota(_) => Some(Self::Quota),
10695            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10696            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10697            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10698            // Not a failure of the agent. Callers check for it first; `None`
10699            // here means "no class to hand over on".
10700            AgentOutcome::ResourceBlocked(_) => None,
10701        }
10702    }
10703
10704    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10705    fn stem_word(&self) -> &'static str {
10706        match self {
10707            Self::Quota => "quota",
10708            _ => "handover",
10709        }
10710    }
10711}
10712
10713/// The message's first line with its variable parts removed — digit runs and
10714/// path-like tokens — so "exit code 2" and "exit code 7" read
10715/// as one kind of failure.
10716fn failure_signature(msg: &str) -> String {
10717    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10718    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10719    // the historical machine key while the process diagnosis uses readable prose.
10720    if let Some(code) = line
10721        .strip_prefix("process exited with no usable output (exit code ")
10722        .and_then(|s| s.strip_suffix(')'))
10723        .and_then(|s| s.parse::<i32>().ok())
10724    {
10725        line = format!("exited with some({code}) and no usable output");
10726    } else if matches!(
10727        line.as_str(),
10728        "process exited with no usable output (no exit code reported)"
10729            | "process exited with no usable output (exit code unavailable)"
10730    ) {
10731        line = "exited with none and no usable output".to_owned();
10732    }
10733    let mut out = Vec::new();
10734    for word in line.split_whitespace() {
10735        if word.contains('/') || word.contains('\\') {
10736            out.push("<path>".to_owned());
10737            continue;
10738        }
10739        let mut w = String::new();
10740        let mut in_digits = false;
10741        for c in word.chars() {
10742            if c.is_ascii_digit() {
10743                if !in_digits {
10744                    w.push('#');
10745                }
10746                in_digits = true;
10747            } else {
10748                in_digits = false;
10749                w.push(c);
10750            }
10751        }
10752        out.push(w);
10753    }
10754    out.join(" ").chars().take(120).collect()
10755}
10756
10757/// Whether a seat that just failed with `cur` may go to the next roster agent.
10758/// A quota or a timeout always may. Any other failure may not when the agent
10759/// before it failed the same way: an error the prompt causes would otherwise
10760/// walk the whole roster. `prev` is the class of the immediately preceding
10761/// agent's failure, so a quota or timeout in between breaks the run of
10762/// identical failures by itself.
10763fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10764    match cur {
10765        FailClass::Quota | FailClass::Timeout => true,
10766        FailClass::Other(_) => prev != Some(cur),
10767    }
10768}
10769
10770/// A short human reason for a failed outcome, for the handover record.
10771fn fail_reason(out: &AgentOutcome) -> String {
10772    match out {
10773        AgentOutcome::Ok(_) => String::new(),
10774        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10775        AgentOutcome::Dropped(o) => format!(
10776            "the CLI dropped the stream ({})",
10777            o.dropped
10778                .as_ref()
10779                .map(|d| d.why.as_str())
10780                .unwrap_or("it ended without delivering its answer")
10781        ),
10782        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10783            e.lines().next().unwrap_or("").chars().take(160).collect()
10784        }
10785    }
10786}
10787
10788/// Note one handover in the run: the structured record and, in the timeline,
10789/// the sentence a person reads. A quota keeps the wording it always had.
10790pub(crate) fn record_handover(
10791    state: &mut RunState,
10792    node: &str,
10793    seat: &str,
10794    from: &str,
10795    to: &str,
10796    class: &FailClass,
10797    reason: &str,
10798) {
10799    let message = if *class == FailClass::Quota {
10800        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10801    } else {
10802        format!("{seat}: handed over {from} -> {to} ({reason})")
10803    };
10804    state.event(node, message);
10805    state.handovers.push(Handover {
10806        at: Timestamp::now(),
10807        node: node.to_owned(),
10808        seat: seat.to_owned(),
10809        from: from.to_owned(),
10810        to: to.to_owned(),
10811        reason: reason.to_owned(),
10812    });
10813}
10814
10815/// Did this reply report running a command whose own CLI never confirmed an
10816/// exit status?
10817///
10818/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10819/// command *finished* (see that type's own doc), so this can only be `true`
10820/// for a command whose completion event carried no readable exit code — not
10821/// for one that simply is not mentioned at all. That is the one signal this
10822/// crate can read, from the same record `state.jobs` renders, about a reply
10823/// standing next to work its own CLI cannot vouch for finishing; it is
10824/// deliberately not a check on the exit code's *value* (a fixer legitimately
10825/// runs a command that fails mid-iteration before it succeeds) and not a
10826/// guess at a command still running in the background (which emits no event
10827/// at all, and so leaves no evidence here to find).
10828fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10829    commands.iter().any(|c| c.exit_code.is_none())
10830}
10831
10832/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10833/// trusted as a verified no-op — the adoption guard's own text-level half.
10834///
10835/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10836/// timed out): a marker only earns the benefit of the doubt from a turn the
10837/// CLI itself vouches for finishing properly, the same house style
10838/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10839/// *fix* report to for `commands`. A candidate that timed out, exited
10840/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10841/// is, whatever prose it wrote — this returns `None` before it ever looks at
10842/// `text`. The remaining guards (the tree really is empty, the evidence is
10843/// non-empty) are the caller's: this only reads what the reply *claimed*.
10844fn verified_noop_claim(
10845    usable: bool,
10846    commands: &[agent::CommandEvidence],
10847    text: &str,
10848) -> Option<String> {
10849    (usable && !has_unconfirmed_command(commands))
10850        .then(|| verdict::verified_noop(text))
10851        .flatten()
10852}
10853
10854fn short(commit: &str) -> String {
10855    commit.chars().take(7).collect()
10856}
10857
10858fn make_executable(path: &Path) -> Result<()> {
10859    #[cfg(unix)]
10860    {
10861        use std::os::unix::fs::PermissionsExt as _;
10862        let mut perms = std::fs::metadata(path)?.permissions();
10863        perms.set_mode(0o755);
10864        std::fs::set_permissions(path, perms)?;
10865    }
10866    #[cfg(not(unix))]
10867    {
10868        let _ = path;
10869    }
10870    Ok(())
10871}
10872
10873/// What every seat in one batch shares: where the answers are attributed, the
10874/// prompt overlay they inherit, and the build cache they are told to use.
10875///
10876/// A struct rather than four more parameters: `wave` also needs the run's
10877/// state (to record who is answering right now) and the attempt number, and
10878/// eight positional arguments is both unreadable and a clippy error.
10879struct WaveCtx<'a> {
10880    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
10881    /// paid for it.
10882    run: &'a str,
10883    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
10884    node: &'a str,
10885    prompts: &'a Prompts,
10886    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
10887    cache: Option<&'a Path>,
10888    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
10889    /// `JobRecord::round`. `None` for every other node.
10890    round: Option<usize>,
10891    /// Carry each seat's failed-agent history across waves (the review loop
10892    /// only): start-of-round priority and handover choice read
10893    /// [`RunState::seat_history`], and every answer or failure writes it.
10894    carry_seats: bool,
10895    /// The run's park / interrupt requests, so a wait for a shared resource
10896    /// can be abandoned the moment the operator asks to park.
10897    pauses: Option<(&'a Pause, &'a Pause)>,
10898}
10899
10900/// Shared scheduling policy for operations and spawned seat invocations.
10901fn repository_wait(
10902    state: &RunState,
10903    pauses: Option<(&Pause, &Pause)>,
10904) -> crate::repo_lock::WaitPolicy {
10905    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
10906    let inherited = crate::repo_lock::WaitPolicy::current();
10907    crate::repo_lock::WaitPolicy::new(
10908        Duration::from_secs(state.config.graph.timeout_resource_wait),
10909        move || {
10910            inherited.cancelled()
10911                || pauses
10912                    .as_ref()
10913                    .is_some_and(|(a, b)| a.parked() || b.parked())
10914        },
10915    )
10916}
10917
10918fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
10919    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
10920        state.event("resource", timeout.0.description());
10921        state.resource_block = Some(timeout.0.clone());
10922        return;
10923    }
10924    if error.is::<crate::repo_lock::ResourceBlocked>() {
10925        state.resource_block = Some(crate::run::ResourceBlock {
10926            cause: crate::run::ResourceBlockCause::Other,
10927            node: "repository".into(),
10928            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
10929                "disk admission"
10930            } else if error.to_string().contains("disk pressure") {
10931                "disk pressure"
10932            } else if error.to_string().contains("disk admission") {
10933                "disk admission"
10934            } else if error.to_string().contains(crate::incremental::BLOCKED) {
10935                "incremental cache admission"
10936            } else {
10937                "repository coordination"
10938            }
10939            .into(),
10940            detail: format!("{error:#}"),
10941            at: Timestamp::now(),
10942        });
10943        state.event("resource", error.to_string());
10944    }
10945}
10946
10947async fn coordinate_operation(
10948    state: &mut RunState,
10949    cwd: &Path,
10950    wait: &crate::repo_lock::WaitPolicy,
10951) -> Result<Option<crate::repo_lock::SeatLease>> {
10952    let result =
10953        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
10954            .await;
10955    if let Err(e) = &result {
10956        record_repository_block(state, e);
10957    }
10958    result
10959}
10960
10961/// Run one job, honouring the parallelism budget.
10962async fn run_one(
10963    job: SeatJob,
10964    sem: Arc<Semaphore>,
10965    ctx: &WaveCtx<'_>,
10966    state: &mut RunState,
10967    attempt: usize,
10968) -> (SeatState, AgentOutcome) {
10969    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
10970        .await
10971        .pop()
10972        .expect("one job in, one result out");
10973    (seat, out)
10974}
10975
10976/// Run every job concurrently, capped by the semaphore, preserving order.
10977///
10978/// Every seat in the batch is recorded into [`RunState::active`] before the
10979/// wave starts and cleared as each answer lands, so the run's own record says
10980/// who is still being waited on rather than only who finished.
10981async fn wave(
10982    jobs: Vec<SeatJob>,
10983    sem: Arc<Semaphore>,
10984    ctx: &WaveCtx<'_>,
10985    state: &mut RunState,
10986    attempt: usize,
10987) -> Vec<(usize, SeatState, AgentOutcome)> {
10988    let WaveCtx {
10989        run,
10990        node,
10991        prompts,
10992        cache,
10993        round,
10994        carry_seats: _,
10995        pauses,
10996    } = *ctx;
10997    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
10998    for job in &jobs {
10999        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11000    }
11001    if let Err(e) = state.save() {
11002        // A failed persist of "who is answering right now" must not abort the
11003        // wave: the seats are already being asked, and the alternative is
11004        // losing the answers to save a status line nobody may even be
11005        // watching.
11006        tracing::warn!("could not persist in-progress seats: {e:#}");
11007    }
11008    // Shared-mode waves keep their existing single lease. Isolated writers
11009    // acquire their own checkout's target at seat admission.
11010    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11011    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11012    // never borrowed from a job's agent budget (and never charged to it either,
11013    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11014    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11015    let cache_guard = if let Some(cache_dir) = cache {
11016        if jobs_had_a_writer {
11017            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11018            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11019            match acquire_cache_lease(
11020                state,
11021                cache_dir,
11022                &owner,
11023                resource_limit,
11024                node,
11025                node,
11026                &cancel,
11027            )
11028            .await
11029            {
11030                Ok(Some(g)) => Some(g),
11031                // Parking: leave without spawning anything. The run parks at
11032                // the next boundary and the seats are asked afresh on resume.
11033                Ok(None) => {
11034                    if let Some(block) = &mut state.resource_block {
11035                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11036                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11037                        };
11038                    }
11039                    return block_wave(
11040                        jobs,
11041                        state,
11042                        node,
11043                        attempt,
11044                        "parked while waiting for the shared build cache",
11045                    );
11046                }
11047                // An unreadable lease is not contention: keep the old
11048                // fallback (no shared cache for this wave's seats).
11049                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11050                Err(e) => {
11051                    // Writing seats may not build into a cache this run does
11052                    // not hold, and an agent that cannot be given one is not
11053                    // asked at all: the run stops resumably instead.
11054                    let why = format!("{e:#}");
11055                    state.event(
11056                        "resource",
11057                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11058                    );
11059                    return block_wave(jobs, state, node, attempt, &why);
11060                }
11061            }
11062        } else {
11063            None
11064        }
11065    } else {
11066        None
11067    };
11068    // Every job keeps its whole budget: the wait above was not the agent's.
11069    // Restart the seats' clocks so "started" means "being spawned now".
11070    state.seats_spawning(node, attempt);
11071    if let Err(e) = state.save() {
11072        tracing::warn!("could not persist the start of a wave: {e:#}");
11073    }
11074    // Queueing behind this wave's own seats for a parallelism slot is normal
11075    // (each of them is bounded by its own agent timeout); only a wait beyond
11076    // all of them plus the resource limit means the slots never came back.
11077    let slot_limit = resource_limit
11078        + jobs
11079            .iter()
11080            .map(|j| j.timeout)
11081            .max()
11082            .unwrap_or_default()
11083            .saturating_mul(jobs.len() as u32);
11084    let mut set = tokio::task::JoinSet::new();
11085    // Seats announce themselves here the moment they hold a parallelism
11086    // permit, i.e. just before their CLI is spawned.
11087    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11088    let overlay = prompts.overlay(node);
11089    let repository_wait = repository_wait(state, pauses);
11090    for (i, mut job) in jobs.into_iter().enumerate() {
11091        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11092        if cache.is_some() {
11093            job.prompt.push('\n');
11094            job.prompt
11095                .push_str(&prompt::build_cache_note(node, job.allow_write));
11096        }
11097        let sem = Arc::clone(&sem);
11098        let run = run.to_owned();
11099        let node = node.to_owned();
11100        // Only implementers were told about the task's attachments, so only
11101        // their seats get the directory widened for reading.
11102        let attachments = if node == "implement" {
11103            state.attachments.clone()
11104        } else {
11105            Vec::new()
11106        };
11107        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11108        // `prompt::build_cache_note`'s doc for why setting it anyway is
11109        // exactly how a sandboxed reviewer's write refusal got reported as a
11110        // defect in the patch, not a property of its own seat. And a
11111        // write-allowed one is handed it only when the lease above was
11112        // actually acquired: a wave that could not get it (`cache_guard` is
11113        // `None`, see its own comment) must not send seats to build into a
11114        // directory this run does not hold - that is the exact concurrent,
11115        // unmanaged-write race this module exists to prevent, not something
11116        // "proceeding anyway" is allowed to reintroduce.
11117        let cache = cache
11118            .filter(|_| job.allow_write && cache_guard.is_some())
11119            .map(Path::to_path_buf);
11120        let spawned_tx = spawned_tx.clone();
11121        let repository_wait = repository_wait.clone();
11122        let coordination = state.config.coordination.clone();
11123        let fetched_base = state.fetched_base.clone();
11124        set.spawn(async move {
11125            // A wait for a parallelism slot is scheduling, not the agent: it
11126            // is bounded by its own limit and ends as a resource block, never
11127            // as a timeout of the agent that was not started.
11128            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11129                Ok(p) => p,
11130                Err(_) => {
11131                    return (
11132                        i,
11133                        job.seat,
11134                        AgentOutcome::ResourceBlocked(format!(
11135                            "no parallel slot became free within {}s",
11136                            slot_limit.as_secs()
11137                        )),
11138                        None,
11139                        false,
11140                    );
11141                }
11142            };
11143            spawned_tx.send(job.seat.key.clone()).ok();
11144            let mut seat = job.seat;
11145            let out = repository_wait
11146                .scope(agent::invoke(
11147                    &job.spec,
11148                    &mut seat,
11149                    &Invocation {
11150                        coordination: coordination.as_ref(),
11151                        fetched_base: fetched_base.as_ref(),
11152                        cwd: &job.cwd,
11153                        prompt: &job.prompt,
11154                        timeout: job.timeout,
11155                        allow_write: job.allow_write,
11156                        sessions: job.sessions,
11157                        artifacts: &job.artifacts,
11158                        stem: &job.stem,
11159                        run: &run,
11160                        node: &node,
11161                        cache_dir: cache.as_deref(),
11162                        attachments: &attachments,
11163                        writable: &[],
11164                    },
11165                ))
11166                .await;
11167            let cache_block = out
11168                .as_ref()
11169                .err()
11170                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11171                .map(|timeout| timeout.0.clone());
11172            let interrupted = out
11173                .as_ref()
11174                .err()
11175                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11176            let out = match out {
11177                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11178                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11179                // Billed work the CLI failed to hand over is not an ordinary
11180                // failure, but its text is the CLI's raw error JSON, not an
11181                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11182                // read it as one by forgetting to check. `usable()` is always
11183                // false here (dropped implies an empty response), so this has
11184                // to be checked before the catch-all `Failed` below or the
11185                // one shape this exists for is lost with the rest.
11186                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11187                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11188                Ok(o) => AgentOutcome::Failed(format!(
11189                    "process exited with no usable output ({})",
11190                    crate::notices::exit_status(o.exit_code)
11191                )),
11192                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11193                    AgentOutcome::ResourceBlocked(e.to_string())
11194                }
11195                Err(e) => AgentOutcome::Failed(e.to_string()),
11196            };
11197            (i, seat, out, cache_block, interrupted)
11198        });
11199    }
11200    drop(spawned_tx);
11201    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11202    loop {
11203        let joined = tokio::select! {
11204            Some(key) = spawned_rx.recv() => {
11205                // The clock of this seat starts now, not when it queued.
11206                state.seat_spawned(&key);
11207                if let Err(e) = state.save() {
11208                    tracing::warn!("could not persist a seat's start: {e:#}");
11209                }
11210                continue;
11211            }
11212            joined = set.join_next() => joined,
11213        };
11214        let Some(joined) = joined else {
11215            break;
11216        };
11217        let (i, seat, out, cache_block, interrupted) = match joined {
11218            Ok(v) => v,
11219            // No seat to clear: a panicked task never reported which one it
11220            // was. The defensive sweep below this loop is what stops that
11221            // seat's `active` entry from surviving forever.
11222            Err(e) => {
11223                tracing::error!("agent task panicked: {e}");
11224                continue;
11225            }
11226        };
11227        state.seat_finished(&seat.key);
11228        if interrupted
11229            && node == "implement"
11230            && let Some(label) = state
11231                .candidates
11232                .iter()
11233                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11234                .map(|candidate| candidate.label)
11235        {
11236            state.candidate_preservation.insert(
11237                label,
11238                "interrupted implementation awaiting persistence".into(),
11239            );
11240            state.interrupted_implementations.insert(label);
11241        }
11242        if let Some(block) = cache_block
11243            && state.resource_block.is_none()
11244        {
11245            state.event("resource", block.description());
11246            state.resource_block = Some(block);
11247        }
11248        if let AgentOutcome::ResourceBlocked(why) = &out
11249            && state.resource_block.is_none()
11250        {
11251            state.resource_block = Some(crate::run::ResourceBlock {
11252                cause: crate::run::ResourceBlockCause::Other,
11253                node: node.to_owned(),
11254                kind: if why.contains("disk pressure") {
11255                    "disk pressure"
11256                } else if why.contains("disk admission") {
11257                    "disk admission"
11258                } else if why.contains(crate::incremental::BLOCKED) {
11259                    "incremental cache admission"
11260                } else if why.contains(crate::build_target::KIND) {
11261                    crate::build_target::KIND
11262                } else if why.contains("repository coordination") {
11263                    "repository coordination"
11264                } else {
11265                    "parallel slot"
11266                }
11267                .to_owned(),
11268                detail: why.clone(),
11269                at: Timestamp::now(),
11270            });
11271            let activity = if interrupted {
11272                "agent execution interrupted"
11273            } else {
11274                "no agent was started"
11275            };
11276            state.event("resource", format!("{node}: {activity} - {why}"));
11277        }
11278        record_jobs(state, node, round, &seat.key, &out);
11279        if let Err(e) = state.save() {
11280            tracing::warn!("could not persist a seat's completion: {e:#}");
11281        }
11282        if collected.len() <= i {
11283            collected.resize_with(i + 1, || None);
11284        }
11285        collected[i] = Some((i, seat, out));
11286    }
11287    // Belt-and-braces for the panic branch above: every seat this exact batch
11288    // started shares this `(node, attempt)` pair, and every seat that finished
11289    // normally already cleared itself, so anything left tagged with it here
11290    // can only be a panicked task's leftover. Cleared unconditionally rather
11291    // than left to read as still answering forever.
11292    if state
11293        .active
11294        .values()
11295        .any(|a| a.node == node && a.attempt == attempt)
11296    {
11297        state
11298            .active
11299            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11300        if let Err(e) = state.save() {
11301            tracing::warn!("could not persist the end of a wave: {e:#}");
11302        }
11303    }
11304    // Whether or not the lease above was actually held, several worktrees
11305    // may just have built into the cache with nothing here able to name one
11306    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11307    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11308    // clean it might not have strictly needed; trusting a stale match would
11309    // cost it a wrong answer.
11310    if let Some(cache_dir) = cache
11311        && jobs_had_a_writer
11312    {
11313        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11314    }
11315    if let Some(guard) = cache_guard {
11316        guard.release();
11317    }
11318    collected.into_iter().flatten().collect()
11319}
11320
11321/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11322/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11323/// this is data collection, not the fix-specific completion contract in
11324/// [`Runner::continue_fix_report`], and applies regardless of which node
11325/// asked.
11326///
11327/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11328/// evidence from; `Failed` does not, and correctly contributes nothing — a
11329/// timeout or crash is not itself evidence about a command the seat may have
11330/// started.
11331fn record_jobs(
11332    state: &mut RunState,
11333    node: &str,
11334    round: Option<usize>,
11335    seat: &str,
11336    out: &AgentOutcome,
11337) {
11338    let commands: &[agent::CommandEvidence] = match out {
11339        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11340        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11341    };
11342    let checked_at = Timestamp::now();
11343    for c in commands {
11344        state.jobs.push(JobRecord {
11345            node: node.to_owned(),
11346            round,
11347            seat: seat.to_owned(),
11348            id: c.id.clone(),
11349            description: c.description.clone(),
11350            checked_at,
11351            status: match c.exit_code {
11352                Some(0) => JobStatus::Completed,
11353                Some(_) => JobStatus::Failed,
11354                None => JobStatus::Unknown,
11355            },
11356            exit_code: c.exit_code,
11357            result_summary: c.result_summary.clone(),
11358            source: c.source.clone(),
11359        });
11360    }
11361}
11362
11363/// Is a review round clean, given how many reviewer seats answered against
11364/// how many the round expected?
11365///
11366/// A seat that never answered (timeout, crash, unparsable output) is not a
11367/// seat that read the patch and found nothing — treating it as such is
11368/// exactly the bug this function exists to close. Under the default `block`
11369/// policy a missing seat can never be clean; `warn` still requires the seats
11370/// that *did* answer to have found nothing blocking and verification to be
11371/// green.
11372///
11373/// `quota_missing` narrows that `block` default for exactly one cause of
11374/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11375/// a session limit lifts by the very next round buys nothing — the seat is
11376/// asked again with the same quota — so once every missing seat is accounted
11377/// for by a quota loss (and at least one seat *did* answer, so a decision has
11378/// something to rest on) the round is decided on the panel that could answer,
11379/// same as `warn` would. A panel that lost every seat to quota is not
11380/// decided here: `answered == 0` falls through to the existing `block`
11381/// fallback so a fully collapsed panel still waits rather than landing on no
11382/// review at all.
11383fn round_is_clean(
11384    blocking: usize,
11385    e2e_ok: bool,
11386    answered: usize,
11387    expected: usize,
11388    quota_missing: usize,
11389    policy: IncompleteReviewPolicy,
11390) -> bool {
11391    if blocking != 0 || !e2e_ok {
11392        return false;
11393    }
11394    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11395        return true;
11396    }
11397    answered > 0 && expected - answered <= quota_missing
11398}
11399
11400/// The review loop's own conclusion, derived entirely from its persisted
11401/// round records and the round budget that produced them — never from
11402/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11403/// recomputes the identical answer regardless of what an earlier node in the
11404/// same walk, or a previous walk, did to `status`.
11405///
11406/// `None` while more rounds remain to try, including when review never ran
11407/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11408/// gone clean, or the budget is spent, or the tree has stopped moving (see
11409/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11410///
11411/// - An incomplete panel that raised nothing is missing input, not a
11412///   verified tree — never a hand-off candidate, whatever verification said
11413///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11414/// - Otherwise, green e2e on the last round hands off (see
11415///   [`Runner::stop_reviewing`]); red e2e blocks.
11416///
11417/// A last round whose own verification is still `ResourceBlocked` — magi
11418/// itself never got a command to run, not evidence the patch is broken —
11419/// is neither: this returns `None` for it too, the same as "more rounds
11420/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11421/// handling of that shape) instead of this cheap recomputation guessing a
11422/// verdict a real attempt never produced.
11423pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11424    if max_rounds == 0
11425        || reviews.last().is_some_and(|r| {
11426            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11427        })
11428    {
11429        return Some(RunStatus::Gating);
11430    }
11431    let last = reviews.last()?;
11432    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11433    if reviews.len() < max_rounds && !stagnant {
11434        return None;
11435    }
11436    if last.incomplete() && last.blocking == 0 {
11437        return Some(RunStatus::Blocked);
11438    }
11439    if last.e2e_status() == E2eStatus::ResourceBlocked
11440        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11441    {
11442        return None;
11443    }
11444    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11445        RunStatus::Gating
11446    } else {
11447        RunStatus::Blocked
11448    })
11449}
11450
11451/// How long a re-ask may take, given the budget the first attempt had.
11452///
11453/// A `nudged` retry is a request to restate an answer the seat has already
11454/// worked out: it carries no new work, so it does not deserve the original
11455/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11456/// 133 seconds while a third sat for over ten minutes on a resumed session
11457/// holding 410 KB of prior output - and because the retry had inherited the
11458/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11459/// judging round whose other seats were long finished.
11460///
11461/// A quarter of the budget, with a floor so that a deliberately short timeout
11462/// does not collapse to nothing. A retry that re-sends the whole prompt
11463/// (because the seat kept no context) is the original job again, and keeps the
11464/// original budget.
11465pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11466    if nudged {
11467        (full / 4).max(Duration::from_secs(120)).min(full)
11468    } else {
11469        full
11470    }
11471}
11472
11473/// Run a wave and parse each reply, re-asking the seats whose reply was
11474/// unusable.
11475///
11476/// The re-ask is a nudge rather than the whole prompt again when the seat still
11477/// holds its conversation, which is the difference between a cheap retry and
11478/// paying for the entire candidate set twice.
11479///
11480/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11481/// successor in `roster` is handed to it instead of being re-asked: the
11482/// handover is the retry. A seat with no successor left (a single-agent
11483/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11484/// the asks to one seat in one node number at most
11485/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11486/// is asked once (a dropped stream is nudged first), and only the last agent
11487/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11488/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11489/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11490/// other failure stops the chain when the previous agent failed the same way
11491/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11492/// [`has_context`] is false and the job's own full prompt and full budget are
11493/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11494/// intermediate ones are not losses) and is returned as a failure like any
11495/// other absent seat — the caller decides whether the panel still has a
11496/// quorum. An empty `roster` disables handover: failures are nudged as they
11497/// always were, and a quota is simply lost. A reply that fails to parse or
11498/// validate is the prompt's doing and is only ever nudged, never handed over.
11499///
11500/// The returned [`SeatState`] names the agent that answered (or tried last).
11501#[allow(clippy::too_many_arguments)]
11502async fn ask_json_wave<T>(
11503    jobs: Vec<SeatJob>,
11504    sem: Arc<Semaphore>,
11505    retries: usize,
11506    roster: &[AgentSpec],
11507    ctx: &WaveCtx<'_>,
11508    losses: &mut Vec<QuotaLoss>,
11509    state: &mut RunState,
11510    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11511) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11512where
11513    T: serde::de::DeserializeOwned + Send + 'static,
11514{
11515    ask_wave_with(
11516        jobs,
11517        sem,
11518        retries,
11519        roster,
11520        ctx,
11521        losses,
11522        state,
11523        &|text: &str| {
11524            let v = verdict::extract_json::<T>(text)?;
11525            validate(&v)?;
11526            Ok(v)
11527        },
11528    )
11529    .await
11530}
11531
11532/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11533/// a node whose answer is prose (deliberation) shares the same handover,
11534/// failure classification, quota bookkeeping and bounds instead of a copy.
11535///
11536/// A seat handed to another roster agent is sent the job's `handover` prompt
11537/// (when it has one) rather than `prompt`: the new agent has no session, so a
11538/// resume-style prompt would be incomplete. That holds for the handover ask
11539/// and for every nudge to that agent whose `has_context` is false.
11540#[allow(clippy::too_many_arguments)]
11541async fn ask_wave_with<T>(
11542    jobs: Vec<SeatJob>,
11543    sem: Arc<Semaphore>,
11544    retries: usize,
11545    roster: &[AgentSpec],
11546    ctx: &WaveCtx<'_>,
11547    losses: &mut Vec<QuotaLoss>,
11548    state: &mut RunState,
11549    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11550) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11551where
11552    T: Send + 'static,
11553{
11554    let n = jobs.len();
11555    let originals: Vec<SeatJob> = jobs;
11556    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11557    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11558    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11559    // answer, N once it has gone through N nudges. Read back once this
11560    // returns, so a caller building a history record (`ReviewRecord`) can
11561    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11562    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11563    // field's own doc.
11564    let mut nudges: Vec<usize> = vec![0; n];
11565    // The agent now occupying each seat, the ids it has already been through,
11566    // where in the roster the walk began, the class of the last failure, and
11567    // the stem word of a handover not yet asked (full prompt, full budget).
11568    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11569    let mut tried: Vec<BTreeSet<String>> = specs
11570        .iter()
11571        .map(|s| BTreeSet::from([s.id.clone()]))
11572        .collect();
11573    let starts: Vec<usize> = specs
11574        .iter()
11575        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11576        .collect();
11577    let carry = ctx.carry_seats && !roster.is_empty();
11578    // Carried across rounds: ids that failed the seat earlier, and how the
11579    // last failure went (so a repeat of it is not handed over again).
11580    let carried: Vec<BTreeSet<String>> = originals
11581        .iter()
11582        .map(|j| {
11583            state
11584                .seat_history
11585                .get(&j.seat.key)
11586                .filter(|_| carry)
11587                .map(|h| h.failed.clone())
11588                .unwrap_or_default()
11589        })
11590        .collect();
11591    let mut prev: Vec<Option<FailClass>> = originals
11592        .iter()
11593        .map(|j| {
11594            state
11595                .seat_history
11596                .get(&j.seat.key)
11597                .filter(|_| carry)
11598                .and_then(|h| h.last_fail.clone())
11599        })
11600        .collect();
11601    let next_agent =
11602        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11603            let others: BTreeSet<String> = specs
11604                .iter()
11605                .enumerate()
11606                .filter(|(j, _)| *j != i)
11607                .map(|(_, s)| s.id.clone())
11608                .collect();
11609            pick_successor(
11610                roster,
11611                starts[i],
11612                tried,
11613                carry.then(|| &carried[i]),
11614                &others,
11615            )
11616            .cloned()
11617        };
11618    let mut fresh: Vec<Option<String>> = vec![None; n];
11619    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11620    let mut pending: Vec<usize> = (0..n).collect();
11621
11622    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11623    // asks: an agent with a successor is asked once and handed over, and only
11624    // a seat with no successor spends `retries` nudges on the same agent. This
11625    // only guarantees the loop's own termination whatever those say.
11626    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11627    for round in 0..max_rounds {
11628        if pending.is_empty() {
11629            break;
11630        }
11631        let mut batch = Vec::with_capacity(pending.len());
11632        let mut renudged: Vec<&str> = Vec::new();
11633        for &i in &pending {
11634            let src = &originals[i];
11635            // A seat now held by another agent than the job named has no
11636            // session of its own: it gets the full-context prompt whenever
11637            // it is asked in full (the handover ask, a nudge it cannot
11638            // resume).
11639            let full: &str = match &src.handover {
11640                Some(h) if specs[i].id != src.spec.id => h,
11641                _ => &src.prompt,
11642            };
11643            // The prompt and the budget are one decision: a nudge restates
11644            // finished work, a re-sent prompt redoes it.
11645            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11646                (
11647                    full.to_owned(),
11648                    src.timeout,
11649                    format!("{}-{word}-{}", src.stem, specs[i].id),
11650                )
11651            } else if nudges[i] == 0 {
11652                (full.to_owned(), src.timeout, src.stem.clone())
11653            } else {
11654                renudged.push(src.seat.key.as_str());
11655                let why = done[i]
11656                    .as_ref()
11657                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11658                    .unwrap_or_else(|| "no parsable answer".to_owned());
11659                let nudge = prompt::nudge(&why);
11660                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11661                let prompt = if nudged {
11662                    nudge
11663                } else {
11664                    format!("{full}\n\n---\n\n{nudge}")
11665                };
11666                (
11667                    prompt,
11668                    retry_budget(src.timeout, nudged),
11669                    format!("{}-retry{}", src.stem, nudges[i]),
11670                )
11671            };
11672            batch.push(SeatJob {
11673                spec: specs[i].clone(),
11674                seat: seats[i].clone(),
11675                cwd: src.cwd.clone(),
11676                prompt,
11677                timeout,
11678                allow_write: src.allow_write,
11679                sessions: src.sessions,
11680                artifacts: src.artifacts.clone(),
11681                stem,
11682                handover: None,
11683            });
11684        }
11685
11686        if !renudged.is_empty() {
11687            state.event(
11688                ctx.node,
11689                format!("retry {round}: re-asking {}", renudged.join(", ")),
11690            );
11691        }
11692        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11693        let mut still = Vec::new();
11694        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11695            seats[i] = seat;
11696            // No agent was asked: nothing to hand over, nudge, remember or
11697            // charge. The caller sees `resource_block` and stops the node.
11698            if let AgentOutcome::ResourceBlocked(why) = &out {
11699                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11700                continue;
11701            }
11702            let class = FailClass::of(&out);
11703            // A dropped stream is nudged first (the conversation is still
11704            // there to pick up); only a seat whose nudges are spent hands over.
11705            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11706                && nudges[i] < retries
11707                && !roster.is_empty();
11708            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11709                let next = should_hand_over(prev[i].as_ref(), &cur)
11710                    .then(|| next_agent(i, &tried[i], &specs))
11711                    .flatten();
11712                if carry {
11713                    let h = state
11714                        .seat_history
11715                        .entry(originals[i].seat.key.clone())
11716                        .or_default();
11717                    h.failed.insert(specs[i].id.clone());
11718                    h.last_fail = Some(cur.clone());
11719                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11720                        h.last_ok = None;
11721                    }
11722                    // Saved before the next agent is asked, so a restart in
11723                    // between does not forget who failed.
11724                    if let Err(e) = state.save() {
11725                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11726                    }
11727                }
11728                if let Some(next) = next {
11729                    record_handover(
11730                        state,
11731                        ctx.node,
11732                        &originals[i].seat.key,
11733                        &specs[i].id,
11734                        &next.id,
11735                        &cur,
11736                        &fail_reason(&out),
11737                    );
11738                    tried[i].insert(next.id.clone());
11739                    prev[i] = Some(cur.clone());
11740                    seats[i] =
11741                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11742                    specs[i] = next;
11743                    fresh[i] = Some(cur.stem_word().to_owned());
11744                    nudges[i] = 0;
11745                    done[i] = Some(Err(anyhow::anyhow!(
11746                        "handed over after: {}",
11747                        fail_reason(&out)
11748                    )));
11749                    still.push(i);
11750                    continue;
11751                }
11752            }
11753            if carry
11754                && !nudge_first
11755                && let Some(cur) = class.clone()
11756            {
11757                // The chain ended here (no successor, or a repeated failure).
11758                let h = state
11759                    .seat_history
11760                    .entry(originals[i].seat.key.clone())
11761                    .or_default();
11762                h.failed.insert(specs[i].id.clone());
11763                h.last_fail = Some(cur);
11764            }
11765            let parsed = match out {
11766                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11767                AgentOutcome::Quota(o) => {
11768                    last_quota[i] = o.quota.clone();
11769                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11770                }
11771                // Not a parseable answer: the nudge loop re-asks it, which is
11772                // exactly what a dropped stream needs. Just don't hand its raw
11773                // error JSON to `extract_json`.
11774                AgentOutcome::Dropped(o) => {
11775                    let why = o
11776                        .dropped
11777                        .as_ref()
11778                        .map(|d| d.why.as_str())
11779                        .unwrap_or("the CLI ended the stream without delivering its answer");
11780                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11781                }
11782                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11783                    Err(anyhow::anyhow!(e))
11784                }
11785            };
11786            let quota = class == Some(FailClass::Quota);
11787            let failed = parsed.is_err();
11788            if !failed && matches!(ctx.node, "judge" | "vote") {
11789                // A validated answer restores this seat's quorum presence,
11790                // including on the normal path after an all-seat block.
11791                state
11792                    .quota
11793                    .retain(|loss| loss.seat != originals[i].seat.key);
11794            }
11795            done[i] = Some(parsed);
11796            if carry && !failed {
11797                let h = state
11798                    .seat_history
11799                    .entry(originals[i].seat.key.clone())
11800                    .or_default();
11801                h.failed.remove(&specs[i].id);
11802                h.last_ok = Some(specs[i].id.clone());
11803                h.last_fail = None;
11804            }
11805            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11806            // fail the same way; and never re-ask a seat that already parsed.
11807            // A failed agent that still has a successor is not re-asked
11808            // either: the handover was its remedy and has just been refused
11809            // (the chain stops on a repeated failure class). A seat with no
11810            // successor left (a single-agent roster, the roster's tail, or an
11811            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11812            let agent_failure = class.is_some()
11813                && !nudge_first
11814                && !roster.is_empty()
11815                && next_agent(i, &tried[i], &specs).is_some();
11816            if failed && !quota && !agent_failure && nudges[i] < retries {
11817                nudges[i] += 1;
11818                still.push(i);
11819            }
11820        }
11821        pending = still;
11822    }
11823
11824    // One loss per seat whose chain ended on a quota: the intermediate ones
11825    // were absorbed by a handover and are not losses.
11826    for (i, q) in last_quota.into_iter().enumerate() {
11827        if let Some(quota) = q {
11828            losses.push(QuotaLoss::from_report(
11829                originals[i].seat.key.clone(),
11830                ctx.node,
11831                Some(&quota),
11832            ));
11833        }
11834    }
11835
11836    // A stalled quorum already has its own recovery checkpoint. Refresh
11837    // its missing seats before deciding whether it can resume.
11838    if state.status != RunStatus::Stalled
11839        && ctx.node != "deliberate"
11840        && n > 0
11841        && losses.len() == n
11842        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11843    {
11844        block_machine_outage(state, ctx.node, losses);
11845        state.quota.append(losses);
11846    }
11847
11848    seats
11849        .into_iter()
11850        .zip(done)
11851        .zip(nudges)
11852        .map(|((seat, res), attempts)| {
11853            (
11854                seat,
11855                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
11856                attempts,
11857            )
11858        })
11859        .collect()
11860}
11861
11862/// A node with no available agent has no task verdict. Preserve the node
11863/// checkpoint and record why a subsequent explicit resume is needed.
11864pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
11865    let mut auth: Vec<_> = losses
11866        .iter()
11867        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
11868        .map(|loss| loss.agent.clone())
11869        .collect();
11870    auth.sort();
11871    auth.dedup();
11872    let (kind, detail) = if auth.is_empty() {
11873        (
11874            "agent usage limit",
11875            "All seats reached their agent usage limits; resume after usage is available"
11876                .to_owned(),
11877        )
11878    } else {
11879        (
11880            "agent authentication",
11881            format!(
11882                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
11883                auth.join(", ")
11884            ),
11885        )
11886    };
11887    state.resource_block = Some(crate::run::ResourceBlock {
11888        node: node.to_owned(),
11889        kind: kind.to_owned(),
11890        cause: crate::run::ResourceBlockCause::Other,
11891        detail: detail.clone(),
11892        at: Timestamp::now(),
11893    });
11894    state.event(node, detail);
11895}
11896
11897/// Did the wave end without asking any agent (see [`block_wave`])?
11898fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
11899    results
11900        .iter()
11901        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
11902}
11903
11904/// Settle a wave that never spawned anything: every job answers
11905/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
11906/// else about the seat (session, history, quota) is touched.
11907fn block_wave(
11908    jobs: Vec<SeatJob>,
11909    state: &mut RunState,
11910    node: &str,
11911    attempt: usize,
11912    why: &str,
11913) -> Vec<(usize, SeatState, AgentOutcome)> {
11914    state.resource_wait = None;
11915    state
11916        .active
11917        .retain(|_, a| !(a.node == node && a.attempt == attempt));
11918    if let Err(e) = state.save() {
11919        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
11920    }
11921    jobs.into_iter()
11922        .enumerate()
11923        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
11924        .collect()
11925}
11926
11927/// Acquire the shared build cache's lease, waiting out contention within
11928/// `budget` (never past it — see AGENTS.md's build-cache section on why an
11929/// unbounded wait is never acceptable).
11930///
11931/// A first, non-blocking check happens before ever waiting; if it finds the
11932/// lease busy, that fact is logged as a `verify` event *and* flushed with
11933/// [`RunState::save`] immediately — not only once the wait finally succeeds
11934/// or gives up — so a `magi show` run by a different process while this one
11935/// is still waiting reads a `run.json` that says so, rather than whatever it
11936/// looked like before the wait started. The same applies to the terminal
11937/// failure: logged and saved before this returns `Err`, so a caller that
11938/// could not get the lease at all still leaves a legible record of why.
11939async fn acquire_cache_lease(
11940    state: &mut RunState,
11941    cache_dir: &Path,
11942    owner: &crate::cache::Owner,
11943    budget: Duration,
11944    node: &str,
11945    context: &str,
11946    cancel: &(dyn Fn() -> bool + Sync),
11947) -> Result<Option<crate::cache::Guard>> {
11948    let home = crate::run::home();
11949    let kind = if crate::build_target::isolated(&state.config) {
11950        crate::build_target::KIND
11951    } else {
11952        "shared build cache"
11953    };
11954    let started = Instant::now();
11955    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
11956        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
11957        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
11958        Err(e) => {
11959            state.event(
11960                "verify",
11961                format!(
11962                    "{context}: could not check the {kind} at {}: {e:#}",
11963                    cache_dir.display()
11964                ),
11965            );
11966            if let Err(e2) = state.save() {
11967                tracing::warn!("could not persist a cache-check failure: {e2:#}");
11968            }
11969            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
11970        }
11971    };
11972    state.event(
11973        "verify",
11974        format!(
11975            "{context}: waiting for the {kind} at {} ({})",
11976            cache_dir.display(),
11977            busy.describe()
11978        ),
11979    );
11980    // Seats of this node are waiting, not running: say so, so the countdown a
11981    // reader sees only ever measures an agent that has been spawned.
11982    state.resource_wait = Some(crate::run::ResourceWait {
11983        node: context.to_owned(),
11984        kind: kind.to_owned(),
11985        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
11986        since: Timestamp::now(),
11987        limit_secs: budget.as_secs(),
11988    });
11989    if let Err(e) = state.save() {
11990        tracing::warn!("could not persist a cache wait: {e:#}");
11991    }
11992    let remaining = budget.saturating_sub(started.elapsed());
11993    let waited = crate::cache::wait_for_unless(
11994        &home,
11995        cache_dir,
11996        owner,
11997        remaining,
11998        Duration::from_secs(5),
11999        cancel,
12000    )
12001    .await;
12002    state.resource_wait = None;
12003    let cause = match &waited {
12004        Ok(Some(_)) => None,
12005        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12006        Err(error)
12007            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12008        {
12009            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12010                target: cache_dir.to_owned(),
12011                waited_secs: started.elapsed().as_secs(),
12012                limit_secs: budget.as_secs(),
12013            })
12014        }
12015        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12016            Some(crate::run::ResourceBlockCause::Timeout {
12017                waited_secs: started.elapsed().as_secs(),
12018                limit_secs: budget.as_secs(),
12019            })
12020        }
12021        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12022    };
12023    if let Some(cause) = cause {
12024        let detail = match &waited {
12025            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12026            Err(error) => format!("{error:#}"),
12027        };
12028        state.resource_block = Some(crate::run::ResourceBlock {
12029            cause,
12030            node: node.to_owned(),
12031            kind: kind.into(),
12032            detail: format!("{}: {detail}", cache_dir.display()),
12033            at: Timestamp::now(),
12034        });
12035        state.event(
12036            "resource",
12037            state.resource_block.as_ref().unwrap().description(),
12038        );
12039    }
12040    if let Err(error) = state.save() {
12041        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12042    }
12043    waited
12044}
12045
12046/// The lease state could not be read at all (unreadable lease file, a
12047/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12048/// known to be contended, so a wave degrades to running without a shared cache
12049/// instead of stopping on a hold that [`crate::triage`] could never release.
12050#[derive(Debug)]
12051struct CacheCheckError(String);
12052
12053impl std::fmt::Display for CacheCheckError {
12054    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12055        f.write_str(&self.0)
12056    }
12057}
12058
12059impl std::error::Error for CacheCheckError {}
12060
12061/// Keep a specific acquisition outcome when the caller adds command evidence.
12062fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12063    let kind = if crate::build_target::isolated(&state.config) {
12064        crate::build_target::KIND
12065    } else {
12066        "shared build cache"
12067    };
12068    state
12069        .resource_block
12070        .get_or_insert_with(|| crate::run::ResourceBlock {
12071            cause: crate::run::ResourceBlockCause::Other,
12072            node: node.to_owned(),
12073            kind: kind.into(),
12074            detail: format!("{error:#}"),
12075            at: Timestamp::now(),
12076        });
12077    if let Err(error) = state.save() {
12078        tracing::warn!("could not persist cache resource block: {error:#}");
12079    }
12080}
12081
12082tokio::task_local! {
12083    static VERIFY_TARGET: PathBuf;
12084}
12085
12086/// Run `body` — a verify command batch — while holding the shared build
12087/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12088/// never interleave with another borrower's build against the same
12089/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12090/// timeout, or a human's own `magi review`. See the `cache` module doc for
12091/// why this matters more than Cargo's own per-target locking covers — two
12092/// *different* worktrees building the same package name/version into one
12093/// cache directory is a staleness bug, not a lock contention one.
12094///
12095/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12096/// agent waves do. Repository scheduling also has its own bounded,
12097/// cancellable resource-wait policy. Contention must not consume the
12098/// verification budget: `body` receives the full `budget` after both leases
12099/// are acquired and the cache is fresh. Without a shared cache, only
12100/// repository coordination is acquired before handing over the full budget.
12101///
12102/// A lease that cannot be acquired within the resource wait is reported as a single
12103/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12104/// verification — the same shape a spawn failure already takes in
12105/// [`run_commands`], so a caller need not special-case it.
12106#[allow(clippy::too_many_arguments)]
12107async fn with_cache_lease<'s, F, Fut>(
12108    state: &'s mut RunState,
12109    cache_dir: Option<&Path>,
12110    node: &str,
12111    seat: &str,
12112    worktree: &Path,
12113    head: &str,
12114    budget: Duration,
12115    context: &str,
12116    wait: &crate::repo_lock::WaitPolicy,
12117    body: F,
12118) -> Result<(Vec<CommandOutcome>, bool)>
12119where
12120    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12121    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12122{
12123    // Match editing waves: cache first, repository second. In particular,
12124    // pre_gate must never hold the repository while waiting for a wave's cache.
12125    let started = Instant::now();
12126    let home = crate::run::home();
12127    let isolated = crate::build_target::isolated(&state.config);
12128    let planned_target = if isolated {
12129        let plan = (|| -> Result<PathBuf> {
12130            crate::build_target::supports(&state.config)?;
12131            crate::build_target::resolve(&home, worktree)
12132        })();
12133        match plan {
12134            Ok(path) => Some(path),
12135            Err(error) => {
12136                record_cache_error(state, node, &error);
12137                return Ok((
12138                    vec![CommandOutcome {
12139                        command: "(planning isolated build cache)".into(),
12140                        code: None,
12141                        output_tail: format!("{error:#}"),
12142                        duration_ms: 0,
12143                        resource_blocked: true,
12144                        ..Default::default()
12145                    }],
12146                    false,
12147                ));
12148            }
12149        }
12150    } else {
12151        None
12152    };
12153    let cache_dir = planned_target.as_deref().or(cache_dir);
12154    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12155    let guard = if let Some(cache_dir) = cache_dir {
12156        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12157        match acquire_cache_lease(
12158            state,
12159            cache_dir,
12160            &owner,
12161            resource_limit,
12162            node,
12163            context,
12164            &|| wait.cancelled(),
12165        )
12166        .await
12167        .and_then(|g| {
12168            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12169        }) {
12170            Ok(g) => Some(g),
12171            Err(e) => {
12172                record_cache_error(state, node, &e);
12173                return Ok((
12174                    vec![CommandOutcome {
12175                        command: if isolated {
12176                            "(waiting for the isolated build cache)"
12177                        } else {
12178                            "(waiting for the shared build cache)"
12179                        }
12180                        .into(),
12181                        code: None,
12182                        output_tail: e.to_string(),
12183                        duration_ms: started.elapsed().as_millis() as u64,
12184                        resource_blocked: true,
12185                        ..Default::default()
12186                    }],
12187                    false,
12188                ));
12189            }
12190        }
12191    } else {
12192        None
12193    };
12194    let _coordination = coordinate_operation(state, worktree, wait).await?;
12195    if let Some(path) = &planned_target {
12196        state.event(node, format!("isolated build target: {}", path.display()));
12197    }
12198    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12199        let identity = crate::cache::Identity::new(worktree, head);
12200        let fresh = crate::cache::ensure_fresh(
12201            &home,
12202            cache_dir,
12203            &identity,
12204            &state.config.verify.cargo_manifests(),
12205        );
12206        if let Err(e) = fresh {
12207            record_cache_error(state, node, &e);
12208            state.event(
12209                "verify",
12210                format!(
12211                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12212                    worktree.display(),
12213                    short(head)
12214                ),
12215            );
12216            if let Some(guard) = guard {
12217                guard.release();
12218            }
12219            return Ok((
12220                vec![CommandOutcome {
12221                    command: "(confirming the build cache is fresh)".into(),
12222                    code: None,
12223                    output_tail: e.to_string(),
12224                    duration_ms: started.elapsed().as_millis() as u64,
12225                    resource_blocked: true,
12226                    ..Default::default()
12227                }],
12228                false,
12229            ));
12230        }
12231    }
12232    let future = body(state, budget);
12233    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12234        VERIFY_TARGET.scope(target, future).await
12235    } else {
12236        future.await
12237    };
12238    if !timed_out_pids.is_empty() {
12239        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12240    }
12241    // Drop repository coordination before releasing the cache, reversing the
12242    // acquisition order. A cancelled/error future also drops both guards.
12243    drop(_coordination);
12244    if let Some(guard) = guard {
12245        guard.release();
12246    }
12247    Ok((outcomes, retried))
12248}
12249
12250/// Poll `pids` — commands [`run_commands`] reports as still running when its
12251/// own timeout elapsed — until every one is confirmed gone, or
12252/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12253///
12254/// Real confirmation where confirmation is possible, not a substitute for
12255/// full process-tree observation: a grandchild the timed-out process spawned
12256/// and that survives independently of it is invisible to a pid check the
12257/// same way it always was, and continuing to observe and collect *that*
12258/// stays a different piece of work with its own owner. This only narrows a
12259/// fixed blind wait into an actual check of the pids this process does know
12260/// about.
12261async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12262    wait_for_pids_with(
12263        pids,
12264        crate::proc::pid_alive,
12265        LEASE_RELEASE_POLL,
12266        LEASE_RELEASE_MAX_WAIT,
12267    )
12268    .await;
12269}
12270
12271/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12272/// interval and ceiling supplied by the caller, so the polling *logic* -
12273/// returns as soon as every pid reports dead, gives up at the ceiling
12274/// otherwise - is testable on millisecond durations without asking the real
12275/// OS about a pid at all.
12276async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12277    pids: &[u32],
12278    alive: F,
12279    poll: Duration,
12280    max_wait: Duration,
12281) {
12282    let deadline = Instant::now() + max_wait;
12283    loop {
12284        if pids.iter().all(|&pid| !alive(pid)) {
12285            return;
12286        }
12287        if Instant::now() >= deadline {
12288            return;
12289        }
12290        tokio::time::sleep(poll).await;
12291    }
12292}
12293
12294/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12295/// admission that it could not even get a verify command to run, as opposed
12296/// to evidence the command actually produced? A caller that would otherwise
12297/// read a resource-blocked outcome as a red command must check this first:
12298/// see [`Runner::gate`], which retries rather than records `Blocked` when
12299/// this is true.
12300fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12301    outcomes.iter().any(|o| o.resource_blocked)
12302}
12303
12304/// What [`Runner::gate_fix_round`] decided.
12305pub(crate) enum GateFix {
12306    /// The tree changed and `verify.e2e` is still green: run the gate again.
12307    Retry,
12308    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12309    /// last failure stands and the run ends blocked.
12310    Stop,
12311    /// `verify.e2e` could not run after the fix (magi's own contention):
12312    /// decide nothing now, a later reentry retries.
12313    Defer,
12314}
12315
12316/// Is every red command in `outcomes` an ordinary failure the code could
12317/// explain: it ran, exited non-zero, and said something?
12318///
12319/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12320/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12321/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12322/// what the command is stays the gate's business.
12323pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12324    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12325    red.peek().is_some()
12326        && red.all(|o| {
12327            !o.resource_blocked
12328                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12329                && !o.output_tail.trim().is_empty()
12330        })
12331}
12332
12333/// Describe one verify command's outcome for the event log, distinguishing a
12334/// build/link failure — the toolchain never produced a binary to run — from
12335/// an actual test failure, since only the latter is a verdict on the patch.
12336fn e2e_outcome_label(o: &CommandOutcome) -> String {
12337    if o.ok() {
12338        return "pass".to_owned();
12339    }
12340    let reason = if o.build_failed() {
12341        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12342    } else {
12343        format!("FAIL ({:?})", o.code)
12344    };
12345    format!(
12346        "{reason}\n{}",
12347        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12348    )
12349}
12350
12351/// Does `outcomes` hold a failure worth one more run on the same commit?
12352///
12353/// Only an ordinary test result qualifies: every red command ran, exited
12354/// non-zero and said which way (not a build/link failure, a timeout or kill,
12355/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12356/// evidence about the machine or the toolchain, never about a flaky test.
12357fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12358    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12359    red.peek().is_some()
12360        && !verify_inconclusive(outcomes)
12361        && red.all(|o| {
12362            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12363        })
12364}
12365
12366/// Run `verify.e2e`, retrying once if the first attempt could not build or
12367/// link — a build/link failure is frequently a race against a shared
12368/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12369/// `verify` event per command, tagged with `context` (normally `"round N"`)
12370/// so the call sites that need this — the ordinary per-round leg in
12371/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12372/// will ever call a round green, `verify_current_head` and the gate-repair
12373/// check — read identically in the event log.
12374///
12375/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12376/// only after the failed commands have run once more on the same commit, in
12377/// the same worktree and — because the caller holds it around this whole
12378/// function — under the same cache lease, with a full `timeout` of their own
12379/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12380/// flake: the head is verified, the first failure is recorded and filed
12381/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12382/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12383/// preserving bounded evidence and artifact references for both attempts;
12384/// it claims a matching reproduction only when both attempts yield identical
12385/// confirmed terminal test failures. One verification is therefore run at most
12386/// three times: the build/link retry, then this one rerun. `round` is the
12387/// review round the verification belongs to, if any.
12388async fn run_e2e_with_retry(
12389    state: &mut RunState,
12390    shell: &[String],
12391    commands: &[String],
12392    worktree: &Path,
12393    timeout: Duration,
12394    context: &str,
12395    round: Option<usize>,
12396) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12397    let (mut e2e, mut timed_out_pids) = run_commands(
12398        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12399    )
12400    .await;
12401    for o in &e2e {
12402        state.event(
12403            "verify",
12404            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12405        );
12406    }
12407    // A build/link failure is not a verdict on the patch — it is frequently a
12408    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12409    // one retry before letting a red like that decide the round.
12410    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12411    if verify_retried {
12412        state.event(
12413            "verify",
12414            format!(
12415                "{context}: verify could not build/link, not a test result — retrying once \
12416                 before concluding"
12417            ),
12418        );
12419        let retried = run_commands(
12420            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12421        )
12422        .await;
12423        e2e = retried.0;
12424        // Both attempts' timeouts matter, not just the last one: the first
12425        // attempt's descendants may still be alive alongside the retry's.
12426        timed_out_pids.extend(retried.1);
12427        for o in &e2e {
12428            state.event(
12429                "verify",
12430                format!(
12431                    "{context}: retry `{}` -> {}",
12432                    o.command,
12433                    e2e_outcome_label(o)
12434                ),
12435            );
12436        }
12437    }
12438    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12439        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12440        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12441        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12442        state.event(
12443            "verify",
12444            format!(
12445                "{context}: {} failed with a test result — running it once more on the same \
12446                 commit {} before deciding",
12447                rerun_commands
12448                    .iter()
12449                    .map(|c| format!("`{c}`"))
12450                    .collect::<Vec<_>>()
12451                    .join(", "),
12452                short(&head)
12453            ),
12454        );
12455        let (second, pids) = run_commands(
12456            state,
12457            "verify",
12458            "e2e",
12459            1 + usize::from(verify_retried),
12460            shell,
12461            &rerun_commands,
12462            worktree,
12463            timeout,
12464        )
12465        .await;
12466        timed_out_pids.extend(pids);
12467        for o in &second {
12468            state.event(
12469                "verify",
12470                format!(
12471                    "{context}: rerun `{}` -> {}",
12472                    o.command,
12473                    e2e_outcome_label(o)
12474                ),
12475            );
12476        }
12477        for (slot, &i) in failed.iter().enumerate() {
12478            let Some(again) = second.get(slot) else {
12479                break;
12480            };
12481            let first = std::mem::replace(&mut e2e[i], again.clone());
12482            if again.ok() {
12483                let signature = crate::flake::signature(&first.output_tail, first.code);
12484                let flake = crate::run::VerifyFlake {
12485                    round,
12486                    context: context.to_owned(),
12487                    head: head.clone(),
12488                    command: first.command.clone(),
12489                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12490                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12491                    at: Timestamp::now(),
12492                    task: None,
12493                    filed: false,
12494                    filing_error: None,
12495                };
12496                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12497            } else if !again.resource_blocked {
12498                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
12499                let message = crate::verify_evidence::rerun_event_message(
12500                    context,
12501                    &e2e[i].command,
12502                    &comparison,
12503                );
12504                e2e[i].rerun_comparison = Some(comparison);
12505                state.event("verify", message);
12506            }
12507        }
12508    }
12509    (e2e, verify_retried, timed_out_pids)
12510}
12511
12512/// Run configured shell commands in `cwd`, in order. The second element is
12513/// the pid of every command that hit `timeout` and was still running when
12514/// this stopped waiting on it (best-effort: `None` when the platform did not
12515/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12516/// that releases a shared resource afterward needs to know.
12517///
12518/// Records `task` into [`RunState::active`] at every command boundary
12519/// (`RunState::task_command`) and clears it once the whole list has run
12520/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12521/// for minutes with no seat and no output of its own to show for it (see
12522/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12523/// apart from "not yet run" without this), and this is the only place that
12524/// knows which command is running right now and how many are left. Three
12525/// saves per command — start, not per second — matching the same "only at a
12526/// boundary" rule [`wave`] already follows for seats.
12527#[allow(clippy::too_many_arguments)]
12528async fn run_commands(
12529    state: &mut RunState,
12530    node: &str,
12531    task: &str,
12532    attempt: usize,
12533    shell: &[String],
12534    commands: &[String],
12535    cwd: &Path,
12536    timeout: Duration,
12537) -> (Vec<CommandOutcome>, Vec<u32>) {
12538    let isolated = crate::build_target::isolated(&state.config);
12539    if isolated && let Some(block) = &state.resource_block {
12540        return (
12541            vec![CommandOutcome {
12542                command: "(isolated build admission)".into(),
12543                code: None,
12544                output_tail: block.description(),
12545                duration_ms: 0,
12546                resource_blocked: true,
12547                ..Default::default()
12548            }],
12549            Vec::new(),
12550        );
12551    }
12552    if commands.is_empty() {
12553        // Nothing to mark as running and nothing to clear — an empty list
12554        // means "not configured", and touching `active` (or the disk) over
12555        // that would be a write for every round of a repo with no
12556        // `verify.e2e` / `verify.gate` commands at all.
12557        return (Vec::new(), Vec::new());
12558    }
12559    let mut out = Vec::new();
12560    let mut timed_out_pids = Vec::new();
12561    let total = commands.len();
12562    for (idx, command) in commands.iter().enumerate() {
12563        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12564        if let Err(e) = state.save() {
12565            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12566        }
12567        let started = Instant::now();
12568        let mut cmd = tokio::process::Command::new(&shell[0]);
12569        cmd.quiet();
12570        // Verify the checkout as a standalone caller. Worker ownership and
12571        // pinned executable selection belong to this driver, not to tests or
12572        // tools it runs. Preserve home/seat context and Running's containment.
12573        for key in crate::worker::INVOCATION_ENV {
12574            cmd.env_remove(key);
12575        }
12576        cmd.env_remove(crate::build_id::EXPECT_ENV);
12577        cmd.args(&shell[1..])
12578            .current_dir(cwd)
12579            .stdin(std::process::Stdio::null())
12580            .stdout(std::process::Stdio::piped())
12581            .stderr(std::process::Stdio::piped())
12582            .kill_on_drop(true);
12583        let mut outputs = Vec::new();
12584        let mut cache = None;
12585        let home = crate::run::home();
12586        let head = if isolated {
12587            Some(git::rev_parse(cwd, "HEAD").await)
12588        } else {
12589            None
12590        };
12591        let protected = (|| -> Result<()> {
12592            crate::incremental::configure(&mut cmd, cwd)?;
12593            cache = if isolated {
12594                let target = VERIFY_TARGET
12595                    .try_with(Clone::clone)
12596                    .context("isolated verification has no target lease")?;
12597                cmd.arg(crate::build_target::command::normalize(command)?);
12598                crate::build_target::command::configure(&mut cmd, &target)?;
12599                Some(target)
12600            } else {
12601                crate::build_target::command::clear(&mut cmd)?;
12602                cmd.arg(command);
12603                state.config.cache_dir()
12604            };
12605            let mut paths = vec![cwd.to_owned()];
12606            if let Some(cache) = &cache {
12607                paths.push(cache.clone());
12608            }
12609            let admit = if isolated {
12610                crate::retention::OutputLease::admit_isolated
12611            } else {
12612                crate::retention::OutputLease::admit
12613            };
12614            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12615            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12616                outputs.push(guard);
12617            }
12618            if let Some(cache) = &cache {
12619                outputs.push(crate::retention::OutputLease::cache(
12620                    &crate::run::home(),
12621                    cache,
12622                    false,
12623                )?);
12624                if let Some(head) = head {
12625                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12626                    if task == "pre_gate" {
12627                        crate::cache::invalidate_identity(&home, cache);
12628                    }
12629                }
12630            }
12631            Ok(())
12632        })();
12633        if let Err(e) = protected {
12634            let detail = format!("execution admission unavailable: {e:#}");
12635            state.resource_block = Some(crate::run::ResourceBlock {
12636                cause: crate::run::ResourceBlockCause::Other,
12637                node: node.to_owned(),
12638                kind: if detail.contains("disk admission") {
12639                    "disk admission"
12640                } else {
12641                    "output ownership"
12642                }
12643                .to_owned(),
12644                detail: detail.clone(),
12645                at: Timestamp::now(),
12646            });
12647            out.push(CommandOutcome {
12648                command: command.clone(),
12649                code: None,
12650                output_tail: detail,
12651                duration_ms: 0,
12652                resource_blocked: true,
12653                ..Default::default()
12654            });
12655            break;
12656        }
12657        let spawned = if isolated {
12658            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12659        } else {
12660            crate::seat_process::Running::spawn(cmd, None, outputs)
12661        };
12662        let (code, out_text, err_text, body) = match spawned {
12663            Ok(mut running) => {
12664                let pid = running.child().id();
12665                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12666                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12667                let mut paths = vec![cwd.to_owned()];
12668                if let Some(cache) = cache {
12669                    paths.push(cache);
12670                }
12671                let mut pressure = None;
12672                let status = tokio::select! {
12673                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12674                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12675                        pressure = Some(reason); None
12676                    }
12677                };
12678                let (code, failure) = match status {
12679                    Some(Ok(Ok(status))) => (
12680                        status.code(),
12681                        status
12682                            .code()
12683                            .is_none()
12684                            .then(|| format!("command terminated: {status}")),
12685                    ),
12686                    Some(Ok(Err(error))) => {
12687                        (None, Some(format!("failed waiting for command: {error}")))
12688                    }
12689                    Some(Err(_)) => {
12690                        // Leased cleanup confirms process-tree death itself.
12691                        // Unleased commands still need the caller's PID check
12692                        // after kill-on-drop, before releasing cache ownership.
12693                        if !running.coordinated()
12694                            && let Some(pid) = pid
12695                        {
12696                            timed_out_pids.push(pid);
12697                        }
12698                        (
12699                            None,
12700                            Some(format!("timed out after {}s", timeout.as_secs())),
12701                        )
12702                    }
12703                    None => (None, None),
12704                };
12705                running.finish().await;
12706                if let Some(reason) = pressure {
12707                    state.resource_block = Some(crate::run::ResourceBlock {
12708                        cause: crate::run::ResourceBlockCause::Other,
12709                        node: node.to_owned(),
12710                        kind: "disk pressure".to_owned(),
12711                        detail: reason.clone(),
12712                        at: Timestamp::now(),
12713                    });
12714                    out.push(CommandOutcome {
12715                        command: command.clone(),
12716                        code: None,
12717                        output_tail: reason,
12718                        duration_ms: started.elapsed().as_millis() as u64,
12719                        resource_blocked: true,
12720                        ..Default::default()
12721                    });
12722                    break;
12723                }
12724                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12725                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
12726                let mut body = out_text.clone();
12727                body.push_str(&err_text);
12728                if let Some(failure) = failure {
12729                    body.push('\n');
12730                    body.push_str(&failure);
12731                }
12732                (code, out_text, err_text, body)
12733            }
12734            Err(e) if isolated => {
12735                let e = anyhow::Error::new(e)
12736                    .context(format!("could not start managed build `{}`", shell[0]));
12737                record_cache_error(state, node, &e);
12738                out.push(CommandOutcome {
12739                    command: command.clone(),
12740                    code: None,
12741                    output_tail: format!("{e:#}"),
12742                    duration_ms: 0,
12743                    resource_blocked: true,
12744                    ..Default::default()
12745                });
12746                break;
12747            }
12748            Err(e) => (
12749                None,
12750                String::new(),
12751                String::new(),
12752                format!("failed to spawn `{}`: {e}", shell[0]),
12753            ),
12754        };
12755        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12756        let mut artifact = None;
12757        if !body.is_empty() {
12758            // The full text is kept whatever the summary dropped. A fresh
12759            // name per command so a resume or retry never overwrites an
12760            // earlier run's output. A failed write changes no verdict.
12761            match crate::run::write_verification_artifact(state, task, &body) {
12762                Ok(name) => {
12763                    let rel = format!("artifacts/{name}");
12764                    if summary != body {
12765                        summary = format!("[full output: {rel}]\n{summary}");
12766                    }
12767                    artifact = Some(rel);
12768                }
12769                Err(e) => {
12770                    let warning = format!("could not save the full {task} output: {e:#}");
12771                    tracing::warn!("{warning}");
12772                    state.event(node, warning);
12773                    if summary != body {
12774                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12775                    }
12776                }
12777            }
12778        }
12779        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12780        let mut outcome = CommandOutcome {
12781            command: command.clone(),
12782            code,
12783            output_tail: summary,
12784            duration_ms: started.elapsed().as_millis() as u64,
12785            resource_blocked,
12786            artifact,
12787            failure_evidence: None,
12788            rerun_comparison: None,
12789        };
12790        if !outcome.ok() && !outcome.resource_blocked {
12791            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
12792                code,
12793                outcome.build_failed(),
12794                &out_text,
12795                &err_text,
12796            ));
12797        }
12798        out.push(outcome);
12799        if resource_blocked {
12800            state.resource_block = Some(crate::run::ResourceBlock {
12801                cause: crate::run::ResourceBlockCause::Other,
12802                node: node.to_owned(),
12803                kind: "incremental cache admission".into(),
12804                detail: body,
12805                at: Timestamp::now(),
12806            });
12807            break;
12808        }
12809    }
12810    state.task_finished(task);
12811    if let Err(e) = state.save() {
12812        tracing::warn!("could not persist the end of {task}: {e:#}");
12813    }
12814    (out, timed_out_pids)
12815}
12816
12817/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12818/// section (`report::run`) and in the `merge` event this node records — for
12819/// the operator to run by hand.
12820///
12821/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12822/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12823/// merge commits", or "require linear history") rejects the push a `--no-ff`
12824/// merge would produce, which is exactly the guidance this function replaces.
12825/// `message`'s first line becomes the squash commit's subject, matching the
12826/// note `report::run` prints alongside this command — see that function for
12827/// why an explicit subject is not optional there.
12828fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12829    let repo = repo.display();
12830    match style {
12831        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12832        MergeStyle::Squash => {
12833            // The subject sits inside double quotes, and a title an agent
12834            // wrote may carry the characters that break out of them.
12835            let subject = message
12836                .lines()
12837                .next()
12838                .unwrap_or(branch)
12839                .replace(['\\', '"', '$', '`'], "");
12840            format!(
12841                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12842            )
12843        }
12844        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12845    }
12846}
12847
12848/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12849/// under the hood, rejects a `title` over 256 characters and the whole
12850/// command fails — no PR at all, for a run whose body was otherwise fine
12851/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12852/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12853/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12854/// this bound. It is a margin, not a guarantee — a title packed
12855/// with multi-unit characters could still in principle land close to the
12856/// edge, but a real task title's occasional emoji or accented letter fits
12857/// comfortably inside it.
12858const PR_TITLE_MAX: usize = 240;
12859
12860/// A pull request title from the opening line of `text`, or `None` when that
12861/// line is not English (GitHub text is) or has no letters.
12862///
12863/// A line within `max` is kept as is. A longer one is cut at the end of its
12864/// first sentence when that falls inside `max`, else at a word boundary with a
12865/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
12866/// make every merely-truncated title look non-English). The language check
12867/// runs on the kept text before any mark is added, so only what GitHub will
12868/// show is judged: an English opening followed by non-ASCII far past the cut
12869/// still passes.
12870fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
12871    let line = queue::first_line(text)?;
12872    let chars: Vec<char> = line.chars().collect();
12873    let (kept, mark) = if chars.len() <= max {
12874        (line.to_owned(), "")
12875    } else if let Some(end) = sentence_end(&chars, max) {
12876        (chars[..end].iter().collect::<String>(), "")
12877    } else {
12878        let room = max.saturating_sub(3);
12879        // Cut at the last space inside the room; when the char just past the
12880        // room is a space the room already ends on a word.
12881        let cut = if chars[room].is_whitespace() {
12882            room
12883        } else {
12884            chars[..room]
12885                .iter()
12886                .rposition(|c| c.is_whitespace())
12887                .unwrap_or(room)
12888        };
12889        let head: String = chars[..cut].iter().collect();
12890        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
12891        (head.to_owned(), "...")
12892    };
12893    if kept.is_empty() {
12894        return None;
12895    }
12896    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
12897        return None;
12898    }
12899    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
12900        return None;
12901    }
12902    Some(format!("{kept}{mark}"))
12903}
12904
12905/// The char length of the first sentence of `chars` when it ends within `max`
12906/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
12907/// abbreviations so `e.g. foo` does not end a title early.
12908fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
12909    const MIN: usize = 20;
12910    for i in MIN..max.min(chars.len()) {
12911        if !matches!(chars[i], '.' | '!' | '?') {
12912            continue;
12913        }
12914        let Some(&next) = chars.get(i + 1) else {
12915            continue;
12916        };
12917        if !next.is_whitespace() {
12918            continue;
12919        }
12920        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
12921        if after.is_some_and(|c| c.is_ascii_lowercase()) {
12922            continue;
12923        }
12924        let word: String = chars[..i]
12925            .iter()
12926            .rev()
12927            .take_while(|c| !c.is_whitespace())
12928            .collect::<Vec<_>>()
12929            .into_iter()
12930            .rev()
12931            .collect();
12932        let word = word.to_ascii_lowercase();
12933        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
12934            continue;
12935        }
12936        let end = chars[..i]
12937            .iter()
12938            .rposition(|c| !c.is_whitespace())
12939            .map_or(i, |p| p + 1);
12940        return Some(end);
12941    }
12942    None
12943}
12944
12945/// What `merge = "pr"` (and the merge commit of the other modes) says about a
12946/// change: a title and a body describing what was *implemented*, not the task
12947/// that asked for it. A task reads as a request; a reader of the merged
12948/// history wants the change.
12949struct PrMessage {
12950    title: String,
12951    body: String,
12952}
12953
12954impl PrMessage {
12955    /// Title, blank line, body. The first line is the squash/merge commit
12956    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
12957    /// has to stay one sensible line.
12958    fn commit_message(&self) -> String {
12959        format!("{}\n\n{}", self.title, self.body)
12960    }
12961}
12962
12963/// The text after a leading `TITLE:` (any case) on `line`.
12964fn title_marker(line: &str) -> Option<&str> {
12965    let line = line.trim();
12966    let head = line.get(..6)?;
12967    head.eq_ignore_ascii_case("title:")
12968        .then(|| line[6..].trim())
12969}
12970
12971/// The implementer's own one-line title: the `TITLE:` line the implement
12972/// prompt asks for at the top of its SUMMARY. Candidate commits are all
12973/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
12974/// source, and a title that says as much is refused here too.
12975fn summary_title(summary: &str) -> Option<String> {
12976    let first = summary.lines().find(|l| !l.trim().is_empty())?;
12977    let raw = title_marker(first)?;
12978    if raw.is_empty() {
12979        return None;
12980    }
12981    let title = queue::title_from(raw, PR_TITLE_MAX);
12982    let lower = title.to_ascii_lowercase();
12983    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12984        return None;
12985    }
12986    Some(title)
12987}
12988
12989/// How `open_review`'s instruction begins; see [`landing_title`].
12990const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
12991
12992/// Marker `open_review` gives a candidate that nothing in the roster wrote.
12993pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
12994
12995/// Does this run review work that already existed, rather than implement a
12996/// task? Runs recorded before `reviewed_commits` existed carry only the
12997/// candidate marker.
12998pub(crate) fn is_review_run(state: &RunState) -> bool {
12999    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13000}
13001
13002/// The title of a review-only run: the subject of the oldest commit under
13003/// review. Later commits are usually fixups, and `instruction` is the review
13004/// prompt, which says nothing about the change. GitHub text is English, so a
13005/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13006fn review_title(state: &RunState) -> Option<String> {
13007    english_subject(
13008        state.reviewed_commits.as_ref()?.first()?,
13009        state.config.graph.github_english(),
13010    )
13011}
13012
13013/// `raw` as a pull request title, or `None` when it is blank, not English
13014/// (GitHub text is), or one of magi's own candidate commit subjects.
13015fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13016    let raw = raw.trim();
13017    if raw.is_empty() {
13018        return None;
13019    }
13020    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13021        return None;
13022    }
13023    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13024        return None;
13025    }
13026    let title = queue::title_from(raw, PR_TITLE_MAX);
13027    let lower = title.to_ascii_lowercase();
13028    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13029        return None;
13030    }
13031    Some(title)
13032}
13033
13034/// What a review-only run's branch says about itself, read at the moment the
13035/// pull request is opened.
13036#[derive(Debug, Clone, PartialEq, Eq)]
13037struct BranchFacts {
13038    /// `(subject, body)` of each commit, oldest first.
13039    commits: Vec<(String, String)>,
13040    /// Trimmed `git diff --stat`.
13041    stat: String,
13042}
13043
13044/// Longest diff stat shown: this many file lines plus the summary line.
13045const STAT_FILE_LINES: usize = 25;
13046/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13047const COMMITS_MAX_CHARS: usize = 20_000;
13048
13049/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13050/// say or finds nothing, so the caller falls back to what the run recorded.
13051async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13052    let commits = git::commit_log(repo, base, branch).await.ok()?;
13053    if commits.is_empty() {
13054        return None;
13055    }
13056    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13057    let lines: Vec<&str> = stat.lines().collect();
13058    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13059        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13060        let more = format!(" ... {omitted} more file(s)");
13061        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13062        kept.push(&more);
13063        kept.push(lines[lines.len() - 1]);
13064        kept.join("\n")
13065    } else {
13066        lines.join("\n")
13067    };
13068    Some(BranchFacts { commits, stat })
13069}
13070
13071/// Defang what would break the surrounding markdown: a closing `</details>`
13072/// and a code fence.
13073fn markdown_safe(text: &str) -> String {
13074    text.replace("</details>", "&lt;/details&gt;")
13075        .replace("\x60\x60\x60", "~~~")
13076}
13077
13078fn neutral_title(state: &RunState, winner: char) -> String {
13079    format!(
13080        "chore: land candidate {} of run {}",
13081        winner.to_ascii_uppercase(),
13082        state.id
13083    )
13084}
13085
13086/// Reuse the graph's bounded fixer without starting another graph or driver.
13087/// Copy the working state back even on errors so spent rounds remain visible.
13088pub(crate) async fn repair_landing_gate(
13089    state: &mut RunState,
13090    winner: &Candidate,
13091    outcomes: &[CommandOutcome],
13092) -> Result<GateFix> {
13093    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13094        return Ok(GateFix::Stop);
13095    }
13096    let mut runner = Runner {
13097        roles: state.config.resolve_roles()?,
13098        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13099        state: state.clone(),
13100        pause: Pause::new(),
13101        interrupt: Pause::new(),
13102    };
13103    let result = runner.gate_fix_round(winner, outcomes).await;
13104    *state = runner.state;
13105    result
13106}
13107
13108/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13109/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13110pub(crate) async fn verify_current_head(
13111    state: &mut RunState,
13112    winner: &Candidate,
13113    wait: &crate::repo_lock::WaitPolicy,
13114) -> Result<bool> {
13115    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13116    // Preserve the previous record before replacing it, including on crash recovery.
13117    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13118        state
13119            .verification_history
13120            .push(crate::run::VerificationEvidence {
13121                superseded_by: Some(head.clone()),
13122                archived_at: Some(Timestamp::now()),
13123                fixes_spent: Some(state.gate_fixes.len()),
13124                gate_head: None,
13125                gate_ran: false,
13126                gate: Vec::new(),
13127                e2e: state.head_e2e.take(),
13128            });
13129    }
13130    if let Some(e) = &state.head_e2e
13131        && e.head == head
13132    {
13133        if e.passed {
13134            return Ok(true);
13135        }
13136        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13137            state.status = RunStatus::Blocked;
13138            state.save()?;
13139            return Ok(false);
13140        }
13141    } else if state.reviews.last().is_some_and(|r| {
13142        r.verified_head.as_deref() == Some(head.as_str())
13143            && (r.e2e_status() == E2eStatus::Passed
13144                || (r.e2e_status() == E2eStatus::NotConfigured
13145                    && state.config.verify.e2e.is_empty()))
13146    }) || state
13147        .gate_repair_e2e
13148        .as_ref()
13149        .is_some_and(|e| e.head == head && e.passed)
13150    {
13151        return Ok(true);
13152    }
13153    if let Some(e) = &state.gate_repair_e2e
13154        && e.head == head
13155        && !e.passed
13156        && !e.outcomes.is_empty()
13157        && !verify_inconclusive(&e.outcomes)
13158    {
13159        state.status = RunStatus::Blocked;
13160        state.save()?;
13161        return Ok(false);
13162    }
13163    state.head_e2e = Some(crate::run::GateRepairE2e {
13164        head: head.clone(),
13165        passed: false,
13166        outcomes: Vec::new(),
13167    });
13168    state.save()?;
13169    let commands = state.config.verify.e2e.clone();
13170    let shell = state.config.shell();
13171    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13172    let cache_dir = state.config.cache_dir();
13173    let outcomes = if commands.is_empty() {
13174        Vec::new()
13175    } else {
13176        let (outcomes, _) = with_cache_lease(
13177            state,
13178            cache_dir.as_deref(),
13179            "e2e",
13180            "e2e",
13181            &winner.worktree,
13182            &head,
13183            timeout,
13184            "current head e2e",
13185            wait,
13186            |state, budget| async move {
13187                run_e2e_with_retry(
13188                    state,
13189                    &shell,
13190                    &commands,
13191                    &winner.worktree,
13192                    budget,
13193                    "current head e2e",
13194                    None,
13195                )
13196                .await
13197            },
13198        )
13199        .await?;
13200        outcomes
13201    };
13202    let unresolved = verify_inconclusive(&outcomes);
13203    let passed = !unresolved
13204        && outcomes.iter().all(CommandOutcome::ok)
13205        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13206    if !outcomes.is_empty() && !unresolved {
13207        state.record_base_progress(&head);
13208    }
13209    state.head_e2e = Some(crate::run::GateRepairE2e {
13210        head: head.clone(),
13211        passed,
13212        outcomes,
13213    });
13214    if !passed && !unresolved {
13215        let detail = state
13216            .head_e2e
13217            .as_ref()
13218            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13219            .map(|d| format!(" ({d})"))
13220            .unwrap_or_default();
13221        state.status = RunStatus::Blocked;
13222        state.event(
13223            "e2e",
13224            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13225        );
13226    }
13227    state.save()?;
13228    Ok(passed)
13229}
13230
13231/// Recheck a repair's e2e requirement across failures, resource deferrals and
13232/// process interruptions. A successful result only applies to its exact SHA.
13233pub(crate) async fn check_gate_repair_e2e(
13234    state: &mut RunState,
13235    winner: &Candidate,
13236    wait: &crate::repo_lock::WaitPolicy,
13237) -> Result<GateFix> {
13238    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13239        return Ok(GateFix::Retry);
13240    }
13241    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13242    if let Some(record) = &state.gate_repair_e2e
13243        && record.head == head
13244    {
13245        if record.passed {
13246            return Ok(GateFix::Retry);
13247        }
13248        if !record.outcomes.is_empty()
13249            && record.outcomes.iter().all(|o| {
13250                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13251            })
13252        {
13253            return Ok(GateFix::Stop);
13254        }
13255    }
13256    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13257        head: head.clone(),
13258        passed: false,
13259        outcomes: Vec::new(),
13260    });
13261    state.save()?;
13262    let commands = state.config.verify.e2e.clone();
13263    let outcomes = if commands.is_empty() {
13264        Vec::new()
13265    } else {
13266        let shell = state.config.shell();
13267        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13268        let cache_dir = state.config.cache_dir();
13269        let (outcomes, _) = with_cache_lease(
13270            state,
13271            cache_dir.as_deref(),
13272            "e2e",
13273            "e2e",
13274            &winner.worktree,
13275            &head,
13276            timeout,
13277            "gate repair e2e",
13278            wait,
13279            |state, budget| async move {
13280                run_e2e_with_retry(
13281                    state,
13282                    &shell,
13283                    &commands,
13284                    &winner.worktree,
13285                    budget,
13286                    "gate repair e2e",
13287                    None,
13288                )
13289                .await
13290            },
13291        )
13292        .await?;
13293        outcomes
13294    };
13295    let deferred = verify_inconclusive(&outcomes);
13296    let passed = outcomes.iter().all(CommandOutcome::ok)
13297        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13298    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13299        head,
13300        passed,
13301        outcomes,
13302    });
13303    state.save()?;
13304    if deferred {
13305        Ok(GateFix::Defer)
13306    } else if !passed {
13307        let detail = state
13308            .gate_repair_e2e
13309            .as_ref()
13310            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13311            .map(|d| format!(" ({d})"))
13312            .unwrap_or_default();
13313        state.event(
13314            "gate",
13315            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13316        );
13317        Ok(GateFix::Stop)
13318    } else {
13319        Ok(GateFix::Retry)
13320    }
13321}
13322
13323/// Run the same configured gate for a landing head and a fresh graph.
13324pub(crate) async fn run_landing_gate(
13325    state: &mut RunState,
13326    winner: &Candidate,
13327    wait: &crate::repo_lock::WaitPolicy,
13328) -> Result<Vec<CommandOutcome>> {
13329    let shell = state.config.shell();
13330    let gate_commands = state.config.verify.gate.clone();
13331    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13332    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13333        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13334        Vec::new()
13335    } else {
13336        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13337        let cache_dir = state.config.cache_dir();
13338        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13339        let (outcomes, _) = with_cache_lease(
13340            state,
13341            cache_dir.as_deref(),
13342            "gate",
13343            "gate",
13344            &winner.worktree,
13345            &head,
13346            timeout,
13347            "final gate",
13348            wait,
13349            |state, budget| {
13350                let shell = shell.clone();
13351                let gate_commands = gate_commands.clone();
13352                let winner = winner.clone();
13353                async move {
13354                    Runner::run_pre_gate(state, &winner).await;
13355                    // Bind command evidence after mechanical fixes, before commands start.
13356                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13357                    let (outcomes, timed_out_pids) = run_commands(
13358                        state,
13359                        "gate",
13360                        "gate",
13361                        0,
13362                        &shell,
13363                        &gate_commands,
13364                        &winner.worktree,
13365                        budget,
13366                    )
13367                    .await;
13368                    (outcomes, false, timed_out_pids)
13369                }
13370            },
13371        )
13372        .await?;
13373        outcomes
13374    };
13375    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13376    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13377        let mut outcomes = outcomes;
13378        outcomes.push(CommandOutcome {
13379            command: "gate head stability".into(), code: None,
13380            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13381            duration_ms: 0, resource_blocked: false,
13382            ..Default::default()
13383        });
13384        return Ok(outcomes);
13385    }
13386    if outcomes.is_empty() {
13387        // Nothing configured to check — distinct from every other
13388        // silence in this run's event log, since an empty `gate` alone
13389        // no longer says whether the gate ran at all (see
13390        // `RunState::gate_ran`'s own doc).
13391        state.event("gate", "no gate commands configured; not tested");
13392    }
13393    for o in &outcomes {
13394        state.event(
13395            "gate",
13396            format!(
13397                "`{}` -> {}",
13398                o.command,
13399                if o.ok() {
13400                    "pass".to_owned()
13401                } else {
13402                    format!(
13403                        "FAIL ({:?})\n{}",
13404                        o.code,
13405                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13406                    )
13407                }
13408            ),
13409        );
13410    }
13411    Ok(outcomes)
13412}
13413
13414/// The pull request title to hand to `land::merge_subject`. A review-only run
13415/// opened by an earlier build titled its pull request with the review prompt;
13416/// that title is dropped (empty, so the fallback applies) rather than landed.
13417/// Any other title, including an operator's rename, passes through untouched,
13418/// and so does every title of a run that implements a task.
13419pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13420    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13421        ""
13422    } else {
13423        pr_title
13424    }
13425}
13426
13427/// What the squash subject falls back to when the pull request title is empty
13428/// or candidate-shaped: for a review-only run the derived title, never the
13429/// review prompt held in `instruction`.
13430pub fn landing_subject_source(state: &RunState) -> String {
13431    if is_review_run(state) {
13432        let winner = state.candidates.first().map_or('A', |c| c.label);
13433        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13434    }
13435    state.instruction.clone()
13436}
13437
13438/// `summary` without its `TITLE:` line, which the pull request title already
13439/// carries.
13440fn summary_without_title(summary: &str) -> String {
13441    let mut lines = summary.trim().lines().peekable();
13442    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13443        lines.next();
13444    }
13445    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13446}
13447
13448/// The pull request title and body for the winning candidate.
13449///
13450/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13451/// the task's own opening line via [`queue::title_from`] when there is none.
13452/// `state.instruction` can open with blank lines (`task_text` only rejects a
13453/// body that is blank *entirely*), which `title_from` skips.
13454///
13455/// Publishing uses an independent description generated from the final diff
13456/// and structured evidence. Internal summaries and reports remain local.
13457/// Non-publishing previews may display the original task and candidate summary.
13458/// The footer retains the run and candidate provenance.
13459#[cfg(test)]
13460fn pr_message(state: &RunState, winner: char) -> PrMessage {
13461    pr_message_with(state, winner, None)
13462}
13463
13464/// [`pr_message`] with what the branch of a review-only run says about itself.
13465/// `facts` is ignored for a run that implements a task.
13466#[cfg(test)]
13467fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13468    let raw = pr_message_raw(
13469        state,
13470        winner,
13471        facts,
13472        crate::pr_outcome::FinalHead::Unreported,
13473        ChangeNote::NotAsked,
13474    );
13475    let id = crate::scrub::Identity::current();
13476    PrMessage {
13477        title: crate::scrub::scrub(&raw.title, &id),
13478        body: crate::scrub::scrub(&raw.body, &id),
13479    }
13480}
13481
13482/// What the public description may say about the change itself.
13483#[derive(Debug, Clone, Copy)]
13484enum ChangeNote<'a> {
13485    /// A local preview or non-publishing merge mode: no public generation needed.
13486    NotAsked,
13487    /// A summary written from the final diff.
13488    Summary(&'a crate::run::ChangeSummary),
13489    /// A summary was asked for and could not be produced; the text says why.
13490    Unavailable(&'a str),
13491}
13492
13493fn pr_message_raw(
13494    state: &RunState,
13495    winner: char,
13496    facts: Option<&BranchFacts>,
13497    head: crate::pr_outcome::FinalHead<'_>,
13498    change: ChangeNote<'_>,
13499) -> PrMessage {
13500    if !matches!(change, ChangeNote::NotAsked) {
13501        let (title, mut body) = match change {
13502            ChangeNote::Summary(c) => (
13503                c.title.clone(),
13504                format!("## Summary\n\n{}\n\n", c.body.trim()),
13505            ),
13506            ChangeNote::Unavailable(why) => (
13507                neutral_title(state, winner),
13508                format!(
13509                    "## 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"
13510                ),
13511            ),
13512            ChangeNote::NotAsked => unreachable!(),
13513        };
13514        body.push_str(&public_pr_evidence(state, head));
13515        body.push_str(&format!(
13516            "\n---\nmagi:run/{} magi:candidate-{}\n",
13517            state.id,
13518            winner.to_ascii_lowercase()
13519        ));
13520        return PrMessage { title, body };
13521    }
13522    pr_preview(state, winner, facts, head)
13523}
13524
13525/// Append public facts from the run records after every prose generation,
13526/// including posting-gate rewrites. The agent cannot drop this provenance.
13527fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13528    let mut body = crate::pr_outcome::review_rounds(state);
13529    body.push_str(&crate::pr_outcome::final_verification(state, head));
13530    let open = state.last_round_findings();
13531    if !open.is_empty() {
13532        body.push_str("## Open review findings\n\n");
13533        for f in open {
13534            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13535        }
13536        body.push('\n');
13537    }
13538    if let Some(c) = state.change_summary.as_ref()
13539        && head == crate::pr_outcome::FinalHead::At(&c.head)
13540    {
13541        body.push_str(&format!(
13542            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13543            c.base, c.head
13544        ));
13545    }
13546    body
13547}
13548
13549/// Local-only preview of the operator's task and candidate summary.
13550fn pr_preview(
13551    state: &RunState,
13552    winner: char,
13553    facts: Option<&BranchFacts>,
13554    head: crate::pr_outcome::FinalHead<'_>,
13555) -> PrMessage {
13556    let summary = state
13557        .candidates
13558        .iter()
13559        .find(|c| c.label == winner)
13560        .map(|c| c.summary.as_str())
13561        .unwrap_or_default();
13562    // The fallback is the operator's own words and may not be English; GitHub
13563    // text always is, so a non-English task gets a neutral title instead.
13564    let review = is_review_run(state);
13565    let title = if review {
13566        facts
13567            .and_then(|f| {
13568                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13569            })
13570            .or_else(|| review_title(state))
13571            .or_else(|| {
13572                state
13573                    .candidates
13574                    .iter()
13575                    .find(|c| c.label == winner)
13576                    .filter(|c| !c.branch.starts_with("magi/"))
13577                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13578            })
13579            .unwrap_or_else(|| neutral_title(state, winner))
13580    } else {
13581        summary_title(summary).unwrap_or_else(|| {
13582            english_title(
13583                &state.instruction,
13584                PR_TITLE_MAX,
13585                state.config.graph.github_english(),
13586            )
13587            .unwrap_or_else(|| neutral_title(state, winner))
13588        })
13589    };
13590
13591    let mut body = String::new();
13592    let what = summary_without_title(summary);
13593    if !what.is_empty() {
13594        body.push_str("## Summary\n\n");
13595        body.push_str(&what);
13596        body.push_str("\n\n");
13597    }
13598
13599    // Review history uses structured facts across all rounds, never reports.
13600    body.push_str(&crate::pr_outcome::review_rounds(state));
13601    body.push_str(&crate::pr_outcome::final_verification(state, head));
13602    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13603
13604    let open = state.open_findings();
13605    if !open.is_empty() {
13606        body.push_str("## Open review findings\n\n");
13607        for f in &open {
13608            body.push_str(&format!(
13609                "- `{}` [{:?}] {}\n",
13610                f.id, f.severity, "Context retained in local review records."
13611            ));
13612        }
13613        body.push('\n');
13614    }
13615
13616    if let Some(fix) = fix
13617        && !fix.rejected.is_empty()
13618    {
13619        body.push_str("## Declined by the fixer\n\n");
13620        for r in &fix.rejected {
13621            body.push_str(&format!(
13622                "- `{}`: {}\n",
13623                r.id, "Reason retained in local review records."
13624            ));
13625        }
13626        body.push('\n');
13627    }
13628
13629    if review {
13630        // The review prompt is not the task; list what the branch carries.
13631        body.push_str("## Commits under review\n\n");
13632        if let Some(facts) = facts {
13633            let mut left = COMMITS_MAX_CHARS;
13634            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13635                let mut entry = format!("- {}\n", markdown_safe(subject));
13636                for l in markdown_safe(text).lines() {
13637                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13638                }
13639                if left == 0 {
13640                    body.push_str(&format!(
13641                        "- ... {} more commit(s)\n",
13642                        facts.commits.len() - i
13643                    ));
13644                    break;
13645                }
13646                if entry.len() > left {
13647                    // Even the first commit is cut: one huge body must not
13648                    // push the whole description past GitHub's limit.
13649                    let mut end = left;
13650                    while !entry.is_char_boundary(end) {
13651                        end -= 1;
13652                    }
13653                    entry.truncate(end);
13654                    entry.push_str("\n  ... (truncated)\n");
13655                    left = 0;
13656                } else {
13657                    left -= entry.len();
13658                }
13659                body.push_str(&entry);
13660            }
13661            if !facts.stat.trim().is_empty() {
13662                body.push_str(&format!(
13663                    "\n## Diff stat\n\n```\n{}\n```\n",
13664                    markdown_safe(facts.stat.trim())
13665                ));
13666            }
13667        } else {
13668            match &state.reviewed_commits {
13669                Some(subjects) => {
13670                    for s in subjects {
13671                        body.push_str(&format!("- {}\n", s.trim()));
13672                    }
13673                }
13674                None => {
13675                    // An older run kept only the prompt, with the commit list
13676                    // after its first paragraph.
13677                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13678                    body.push_str(rest.trim());
13679                    body.push('\n');
13680                }
13681            }
13682        }
13683    } else {
13684        let task = state.instruction.trim();
13685        let task = if task.is_empty() {
13686            "(empty task)"
13687        } else {
13688            task
13689        };
13690        body.push_str(&format!(
13691            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13692            task.replace("</details>", "&lt;/details&gt;")
13693        ));
13694    }
13695
13696    body.push_str(&format!(
13697        "\n---\nmagi:run/{} magi:candidate-{}\n",
13698        state.id,
13699        winner.to_ascii_lowercase()
13700    ));
13701
13702    PrMessage { title, body }
13703}
13704
13705/// Source imports have already been prepared from structured inputs. Legacy
13706/// inferred references must never instruct a seat to reconstruct those imports.
13707fn seeded_instruction(state: &RunState) -> String {
13708    let mut inputs = Vec::new();
13709    if let Some(start) = &state.sources.start_from {
13710        inputs.push(format!(
13711            "Start from `{}` at `{}` (including ancestry).",
13712            start.token, start.sha
13713        ));
13714    }
13715    for pick in &state.sources.pick_commits {
13716        inputs.push(format!(
13717            "Pick `{}` at `{}` (single commit).",
13718            pick.token, pick.sha
13719        ));
13720    }
13721    if inputs.is_empty() {
13722        state.instruction.clone()
13723    } else {
13724        format!(
13725            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13726            state.instruction,
13727            inputs.join("\n")
13728        )
13729    }
13730}
13731
13732/// Does the winner have no commits ahead of the base it would land on?
13733/// Any failure to find out reads as "not empty": the merge then behaves as it
13734/// always did rather than refusing on a guess.
13735async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13736    let base = &state.base_branch;
13737    let mut against = base.clone();
13738    if mode == MergeMode::Pr {
13739        // A pull request lands on the remote's base, never the local branch
13740        // of the same name: if that cannot be read, "not empty" is the safe
13741        // answer.
13742        let remote = &state.config.merge.remote;
13743        let tracking = format!("{remote}/{base}");
13744        let fetched = git::fetch(repo, remote, base).await;
13745        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13746            against = tracking;
13747        } else {
13748            return false;
13749        }
13750    }
13751    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13752}
13753
13754/// Why nothing was opened for an empty winner, with what the task's own
13755/// references resolved to.
13756fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13757    let mut detail = format!(
13758        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13759         nothing to open a pull request for"
13760    );
13761    detail.push_str(
13762        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13763    );
13764    detail
13765}
13766
13767/// What the `Pr` merge does once it knows whether the branch already has an
13768/// open pull request.
13769#[derive(Debug, PartialEq, Eq)]
13770enum PrPlan {
13771    Create,
13772    Adopt { url: String, title: String },
13773    Stop(String),
13774}
13775
13776/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13777/// a failed lookup -> stop with the real reason. Never guesses.
13778fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13779    match found {
13780        Ok(land::OpenPr::None) => PrPlan::Create,
13781        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13782        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13783            "several open pull requests exist for this branch, not picking one: {}",
13784            urls.join(" ")
13785        )),
13786        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13787    }
13788}
13789
13790/// `gh pr create`, returning the PR url.
13791pub(crate) async fn gh_pr_create(
13792    cwd: &Path,
13793    base: &str,
13794    head: &str,
13795    title: &str,
13796    body: &str,
13797) -> Result<String> {
13798    let out = tokio::process::Command::new("gh")
13799        .args([
13800            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13801        ])
13802        .current_dir(cwd)
13803        .quiet()
13804        .stdin(std::process::Stdio::null())
13805        .output()
13806        .await
13807        .context("spawn gh")?;
13808    if out.status.success() {
13809        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13810    } else {
13811        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13812    }
13813}
13814
13815/// Never force deletion of uncommitted work, including unknown legacy trees.
13816async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13817    match std::fs::symlink_metadata(path) {
13818        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13819            // A previous cleanup may have removed the tree before a branch
13820            // deletion or state save failed. Unregister it if still present.
13821            git::worktree_remove_clean(repo, path).await?;
13822            return Ok(());
13823        }
13824        Err(e) => return Err(e.into()),
13825        Ok(_) => {}
13826    }
13827    if !git::is_clean(path).await? {
13828        bail!(
13829            "worktree has uncommitted work; refusing removal: {}",
13830            path.display()
13831        );
13832    }
13833    if !git::worktree_remove_clean(repo, path).await? {
13834        bail!("worktree removal refused: {}", path.display());
13835    }
13836    Ok(())
13837}
13838
13839/// Read seats return replies, not working-tree changes. Only registered,
13840/// detached seats directly inside this run's root may discard those changes.
13841async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13842    if !crate::retention::read_seat(path) || !path.exists() {
13843        return remove_preserved_worktree(&state.repo, path).await;
13844    }
13845    let owned = std::fs::symlink_metadata(path)?.is_dir()
13846        && path.parent().map(Path::canonicalize).transpose()?
13847            == Some(state.worktree_root().canonicalize()?)
13848        && crate::retention::worktrees(state)
13849            .await?
13850            .contains(&path.canonicalize()?);
13851    let common = crate::repo_lock::common_dir(&state.repo).await?;
13852    if !owned
13853        || common.is_none()
13854        || crate::repo_lock::common_dir(path).await? != common
13855        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
13856            .await?
13857            .ok()
13858        || state.candidates.iter().any(|c| c.worktree == path)
13859    {
13860        return remove_preserved_worktree(&state.repo, path).await;
13861    }
13862    let changes = git::status_porcelain(path).await?;
13863    if !git::worktree_remove(&state.repo, path).await? {
13864        bail!(
13865            "read-only seat worktree removal refused: {}",
13866            path.display()
13867        );
13868    }
13869    if !changes.is_empty() {
13870        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
13871        let paths: String = paths.chars().take(1024).collect();
13872        state.event(
13873            "fold",
13874            format!(
13875                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
13876                path.file_name().unwrap_or_default().to_string_lossy(),
13877                changes.lines().count()
13878            ),
13879        );
13880    }
13881    Ok(())
13882}
13883
13884fn fold_target(
13885    home: &Path,
13886    root: &Path,
13887    path: &Path,
13888    isolated: bool,
13889) -> Option<crate::build_target::FoldTarget> {
13890    if !isolated {
13891        return None;
13892    }
13893    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
13894        Ok(target) => target,
13895        Err(error) => {
13896            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
13897            None
13898        }
13899    }
13900}
13901
13902fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
13903    if let Some(target) = target
13904        && let Err(error) = target.reclaim_orphaned_target(home)
13905    {
13906        tracing::warn!(%error, "isolated target retained after fold");
13907    }
13908}
13909
13910/// Tear a run's worktrees and branches down.
13911///
13912/// `home` is where the updated `run.json` is saved (via
13913/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
13914/// a housekeeping pass already has its own honest `home` handed to it, and
13915/// falling through to the global here would write back through whichever
13916/// directory some other process or test pinned into that `OnceLock` first,
13917/// not the one the caller actually resolved its `runs` and `state` from.
13918pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
13919    fold_run_with_policy(state, drop_winner, home, false).await
13920}
13921
13922/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
13923pub async fn fold_run_overriding_recovery_retention(
13924    state: &mut RunState,
13925    drop_winner: bool,
13926    home: &Path,
13927) -> Result<Vec<String>> {
13928    fold_run_with_policy(state, drop_winner, home, true).await
13929}
13930
13931async fn fold_run_with_policy(
13932    state: &mut RunState,
13933    drop_winner: bool,
13934    home: &Path,
13935    override_recovery_retention: bool,
13936) -> Result<Vec<String>> {
13937    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
13938        && !override_recovery_retention
13939    {
13940        bail!("refusing fold: {reason}");
13941    }
13942    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
13943        bail!("candidate preservation incomplete; refusing cleanup");
13944    }
13945    // Serialize ordinary folding with the same starts/resumes as target-only
13946    // eviction. Otherwise a second janitor could remove the whole worktree
13947    // around a live output borrower even though target eviction was fenced.
13948    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
13949    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
13950    // An override must use current durable ownership, not a pre-lock snapshot.
13951    if override_recovery_retention {
13952        *state = RunState::load_under(&state.id, home)?;
13953        anyhow::ensure!(
13954            state.status.done() && !state.status.resumable(),
13955            "recovery retention override requires a finished, non-resumable run"
13956        );
13957        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
13958        anyhow::ensure!(
13959            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
13960            "run is live or its ownership is unknown"
13961        );
13962        anyhow::ensure!(
13963            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
13964            "candidate preservation incomplete; refusing cleanup"
13965        );
13966    }
13967    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
13968    if let Some(reason) = &retention_reason
13969        && !override_recovery_retention
13970    {
13971        bail!("refusing fold: {reason}");
13972    }
13973    let _driver = crate::driver::maintenance(home, &state.id)?;
13974    let mut output_guards = Vec::new();
13975    for entry in std::fs::read_dir(state.worktree_root())
13976        .into_iter()
13977        .flatten()
13978        .flatten()
13979    {
13980        if entry.path().join(".git").is_file() {
13981            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
13982        }
13983    }
13984    let repo = state.repo.clone();
13985    // CLI, Web and automatic cleanup all enter here, independently of
13986    // Runner::fold_losers. Protect deletion and shared config release too.
13987    let wait = repository_wait(state, None);
13988    let _coordination = match coordinate_operation(state, &repo, &wait).await {
13989        Ok(lease) => lease,
13990        Err(e) => {
13991            state.save_under(home)?;
13992            return Err(e);
13993        }
13994    };
13995    // Confirmed merges dispose of their owned sources after durable evidence
13996    // capture. Preflight every source before removing anything.
13997    let _source_outputs = if retention_reason.is_some()
13998        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
13999    {
14000        verify_merged_fold_sources(state, drop_winner, home).await?
14001    } else {
14002        Vec::new()
14003    };
14004    if let Some(reason) = retention_reason {
14005        state.event(
14006            "fold",
14007            format!(
14008                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14009                state.id
14010            ),
14011        );
14012        state.save_under(home)?;
14013    }
14014    let root = state.worktree_root();
14015    let winner = state.tally.as_ref().map(|t| t.winner);
14016    let mut removed = Vec::new();
14017    let isolated = crate::build_target::isolated(&state.config);
14018
14019    for i in 0..state.candidates.len() {
14020        let c = state.candidates[i].clone();
14021        let is_winner = Some(c.label) == winner;
14022        if is_winner && !drop_winner {
14023            continue;
14024        }
14025        let existed = c.worktree.exists();
14026        let target = fold_target(home, &root, &c.worktree, isolated);
14027        // A vanished directory can still have a Git registration that keeps
14028        // its branch checked out. Remove that registration before the branch.
14029        remove_preserved_worktree(&repo, &c.worktree).await?;
14030        reclaim_fold_target(home, target);
14031        if existed {
14032            removed.push(c.worktree.to_string_lossy().into_owned());
14033        }
14034        // A branch handed to a later run (and its pull request) is not this
14035        // run's to delete.
14036        let handed_over = state.released_branches.contains(&c.branch);
14037        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14038            if !git::branch_delete(&repo, &c.branch).await? {
14039                bail!("candidate branch removal refused");
14040            }
14041            removed.push(c.branch.clone());
14042        }
14043        state.candidates[i].folded = true;
14044    }
14045
14046    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14047        let path = name.path();
14048        let keep = !drop_winner
14049            && winner.is_some_and(|w| {
14050                path.file_name()
14051                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14052            });
14053        if keep {
14054            continue;
14055        }
14056        let target = fold_target(home, &root, &path, isolated);
14057        remove_read_seat_worktree(state, &path).await?;
14058        reclaim_fold_target(home, target);
14059        removed.push(path.to_string_lossy().into_owned());
14060    }
14061
14062    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14063    // judge worktrees, so once the loop above has cleared all of them out,
14064    // the parent is a bare directory nobody else was ever going to remove -
14065    // git only ever managed what was inside it. Left alone, one of these
14066    // accumulates per fully-folded run; the operator's own machine had 74.
14067    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14068    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14069    // so does anything a run never claimed that happens to share the bay.
14070    remove_if_empty(&root);
14071
14072    if state.enabled_worktree_config && drop_winner {
14073        // A release, not a raw disable: some sibling run in this repository
14074        // may still hold its own reference (see `git::acquire_worktree_config`),
14075        // and only the last release actually turns the setting back off.
14076        git::release_worktree_config(&repo).await.ok();
14077        state.enabled_worktree_config = false;
14078    }
14079    state.save_under(home)?;
14080    Ok(removed)
14081}
14082
14083async fn verify_merged_fold_sources(
14084    state: &RunState,
14085    drop_winner: bool,
14086    home: &Path,
14087) -> Result<Vec<std::fs::File>> {
14088    let winner = state.tally.as_ref().map(|t| t.winner);
14089    let mut heads = BTreeSet::new();
14090    for candidate in &state.candidates {
14091        if Some(candidate.label) == winner && !drop_winner {
14092            continue;
14093        }
14094        anyhow::ensure!(
14095            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14096            "candidate recovery source is outside the inventoried run root: {}",
14097            candidate.worktree.display()
14098        );
14099        match std::fs::symlink_metadata(&candidate.worktree) {
14100            Ok(_) => {}
14101            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14102            Err(error) => return Err(error.into()),
14103        }
14104        if !state.released_branches.contains(&candidate.branch)
14105            && git::branch_exists(&state.repo, &candidate.branch).await?
14106        {
14107            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14108        }
14109    }
14110    let mut cargo_guards = Vec::new();
14111    let entries = match std::fs::read_dir(state.worktree_root()) {
14112        Ok(entries) => Some(entries),
14113        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14114        Err(error) => return Err(error.into()),
14115    };
14116    for entry in entries.into_iter().flatten() {
14117        let path = entry?.path();
14118        let metadata = std::fs::symlink_metadata(&path)?;
14119        anyhow::ensure!(
14120            metadata.is_dir() && !metadata.file_type().is_symlink(),
14121            "non-directory or symlink recovery source retained: {}",
14122            path.display()
14123        );
14124        if !drop_winner
14125            && winner.is_some_and(|w| {
14126                path.file_name()
14127                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14128            })
14129        {
14130            continue;
14131        }
14132        anyhow::ensure!(
14133            path.join(".git").is_file(),
14134            "unregistered recovery source retained: {}",
14135            path.display()
14136        );
14137        anyhow::ensure!(
14138            git::git(
14139                &path,
14140                &[
14141                    "status",
14142                    "--porcelain",
14143                    "--untracked-files=all",
14144                    "--ignored",
14145                    "--",
14146                    ".",
14147                    ":(exclude)target"
14148                ]
14149            )
14150            .await?
14151            .is_empty(),
14152            "source changes or ignored recovery files retained: {}",
14153            path.display()
14154        );
14155        match std::fs::symlink_metadata(path.join("target")) {
14156            Ok(_) => {
14157                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14158            }
14159            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14160            Err(error) => return Err(error.into()),
14161        }
14162        for checkpoint in [
14163            "rebase-merge",
14164            "rebase-apply",
14165            "sequencer",
14166            "CHERRY_PICK_HEAD",
14167            "MERGE_HEAD",
14168            "REBASE_HEAD",
14169            "REVERT_HEAD",
14170            "BISECT_LOG",
14171            "AUTO_MERGE",
14172            "MERGE_MSG",
14173        ] {
14174            let location = git::git(
14175                &path,
14176                &[
14177                    "rev-parse",
14178                    "--path-format=absolute",
14179                    "--git-path",
14180                    checkpoint,
14181                ],
14182            )
14183            .await?;
14184            anyhow::ensure!(
14185                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14186                if e.kind() == std::io::ErrorKind::NotFound),
14187                "Git recovery checkpoint retained: {checkpoint}"
14188            );
14189        }
14190        heads.insert(git::rev_parse(&path, "HEAD").await?);
14191    }
14192    crate::fold_evidence::preserve(state, home, &heads).await?;
14193
14194    Ok(cargo_guards)
14195}
14196
14197/// Remove `dir` if it exists and has nothing in it.
14198///
14199/// Best-effort and silent by design: a directory that is not empty (a run
14200/// whose winner is still parked there, a stray file some other process left)
14201/// is exactly the case this must refuse, and a directory that is already gone
14202/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14203/// already refuses a non-empty directory, so the emptiness check below is
14204/// belt, not suspenders - it is what keeps this from ever attempting the
14205/// removal in the case that matters, rather than trusting `remove_dir`'s
14206/// error path to have no side effects if it ever changed.
14207fn remove_if_empty(dir: &Path) {
14208    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14209        std::fs::remove_dir(dir).ok();
14210    }
14211}
14212
14213/// Severity of the worst open finding in the last review round, for reporting.
14214pub fn worst_open(state: &RunState) -> Option<Severity> {
14215    state
14216        .reviews
14217        .last()?
14218        .reviews
14219        .iter()
14220        .flat_map(|r| r.findings.iter())
14221        .map(|f| f.severity)
14222        .max()
14223}
14224
14225/// `[worktree] setup` hides its products per worktree, which needs
14226/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14227/// worktrees, like the hook's; every place that runs setup calls this first.
14228async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14229    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14230        git::acquire_worktree_config(repo).await?;
14231        state.enabled_worktree_config = true;
14232    }
14233    Ok(())
14234}
14235
14236#[cfg(test)]
14237mod tests {
14238    #[tokio::test]
14239    async fn launcher_base_fetch_requires_remote_success() {
14240        let tmp = tempfile::tempdir().unwrap();
14241        let repo = tmp.path().join("repo");
14242        let remote = tmp.path().join("remote");
14243        std::fs::create_dir(&repo).unwrap();
14244        std::fs::create_dir(&remote).unwrap();
14245        git::git(&remote, &["init", "--bare", "-b", "main"])
14246            .await
14247            .unwrap();
14248        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14249        git::git(
14250            &repo,
14251            &[
14252                "-c",
14253                "user.name=Fixture",
14254                "-c",
14255                "user.email=fixture@example.invalid",
14256                "commit",
14257                "--allow-empty",
14258                "-m",
14259                "fixture",
14260            ],
14261        )
14262        .await
14263        .unwrap();
14264        git::git(
14265            &repo,
14266            &["remote", "add", "origin", remote.to_str().unwrap()],
14267        )
14268        .await
14269        .unwrap();
14270        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14271        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14272        assert_eq!(
14273            resolve_base(&repo, "main", "origin", None)
14274                .await
14275                .unwrap()
14276                .commit,
14277            head
14278        );
14279        #[cfg(unix)]
14280        {
14281            let policy: crate::config::Coordination = toml::from_str(
14282                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14283            ).unwrap();
14284            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14285            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14286            let held = crate::repo_lock::SeatLease::operation_with(
14287                &repo,
14288                Some(&policy),
14289                &crate::repo_lock::WaitPolicy::default(),
14290            )
14291            .await
14292            .unwrap();
14293            assert!(held.is_some());
14294            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14295            tokio::pin!(fetch);
14296            assert!(
14297                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14298                    .await
14299                    .is_err()
14300            );
14301            assert!(
14302                !repo.join(".git/FETCH_HEAD").exists(),
14303                "no fetch before admission"
14304            );
14305            drop(held);
14306            let fetched = fetch.await.unwrap();
14307            assert_eq!(fetched.commit, head);
14308            assert_eq!(fetched.remote, "origin");
14309            assert_eq!(fetched.branch, "main");
14310        }
14311        // A surviving tracking ref is not successful fetch evidence.
14312        git::git(
14313            &repo,
14314            &[
14315                "remote",
14316                "set-url",
14317                "origin",
14318                tmp.path().join("missing").to_str().unwrap(),
14319            ],
14320        )
14321        .await
14322        .unwrap();
14323        let error = resolve_base(&repo, "main", "origin", None)
14324            .await
14325            .unwrap_err()
14326            .to_string();
14327        assert!(error.contains("cannot read origin/main"));
14328        assert!(error.contains("refusing to branch off"));
14329    }
14330
14331    #[test]
14332    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14333        let leaked = vec!["chore(deps): update a crate".to_owned()];
14334        let own = "fix(daemon): apply a chosen action";
14335        assert!(should_retitle("", own, &leaked));
14336        assert!(should_retitle(
14337            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14338            own,
14339            &leaked
14340        ));
14341        assert!(should_retitle(
14342            "chore: land candidate A of run 1",
14343            own,
14344            &leaked
14345        ));
14346        assert!(should_retitle(
14347            "magi: candidate A (uncommitted work)",
14348            own,
14349            &leaked
14350        ));
14351        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14352        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14353        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14354    }
14355
14356    #[test]
14357    fn pr_merge_plan_creates_adopts_or_stops() {
14358        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14359        assert_eq!(
14360            pr_merge_plan(Ok(land::OpenPr::One {
14361                url: "u".into(),
14362                title: "t".into()
14363            })),
14364            PrPlan::Adopt {
14365                url: "u".into(),
14366                title: "t".into()
14367            }
14368        );
14369        let PrPlan::Stop(many) =
14370            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14371        else {
14372            panic!("many must stop");
14373        };
14374        assert!(many.contains('a') && many.contains('b'));
14375        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14376            panic!("a failed lookup must stop");
14377        };
14378        assert!(err.contains("bad token"));
14379    }
14380
14381    use super::*;
14382    use crate::run::GateStatus;
14383    use std::collections::BTreeMap;
14384    use std::time::Duration;
14385
14386    fn conductor() -> AgentSpec {
14387        AgentSpec {
14388            id: "conductor".to_owned(),
14389            kind: crate::config::AgentKind::Command,
14390            model: None,
14391            command: vec!["true".to_owned()],
14392            extra_args: Vec::new(),
14393            env: BTreeMap::new(),
14394            prompt_delivery: None,
14395            max_turn_secs: None,
14396        }
14397    }
14398
14399    fn spec(id: &str) -> AgentSpec {
14400        AgentSpec {
14401            id: id.to_owned(),
14402            kind: crate::config::AgentKind::Command,
14403            model: None,
14404            command: vec!["true".to_owned()],
14405            extra_args: Vec::new(),
14406            env: BTreeMap::new(),
14407            prompt_delivery: None,
14408            max_turn_secs: None,
14409        }
14410    }
14411
14412    fn ids(xs: &[&str]) -> BTreeSet<String> {
14413        xs.iter().map(|s| (*s).to_owned()).collect()
14414    }
14415
14416    #[test]
14417    fn pick_successor_skips_an_agent_another_seat_holds() {
14418        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14419        let roster = [spec("a"), spec("b"), spec("c")];
14420        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14421        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14422    }
14423
14424    #[test]
14425    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14426        // The other seat started on c but was handed to d; c is free again.
14427        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14428        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14429        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14430        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14431        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14432    }
14433
14434    #[test]
14435    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14436        let roster = [spec("a"), spec("b")];
14437        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14438        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14439        let carried = ids(&["b"]);
14440        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14441        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14442    }
14443
14444    #[test]
14445    fn pick_successor_returns_none_without_any_untried_successor() {
14446        let roster = [spec("a"), spec("b")];
14447        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14448        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14449        let carried = ids(&["a"]);
14450        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14451    }
14452
14453    #[test]
14454    fn pick_successor_rescue_avoids_another_seats_occupant() {
14455        // b is a carried failure and free; a is held by the other seat.
14456        let roster = [spec("a"), spec("b"), spec("c")];
14457        let carried = ids(&["b", "c"]);
14458        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14459        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14460    }
14461
14462    #[test]
14463    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14464        let roster = [spec("a"), spec("b"), spec("c")];
14465        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14466        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14467    }
14468
14469    #[test]
14470    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14471        let roster = [spec("a"), spec("b"), spec("c")];
14472        let failed = ids(&["a", "b", "c"]);
14473        // Rescue looks at the whole roster, once per id, then runs out.
14474        let mut tried = ids(&["b"]);
14475        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14476        assert_eq!(first.id, "a");
14477        tried.insert(first.id.clone());
14478        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14479        assert_eq!(second.id, "c");
14480        tried.insert(second.id.clone());
14481        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14482    }
14483
14484    #[test]
14485    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14486        let roster = [spec("a"), spec("b")];
14487        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14488        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14489    }
14490
14491    #[test]
14492    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14493        let roster = [spec("a"), spec("b"), spec("c")];
14494        let h = SeatHistory {
14495            failed: ids(&["a"]),
14496            last_ok: Some("b".to_owned()),
14497            last_fail: None,
14498        };
14499        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14500        // A last answerer that left the roster, or later failed, is ignored.
14501        let gone = SeatHistory {
14502            last_ok: Some("zzz".to_owned()),
14503            ..h.clone()
14504        };
14505        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14506        let failed = SeatHistory {
14507            failed: ids(&["a", "b"]),
14508            last_ok: Some("b".to_owned()),
14509            last_fail: None,
14510        };
14511        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14512    }
14513
14514    #[test]
14515    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14516        let first = SeatState::new("review-1", "alpha", 7);
14517        let next = handover_seat("review-1", "gamma", 7);
14518        assert_ne!(first.claude_session, next.claude_session);
14519    }
14520
14521    #[test]
14522    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14523        let mut state = state_with_summary("x", "y");
14524        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14525        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14526        assert_ne!(a.claude_session, b.claude_session);
14527    }
14528
14529    #[test]
14530    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14531        let roster = [spec("a"), spec("b")];
14532        let h = SeatHistory {
14533            failed: ids(&["a", "b"]),
14534            ..SeatHistory::default()
14535        };
14536        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14537        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14538        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14539    }
14540
14541    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14542    // fallback loop depends on to terminate: it must walk forward from the
14543    // seat's own position, never restart at the front of the roster, and it
14544    // must never hand back an id already tried, however many times that id
14545    // happens to appear.
14546
14547    #[test]
14548    fn failure_signature_ignores_numbers_and_paths() {
14549        assert_eq!(
14550            failure_signature("exited with Some(2) and no usable output"),
14551            failure_signature("exited with Some(137) and no usable output")
14552        );
14553        assert_eq!(
14554            failure_signature("process exited with no usable output (exit code 2)"),
14555            failure_signature("process exited with no usable output (exit code 137)")
14556        );
14557        for (old, new) in [
14558            (
14559                "exited with Some(2) and no usable output",
14560                "process exited with no usable output (exit code 2)",
14561            ),
14562            (
14563                "exited with None and no usable output",
14564                "process exited with no usable output (exit code unavailable)",
14565            ),
14566        ] {
14567            let previous = FailClass::Other(failure_signature(old));
14568            let current = FailClass::Other(failure_signature(new));
14569            assert_eq!(previous, current, "resumption retains the failure class");
14570            assert!(!should_hand_over(Some(&previous), &current));
14571        }
14572        assert_eq!(
14573            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14574            failure_signature("cannot open /var/x.txt: denied")
14575        );
14576        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14577    }
14578
14579    #[test]
14580    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14581        let other = FailClass::Other("x".into());
14582        assert!(should_hand_over(None, &FailClass::Quota));
14583        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14584        assert!(should_hand_over(
14585            Some(&FailClass::Timeout),
14586            &FailClass::Timeout
14587        ));
14588        assert!(should_hand_over(None, &other));
14589        assert!(!should_hand_over(Some(&other), &other));
14590        assert!(should_hand_over(
14591            Some(&other),
14592            &FailClass::Other("y".into())
14593        ));
14594        // A quota or timeout in between ends the run of identical failures.
14595        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14596        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14597    }
14598
14599    #[test]
14600    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14601        let a = SeatState::new("judge-1", "alpha", 7);
14602        let b = handover_seat("judge-1", "beta", 7);
14603        assert_ne!(a.claude_session, b.claude_session);
14604        assert_eq!(b.turns, 0);
14605    }
14606
14607    #[test]
14608    fn a_timeout_is_classified_apart_from_other_failures() {
14609        assert_eq!(
14610            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14611            Some(FailClass::Timeout)
14612        );
14613        assert!(matches!(
14614            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14615            Some(FailClass::Other(_))
14616        ));
14617    }
14618
14619    #[test]
14620    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14621        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14622        let tried = BTreeSet::from(["beta".to_owned()]);
14623        // beta sits at index 1; the next candidate is gamma, never alpha —
14624        // which is very likely a different candidate slot's own agent.
14625        let next = next_untried_in_roster(&roster, 1, &tried);
14626        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14627    }
14628
14629    #[test]
14630    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14631        let roster = vec![spec("alpha"), spec("beta")];
14632        let tried = BTreeSet::from(["beta".to_owned()]);
14633        // beta is the roster's last entry: nothing follows it, and alpha —
14634        // earlier in the roster, almost certainly a different candidate
14635        // slot's own agent — must not be reached by wrapping back to it.
14636        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14637    }
14638
14639    #[test]
14640    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14641        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14642        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14643        // beta (index 1) and gamma (index 2, the only entry after it) have
14644        // both been tried; alpha (index 0) never has, but it comes before
14645        // beta's own position, so there is nothing further for this seat.
14646        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14647    }
14648
14649    #[test]
14650    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14651        let roster = vec![spec("a"), spec("a"), spec("b")];
14652        let tried = BTreeSet::from(["a".to_owned()]);
14653        let next = next_untried_in_roster(&roster, 0, &tried);
14654        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14655    }
14656
14657    #[test]
14658    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14659        let roster = vec![spec("a"), spec("b")];
14660        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14661        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14662    }
14663
14664    #[test]
14665    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14666        let dir = tempfile::tempdir().unwrap();
14667        let bay = dir.path().join("ffff");
14668
14669        // Not there yet: nothing to do, nothing to panic on.
14670        remove_if_empty(&bay);
14671        assert!(!bay.exists());
14672
14673        // Something still inside - the winner's worktree, or a stray file -
14674        // keeps the directory standing.
14675        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14676        remove_if_empty(&bay);
14677        assert!(bay.exists(), "non-empty directory must survive");
14678
14679        // Once the last entry is gone, so is the directory itself.
14680        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14681        remove_if_empty(&bay);
14682        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14683    }
14684
14685    // `round_is_clean` is the exact decision this task fixed: a round with a
14686    // seat that never answered must not read the same as a round every seat
14687    // actually reviewed. These are deterministic and process-free by design —
14688    // the equivalent end-to-end check (a real reviewer timing out under a
14689    // live graph run) is a genuine race against wall-clock contention, and a
14690    // spawn slow enough to blow even a generous budget under a loaded test
14691    // run must not turn this specific regression check flaky.
14692
14693    #[test]
14694    fn a_full_panel_that_found_nothing_is_clean() {
14695        assert!(round_is_clean(
14696            0,
14697            true,
14698            2,
14699            2,
14700            0,
14701            IncompleteReviewPolicy::Block
14702        ));
14703    }
14704
14705    #[test]
14706    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14707        assert!(!round_is_clean(
14708            0,
14709            true,
14710            1,
14711            2,
14712            0,
14713            IncompleteReviewPolicy::Block
14714        ));
14715    }
14716
14717    #[test]
14718    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14719        assert!(!round_is_clean(
14720            1,
14721            true,
14722            1,
14723            2,
14724            0,
14725            IncompleteReviewPolicy::Warn
14726        ));
14727    }
14728
14729    #[test]
14730    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14731        assert!(round_is_clean(
14732            0,
14733            true,
14734            1,
14735            2,
14736            0,
14737            IncompleteReviewPolicy::Warn
14738        ));
14739    }
14740
14741    #[test]
14742    fn a_full_panel_with_an_open_finding_is_not_clean() {
14743        assert!(!round_is_clean(
14744            1,
14745            true,
14746            2,
14747            2,
14748            0,
14749            IncompleteReviewPolicy::Block
14750        ));
14751    }
14752
14753    #[test]
14754    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14755        assert!(!round_is_clean(
14756            0,
14757            false,
14758            2,
14759            2,
14760            0,
14761            IncompleteReviewPolicy::Block
14762        ));
14763    }
14764
14765    // The stall this task closes: under the default `block` policy, a seat
14766    // missing only because it was rate limited must not force a wait for a
14767    // session limit that will not lift by the next round. `round_is_clean`
14768    // is where that quorum carve-out lives; the review loop around it never
14769    // changes what a reviewer's vote or a finding's severity means.
14770
14771    #[test]
14772    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14773        // 1 of 2 answered, and the one missing was quota'd — the exact
14774        // "review-2 rate limited (quota)" shape from the field report.
14775        assert!(round_is_clean(
14776            0,
14777            true,
14778            1,
14779            2,
14780            1,
14781            IncompleteReviewPolicy::Block
14782        ));
14783    }
14784
14785    #[test]
14786    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14787        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14788        // not a quota loss (`quota_missing` stays 0) — worth another try.
14789        assert!(!round_is_clean(
14790            0,
14791            true,
14792            1,
14793            2,
14794            0,
14795            IncompleteReviewPolicy::Block
14796        ));
14797    }
14798
14799    #[test]
14800    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14801        assert!(!round_is_clean(
14802            1,
14803            true,
14804            1,
14805            2,
14806            1,
14807            IncompleteReviewPolicy::Block
14808        ));
14809        assert!(!round_is_clean(
14810            0,
14811            false,
14812            1,
14813            2,
14814            1,
14815            IncompleteReviewPolicy::Block
14816        ));
14817    }
14818
14819    #[test]
14820    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14821        // Every seat quota'd, nobody answered: there is no panel to decide
14822        // on, so this must fall through to the existing block-and-retry
14823        // fallback rather than call an unreviewed patch clean.
14824        assert!(!round_is_clean(
14825            0,
14826            true,
14827            0,
14828            2,
14829            2,
14830            IncompleteReviewPolicy::Block
14831        ));
14832    }
14833
14834    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14835        CommandOutcome {
14836            command: "test".to_owned(),
14837            code,
14838            output_tail: String::new(),
14839            duration_ms: 0,
14840            resource_blocked,
14841            ..Default::default()
14842        }
14843    }
14844
14845    #[cfg(unix)]
14846    #[tokio::test]
14847    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
14848        ask_test_home();
14849        let temp = tempfile::tempdir().unwrap();
14850        let mut runner = runner_at(RunStatus::Gating);
14851        let shell = vec!["sh".to_owned(), "-c".to_owned()];
14852        let commands = vec![
14853            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
14854            "touch must-not-run".to_owned(),
14855        ];
14856        let (outcomes, retried, pids) = run_e2e_with_retry(
14857            &mut runner.state,
14858            &shell,
14859            &commands,
14860            temp.path(),
14861            Duration::from_secs(5),
14862            "fixture",
14863            None,
14864        )
14865        .await;
14866        assert_eq!(outcomes.len(), 1);
14867        assert!(outcomes[0].resource_blocked);
14868        assert!(!outcomes[0].build_failed());
14869        assert!(!retried);
14870        assert!(pids.is_empty());
14871        assert!(!temp.path().join("must-not-run").exists());
14872        assert_eq!(
14873            runner.state.resource_block.as_ref().unwrap().kind,
14874            "incremental cache admission"
14875        );
14876    }
14877
14878    #[test]
14879    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
14880        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
14881        assert!(
14882            !verify_inconclusive(&[outcome(Some(1), false)]),
14883            "an ordinary failure is still evidence about the patch"
14884        );
14885        assert!(verify_inconclusive(&[outcome(None, true)]));
14886        assert!(
14887            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
14888            "one inconclusive outcome taints the whole batch"
14889        );
14890        assert!(!verify_inconclusive(&[]));
14891    }
14892
14893    #[tokio::test]
14894    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
14895        // Alive for the first two checks, then dead - confirms the loop
14896        // actually re-polls rather than deciding once and sleeping out the
14897        // ceiling regardless.
14898        let calls = std::sync::atomic::AtomicUsize::new(0);
14899        let started = Instant::now();
14900        wait_for_pids_with(
14901            &[123],
14902            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
14903            Duration::from_millis(5),
14904            Duration::from_secs(5),
14905        )
14906        .await;
14907        assert!(
14908            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
14909            "must keep checking rather than deciding on the first answer"
14910        );
14911        assert!(
14912            started.elapsed() < Duration::from_secs(1),
14913            "must return the moment it is confirmed dead, not wait out the ceiling"
14914        );
14915    }
14916
14917    #[tokio::test]
14918    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
14919        let started = Instant::now();
14920        wait_for_pids_with(
14921            &[123],
14922            |_| true, // never reports dead
14923            Duration::from_millis(5),
14924            Duration::from_millis(30),
14925        )
14926        .await;
14927        let elapsed = started.elapsed();
14928        assert!(
14929            elapsed >= Duration::from_millis(30),
14930            "must not give up before its own ceiling: {elapsed:?}"
14931        );
14932        assert!(
14933            elapsed < Duration::from_secs(1),
14934            "must not wait past its own ceiling either: {elapsed:?}"
14935        );
14936    }
14937
14938    #[tokio::test]
14939    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
14940        let started = Instant::now();
14941        wait_for_pids_with(
14942            &[],
14943            |_| true,
14944            Duration::from_secs(5),
14945            Duration::from_secs(5),
14946        )
14947        .await;
14948        assert!(
14949            started.elapsed() < Duration::from_millis(200),
14950            "an empty pid list has nothing to confirm"
14951        );
14952    }
14953
14954    // `review_conclusion` is the exact decision the review hand-off task
14955    // fixed: a round budget spent (or a tree that stopped moving) must not
14956    // collapse into `Blocked` regardless of what verification actually
14957    // said. Deterministic and process-free for the same reason the
14958    // `round_is_clean` family above is.
14959    fn review_round(
14960        clean: bool,
14961        blocking: usize,
14962        answered: usize,
14963        expected: usize,
14964        progressed: bool,
14965        e2e_ok: bool,
14966    ) -> ReviewRound {
14967        ReviewRound {
14968            round: 1,
14969            head: "h".to_owned(),
14970            verified_head: None,
14971            verified_at: None,
14972            reviews: Vec::new(),
14973            e2e: vec![CommandOutcome {
14974                command: "test".to_owned(),
14975                code: Some(if e2e_ok { 0 } else { 1 }),
14976                output_tail: String::new(),
14977                duration_ms: 0,
14978                resource_blocked: false,
14979                ..Default::default()
14980            }],
14981            verify_retried: false,
14982            e2e_deferred: false,
14983            e2e_defer_reason: None,
14984            fix: None,
14985            blocking,
14986            answered,
14987            expected,
14988            clean,
14989            progressed,
14990            vote_split: false,
14991            reconsideration: Vec::new(),
14992            verdict: None,
14993        }
14994    }
14995
14996    #[test]
14997    fn review_conclusion_is_none_when_nothing_has_run() {
14998        assert_eq!(review_conclusion(&[], 3), None);
14999    }
15000
15001    #[test]
15002    fn review_conclusion_is_none_while_rounds_remain() {
15003        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15004        assert_eq!(review_conclusion(&rounds, 3), None);
15005    }
15006
15007    #[test]
15008    fn review_conclusion_is_gating_once_a_round_is_clean() {
15009        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15010        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15011    }
15012
15013    #[test]
15014    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15015        let rounds = vec![
15016            review_round(false, 1, 2, 2, true, true),
15017            review_round(false, 1, 2, 2, true, true),
15018        ];
15019        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15020    }
15021
15022    #[test]
15023    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15024        let rounds = vec![
15025            review_round(false, 1, 2, 2, true, true),
15026            review_round(false, 1, 2, 2, true, false),
15027        ];
15028        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15029    }
15030
15031    #[test]
15032    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15033        // Magi never got a command to run against this round's own head — a
15034        // resource-blocked attempt, not a red one — so this must never
15035        // settle on `Blocked` the way a genuine e2e failure would. `None`
15036        // here is what tells `Runner::review_loop` to retry the check
15037        // itself rather than trust this cheap recomputation with a verdict
15038        // it cannot actually produce.
15039        let mut blocked = review_round(false, 1, 2, 2, true, false);
15040        blocked.e2e[0].resource_blocked = true;
15041        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15042        assert_eq!(review_conclusion(&rounds, 2), None);
15043    }
15044
15045    #[test]
15046    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15047        // Missing input, not a verified tree — never a hand-off candidate.
15048        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15049        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15050    }
15051
15052    #[test]
15053    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15054        let rounds = vec![
15055            review_round(false, 1, 2, 2, false, true),
15056            review_round(false, 1, 2, 2, false, true),
15057        ];
15058        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15059    }
15060
15061    fn secs(n: u64) -> Duration {
15062        Duration::from_secs(n)
15063    }
15064
15065    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15066    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15067    #[tokio::test]
15068    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15069        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15070        if std::env::var_os(CHILD).is_none() {
15071            // Other tests reconcile every run in the process-global home,
15072            // briefly taking owner locks. This ancestry test expects an idle
15073            // predecessor, so give it its own process and pinned test home.
15074            let output = std::process::Command::new(std::env::current_exe().unwrap())
15075                .args([
15076                    "--exact",
15077                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15078                    "--nocapture",
15079                ])
15080                .env(CHILD, "1")
15081                .env_remove("MAGI_WORKER_HOME")
15082                .env_remove("MAGI_WORKER_ID")
15083                .output()
15084                .unwrap();
15085            assert!(
15086                output.status.success()
15087                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15088                "{}\n{}",
15089                String::from_utf8_lossy(&output.stdout),
15090                String::from_utf8_lossy(&output.stderr)
15091            );
15092            return;
15093        }
15094        ask_test_home();
15095        let tmp = tempfile::tempdir().unwrap();
15096        let repo = tmp.path().join("repo");
15097        std::fs::create_dir_all(&repo).unwrap();
15098        init_repo(&repo);
15099        let g = |args: &[&str]| {
15100            let out = std::process::Command::new("git")
15101                .args(args)
15102                .current_dir(&repo)
15103                .quiet()
15104                .output()
15105                .unwrap();
15106            assert!(
15107                out.status.success(),
15108                "{}",
15109                String::from_utf8_lossy(&out.stderr)
15110            );
15111        };
15112        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15113        g(&["checkout", "-b", "historical"]);
15114        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15115        g(&["add", "."]);
15116        g(&["commit", "-m", "old alternative"]);
15117        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15118        g(&["checkout", "-b", "magi/task-selected", &base]);
15119        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15120        g(&["add", "."]);
15121        g(&["commit", "-m", "measurement infrastructure"]);
15122        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15123        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15124        g(&["add", "."]);
15125        g(&["commit", "-m", "dependent implementation"]);
15126        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15127        g(&["checkout", "main"]);
15128        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15129        g(&["add", "."]);
15130        g(&["commit", "-m", "unrelated base change"]);
15131        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15132        let origin = tmp.path().join("origin.git");
15133        g(&[
15134            "clone",
15135            "--bare",
15136            repo.to_str().unwrap(),
15137            origin.to_str().unwrap(),
15138        ]);
15139        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15140        g(&["fetch", "origin"]);
15141        let selection = crate::pr_recovery::Selection {
15142            url: "https://example.test/project/pull/1".into(),
15143            branch: "magi/task-selected".into(),
15144            head: head.clone(),
15145            source_head: None,
15146            source_run: None,
15147            source_proof: None,
15148            disposition: Some(crate::pr_recovery::Disposition::Review),
15149            instruction: "preserve measured behavior".into(),
15150            approved_at: jiff::Timestamp::now(),
15151        };
15152        let mut template = runner_at(RunStatus::Reviewing);
15153        template.state.repo = repo.clone();
15154        template.state.base_commit = current.clone();
15155        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15156        template.state.origin = Some(crate::run::Origin::queue("selected"));
15157        template.state.pr_head = Some(selection.branch.clone());
15158        template.state.pr_recovery = Some(selection.clone());
15159        let mut runner =
15160            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15161                .await
15162                .unwrap();
15163        let wt = runner.state.winner().unwrap().worktree.clone();
15164        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15165        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15166        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15167        assert!(runner.state.seeds.is_empty());
15168        assert_eq!(runner.state.instruction, "preserve measured behavior");
15169        runner.sync_to_base().await.unwrap();
15170        assert_eq!(
15171            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15172            "prerequisite"
15173        );
15174        assert_eq!(
15175            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15176            "measured implementation"
15177        );
15178        assert_eq!(
15179            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15180            "current main change"
15181        );
15182        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15183        assert_eq!(
15184            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15185            head
15186        );
15187
15188        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15189        let mut partial = runner_at(RunStatus::Reviewing);
15190        partial.state.repo = repo.clone();
15191        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15192        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15193            run: Some("exit 1".into()),
15194            ..Default::default()
15195        }];
15196        let selection = runner.state.pr_recovery.clone().unwrap();
15197        partial.state.pr_recovery = Some(selection.clone());
15198        partial.state.pr_head = Some(selection.branch.clone());
15199        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15200        let id = partial.state.id.clone();
15201        let error = match Runner::open_selected(
15202            &repo,
15203            partial.state,
15204            partial.roles,
15205            1,
15206            runner.state.base_commit.clone(),
15207            selection,
15208        )
15209        .await
15210        {
15211            Ok(_) => panic!("setup must fail"),
15212            Err(e) => e,
15213        };
15214        assert_eq!(
15215            error
15216                .downcast_ref::<crate::run::StartupFailure>()
15217                .unwrap()
15218                .run,
15219            id
15220        );
15221        let failed = RunState::load(&id).unwrap();
15222        assert_eq!(failed.status, RunStatus::Failed);
15223        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15224        assert!(Runner::resume(&id).is_err());
15225        runner.state.status = RunStatus::Ready;
15226        runner.state.driver_exited = true;
15227        runner.state.save().unwrap();
15228        let mut retry = runner_at(RunStatus::Reviewing);
15229        retry.state.repo = repo.clone();
15230        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15231        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15232        reselected.approved_at = jiff::Timestamp::now();
15233        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15234        retry.state.pr_head = Some(reselected.branch.clone());
15235        retry.state.pr_recovery = Some(reselected.clone());
15236        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15237            .await
15238            .unwrap();
15239        let restarted = Runner::open_selected(
15240            &repo,
15241            retry.state,
15242            retry.roles,
15243            1,
15244            runner.state.base_commit.clone(),
15245            reselected,
15246        )
15247        .await
15248        .unwrap();
15249        assert_eq!(
15250            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15251                .await
15252                .unwrap(),
15253            head
15254        );
15255        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15256        assert_eq!(
15257            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15258            head
15259        );
15260    }
15261
15262    #[tokio::test]
15263    #[cfg(unix)]
15264    async fn fallback_and_interrupted_restoration_require_coordination() {
15265        use std::os::fd::AsRawFd as _;
15266        ask_test_home();
15267        let tmp = tempfile::tempdir().unwrap();
15268        let mut runner = registered_runner(tmp.path()).await;
15269        runner.state.config.graph.timeout_resource_wait = 1;
15270        let winner = runner.state.candidates[0].clone();
15271        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15272        let leftover = winner.worktree.join("leftover");
15273        std::fs::write(&leftover, "untrusted edits").unwrap();
15274        let next = tmp.path().join("next-fixer");
15275        let mut failed = spec("first");
15276        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15277        let mut successor = spec("second");
15278        successor.command = vec![
15279            "sh".into(),
15280            "-c".into(),
15281            format!("touch '{}'; echo done", next.display()),
15282        ];
15283        let attempts = vec![
15284            (failed.clone(), "first".into()),
15285            (successor.clone(), "second".into()),
15286        ];
15287        let lock_path = runner.state.repo.join(".git/updater.lock");
15288        let external = std::fs::File::create(&lock_path).unwrap();
15289        assert_eq!(
15290            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15291            0
15292        );
15293        let artifacts = tmp.path().join("artifacts");
15294        let build = |spec, seat| SeatJob {
15295            spec,
15296            seat,
15297            cwd: winner.worktree.clone(),
15298            prompt: "fixture".into(),
15299            timeout: Duration::from_secs(10),
15300            allow_write: true,
15301            sessions: false,
15302            artifacts: artifacts.clone(),
15303            stem: "fix".into(),
15304            handover: None,
15305        };
15306        let (_, _, out) = runner
15307            .ask_fixer_among(
15308                attempts.clone(),
15309                "graft",
15310                None,
15311                Some((&winner.worktree, &head)),
15312                build,
15313            )
15314            .await;
15315        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15316        assert!(leftover.exists(), "contention must prevent clean");
15317        assert!(!next.exists());
15318        assert!(runner.state.handovers.is_empty());
15319        // Early interrupted-repair rollback uses the same protected route.
15320        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15321            from_run: "earlier".into(),
15322            generation: 1,
15323            mode: crate::recovery::Mode::VerifyRepair,
15324            reasons: Vec::new(),
15325            reviewed_head: None,
15326            rounds: Vec::new(),
15327            open_findings: Vec::new(),
15328            evidence: None,
15329            criteria_inherited: true,
15330            repair: crate::recovery::Repair::Started {
15331                before: head.clone(),
15332            },
15333        });
15334        assert!(
15335            runner
15336                .recovery_repair(&winner)
15337                .await
15338                .unwrap_err()
15339                .is::<crate::repo_lock::ResourceBlocked>()
15340        );
15341        assert!(matches!(
15342            runner.state.recovery.as_ref().unwrap().repair,
15343            crate::recovery::Repair::Started { .. }
15344        ));
15345        assert!(leftover.exists());
15346        drop(external);
15347        runner.recovery_repair(&winner).await.unwrap();
15348        assert!(!leftover.exists());
15349        assert!(matches!(
15350            runner.state.recovery.as_ref().unwrap().repair,
15351            crate::recovery::Repair::Done { .. }
15352        ));
15353        // A hard lock-open failure also leaves HEAD and untracked work intact.
15354        std::fs::remove_file(&lock_path).unwrap();
15355        std::fs::create_dir(&lock_path).unwrap();
15356        std::fs::write(&leftover, "untrusted edits").unwrap();
15357        let (_, _, out) = runner
15358            .ask_fixer_among(
15359                attempts,
15360                "graft",
15361                None,
15362                Some((&winner.worktree, &head)),
15363                build,
15364            )
15365            .await;
15366        assert!(matches!(out, AgentOutcome::Failed(_)));
15367        assert!(leftover.exists());
15368        assert!(!next.exists());
15369        assert_eq!(
15370            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15371            head
15372        );
15373    }
15374
15375    #[cfg(unix)]
15376    async fn registered_runner(root: &Path) -> Runner {
15377        repository_runner(root, crate::config::test_coordination()).await
15378    }
15379
15380    async fn repository_runner(
15381        root: &Path,
15382        coordination: Option<crate::config::Coordination>,
15383    ) -> Runner {
15384        ask_test_home();
15385        let repo = root.join("repo");
15386        std::fs::create_dir_all(&repo).unwrap();
15387        init_repo(&repo);
15388        if coordination.is_some() {
15389            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15390        }
15391        let mut runner = runner_at(RunStatus::Prep);
15392        runner.state.repo = repo.clone();
15393        runner.state.config.coordination = coordination;
15394        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15395        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15396        runner.state.config.graph.advise = false;
15397        runner.roles.implementers = vec![spec("implement")];
15398        runner.roles.judges = vec![spec("judge")];
15399        runner.prep().await.unwrap();
15400        runner
15401    }
15402
15403    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15404
15405    #[tokio::test]
15406    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15407        let tmp = tempfile::tempdir().unwrap();
15408        let mut runner = repository_runner(tmp.path(), None).await;
15409        let prompts = runner.state.config.prompts.clone();
15410        let run = runner.state.id.clone();
15411        let ctx = WaveCtx {
15412            carry_seats: false,
15413            pauses: None,
15414            run: &run,
15415            node: "advise",
15416            prompts: &prompts,
15417            cache: None,
15418            round: None,
15419        };
15420        let jobs: Vec<_> = ["alpha", "beta"]
15421            .into_iter()
15422            .map(|id| SeatJob {
15423                spec: scripted(id, AUTH_OUTAGE),
15424                seat: SeatState::new(id, id, 7),
15425                prompt: "propose".into(),
15426                cwd: runner.state.candidates[0].worktree.clone(),
15427                timeout: Duration::from_secs(10),
15428                allow_write: false,
15429                sessions: false,
15430                artifacts: agent::artifacts_dir(&runner.state.dir()),
15431                stem: id.into(),
15432                handover: None,
15433            })
15434            .collect();
15435        let mut losses = Vec::new();
15436        let results = ask_wave_with(
15437            jobs.clone(),
15438            runner.sem.clone(),
15439            2,
15440            &[],
15441            &ctx,
15442            &mut losses,
15443            &mut runner.state,
15444            &|_: &str| Ok(()),
15445        )
15446        .await;
15447        assert!(
15448            results
15449                .iter()
15450                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15451        );
15452        assert_eq!(runner.state.quota.len(), 2);
15453        assert!(
15454            runner
15455                .state
15456                .quota
15457                .iter()
15458                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15459        );
15460        assert!(!runner.state.advise_attempted);
15461        runner.stop_for_resource().unwrap();
15462        assert_eq!(runner.state.status, RunStatus::Blocked);
15463        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15464        assert_eq!(
15465            runner.state.resource_block.as_ref().unwrap().kind,
15466            "agent authentication"
15467        );
15468        // A machine loss followed by an ordinary failure is not evidence
15469        // that the whole node was unavailable, and must not earn a refund.
15470        runner.state.resource_block = None;
15471        runner.state.quota.clear();
15472        let mut mixed = jobs;
15473        mixed[1].spec.command = vec!["false".into()];
15474        let results = ask_wave_with(
15475            mixed,
15476            runner.sem.clone(),
15477            0,
15478            &[],
15479            &ctx,
15480            &mut losses,
15481            &mut runner.state,
15482            &|_: &str| Ok(()),
15483        )
15484        .await;
15485        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15486        assert!(runner.state.resource_block.is_none());
15487        assert_eq!(losses.len(), 1);
15488    }
15489
15490    #[tokio::test]
15491    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15492        let tmp = tempfile::tempdir().unwrap();
15493        let mut runner = repository_runner(tmp.path(), None).await;
15494        let implementer = scripted("implement", AUTH_OUTAGE);
15495        runner.roles.implementers = vec![implementer.clone()];
15496        runner.state.config.agents = vec![implementer];
15497        runner.implement().await.unwrap();
15498        assert_eq!(runner.state.status, RunStatus::Blocked);
15499        assert_eq!(runner.state.quota.len(), 1);
15500        assert_eq!(
15501            runner.state.quota[0].cause,
15502            agent::QuotaCause::Authentication
15503        );
15504        let candidate = &runner.state.candidates[0];
15505        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15506        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15507    }
15508
15509    #[tokio::test]
15510    #[cfg(unix)]
15511    async fn parked_implementer_persists_completed_work() {
15512        for registered in [false, true] {
15513            let tmp = tempfile::tempdir().unwrap();
15514            let mut runner = registered_runner(tmp.path()).await;
15515            if !registered {
15516                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15517            }
15518            let marker = tmp.path().join("started");
15519            let release = tmp.path().join("release");
15520            let mut implementer = spec("implement");
15521            implementer.command = vec![
15522                "sh".into(),
15523                "-c".into(),
15524                format!(
15525                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15526                    marker.display(),
15527                    release.display()
15528                ),
15529            ];
15530            runner.roles.implementers = vec![implementer.clone()];
15531            runner.state.config.agents = vec![implementer];
15532            let pause = runner.pause.clone();
15533            let (result, ()) = tokio::join!(runner.implement(), async {
15534                tokio::time::timeout(Duration::from_secs(10), async {
15535                    while !marker.exists() {
15536                        tokio::time::sleep(Duration::from_millis(10)).await;
15537                    }
15538                })
15539                .await
15540                .unwrap();
15541                pause.park();
15542                std::fs::write(&release, "go").unwrap();
15543            });
15544            result.unwrap();
15545            let candidate = &runner.state.candidates[0];
15546            assert!(candidate.commits > 0, "{candidate:?}");
15547            assert!(candidate.summary.contains("saved-result"));
15548            assert_eq!(candidate.files, 1);
15549            let before = candidate.commits;
15550            runner.implement().await.unwrap();
15551            assert_eq!(runner.state.candidates[0].commits, before);
15552        }
15553    }
15554
15555    #[tokio::test]
15556    #[cfg(unix)]
15557    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15558        let tmp = tempfile::tempdir().unwrap();
15559        let mut runner = registered_runner(tmp.path()).await;
15560        let winner = runner.state.candidates[0].clone();
15561        let cache = tmp.path().join("cache");
15562        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15563        runner.state.config.graph.timeout_resource_wait = 0;
15564        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15565        let crate::cache::AcquireOutcome::Acquired(held) =
15566            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15567        else {
15568            panic!("cache must be free")
15569        };
15570        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15571            from_run: "earlier".into(),
15572            generation: 1,
15573            mode: crate::recovery::Mode::VerifyRepair,
15574            reasons: Vec::new(),
15575            reviewed_head: None,
15576            rounds: Vec::new(),
15577            open_findings: Vec::new(),
15578            evidence: None,
15579            criteria_inherited: true,
15580            repair: crate::recovery::Repair::NotStarted,
15581        });
15582        runner.recovery_repair(&winner).await.unwrap();
15583        assert!(matches!(
15584            runner.state.recovery.as_ref().unwrap().repair,
15585            crate::recovery::Repair::WaitingForRestore { .. }
15586        ));
15587        drop(held);
15588        runner.state.resource_block = None;
15589        runner.state.config.graph.timeout_resource_wait = 1;
15590        runner.recovery_repair(&winner).await.unwrap();
15591        assert!(matches!(
15592            runner.state.recovery.as_ref().unwrap().repair,
15593            crate::recovery::Repair::Done { .. }
15594        ));
15595        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15596    }
15597
15598    #[tokio::test]
15599    #[cfg(unix)]
15600    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15601        use std::os::fd::AsRawFd as _;
15602        for graft in [false, true] {
15603            let tmp = tempfile::tempdir().unwrap();
15604            let mut runner = registered_runner(tmp.path()).await;
15605            runner.state.config.graph.timeout_resource_wait = 1;
15606            let winner = runner.state.candidates[0].clone();
15607            let marker = tmp.path().join("fixer-started");
15608            let mut fixer = spec("fixer");
15609            fixer.command = vec![
15610                "sh".into(),
15611                "-c".into(),
15612                format!("echo started >> '{}'; echo done", marker.display()),
15613            ];
15614            runner.roles.fixer = Some(vec![fixer]);
15615            if graft {
15616                let mut loser = winner.clone();
15617                loser.label = 'B';
15618                loser.index = 1;
15619                runner.state.candidates.push(loser);
15620                runner.state.config.graph.graft_runner_up = true;
15621                runner.state.tally = Some(Tally {
15622                    first_choice: BTreeMap::new(),
15623                    borda: BTreeMap::new(),
15624                    winner: winner.label,
15625                    rankings: 1,
15626                    unanimous_initial: true,
15627                    deliberated: false,
15628                    changed_votes: 0,
15629                    unanimous_final: true,
15630                    tie_break: None,
15631                    judges: 1,
15632                    present: 1,
15633                    quorum: 1,
15634                    met_quorum: true,
15635                    uncontested: None,
15636                });
15637                runner.state.judgements.push(crate::run::Judgement {
15638                    judge: 1,
15639                    seat: "judge-1".into(),
15640                    agent: "judge".into(),
15641                    ranking: vec![winner.label, 'B'],
15642                    reasons: BTreeMap::new(),
15643                    confidence: None,
15644                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15645                    order: vec![0, 1],
15646                    failed: None,
15647                    duration_ms: 0,
15648                });
15649            } else {
15650                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15651                    from_run: "earlier".into(),
15652                    generation: 1,
15653                    mode: crate::recovery::Mode::VerifyRepair,
15654                    reasons: Vec::new(),
15655                    reviewed_head: None,
15656                    rounds: Vec::new(),
15657                    open_findings: Vec::new(),
15658                    evidence: None,
15659                    criteria_inherited: true,
15660                    repair: crate::recovery::Repair::NotStarted,
15661                });
15662            }
15663            let reader = crate::repo_lock::SeatLease::for_checkout(
15664                &winner.worktree,
15665                false,
15666                crate::config::test_coordination().as_ref(),
15667            )
15668            .await
15669            .unwrap();
15670            let pause = runner.pause.clone();
15671            let (result, ()) = tokio::join!(
15672                async {
15673                    if graft {
15674                        runner.graft().await
15675                    } else {
15676                        runner.recovery_repair(&winner).await
15677                    }
15678                },
15679                async {
15680                    tokio::time::sleep(Duration::from_millis(100)).await;
15681                    pause.park();
15682                }
15683            );
15684            result.unwrap();
15685            assert!(!marker.exists(), "a blocked seat must not spawn");
15686            // Exercise the persisted state, as a binary replacement/resume does.
15687            runner.state = RunState::load(&runner.state.id).unwrap();
15688            if graft {
15689                assert_eq!(
15690                    runner.state.graft.as_ref().unwrap().outcome,
15691                    GraftOutcome::WaitingForRestore
15692                );
15693            } else {
15694                assert!(matches!(
15695                    runner.state.recovery.as_ref().unwrap().repair,
15696                    crate::recovery::Repair::WaitingForRestore { .. }
15697                ));
15698            }
15699            drop(reader);
15700            runner.pause = Pause::new();
15701            runner.state.resource_block = None;
15702            // Deferred restoration must still respect an external lock owner.
15703            let external =
15704                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15705            assert_eq!(
15706                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15707                0
15708            );
15709            let leftover = winner.worktree.join("leftover");
15710            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15711            let result = if graft {
15712                runner.graft().await
15713            } else {
15714                runner.recovery_repair(&winner).await
15715            };
15716            assert!(
15717                result
15718                    .unwrap_err()
15719                    .is::<crate::repo_lock::ResourceBlocked>()
15720            );
15721            assert!(leftover.exists());
15722            assert!(!marker.exists());
15723            drop(external);
15724            runner.state.resource_block = None;
15725            let result = if graft {
15726                runner.graft().await
15727            } else {
15728                runner.recovery_repair(&winner).await
15729            };
15730            result.unwrap();
15731            assert!(!leftover.exists(), "restore must precede retry");
15732            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15733            if graft {
15734                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15735            } else {
15736                assert!(matches!(
15737                    runner.state.recovery.as_ref().unwrap().repair,
15738                    crate::recovery::Repair::Done { .. }
15739                ));
15740            }
15741        }
15742    }
15743
15744    #[tokio::test]
15745    #[cfg(unix)]
15746    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15747        use std::os::fd::AsRawFd as _;
15748        let tmp = tempfile::tempdir().unwrap();
15749        let mut runner = registered_runner(tmp.path()).await;
15750        runner.state.config.graph.timeout_resource_wait = 1;
15751        let winner = runner.state.candidates[0].clone();
15752        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15753        runner.state.tally = Some(Tally {
15754            first_choice: BTreeMap::new(),
15755            borda: BTreeMap::new(),
15756            winner: winner.label,
15757            rankings: 0,
15758            unanimous_initial: false,
15759            deliberated: false,
15760            changed_votes: 0,
15761            unanimous_final: false,
15762            tie_break: None,
15763            judges: 0,
15764            present: 0,
15765            quorum: 0,
15766            met_quorum: true,
15767            uncontested: Some("fixture".into()),
15768        });
15769        runner.state.graft = Some(GraftRecord {
15770            pre: pre.clone(),
15771            post: None,
15772            lines: None,
15773            limit: None,
15774            agent: None,
15775            outcome: GraftOutcome::Running,
15776            requested: Vec::new(),
15777            adoption: None,
15778            adoption_error: None,
15779        });
15780        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15781        git::commit_all(&winner.worktree, "unfinished graft")
15782            .await
15783            .unwrap();
15784        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15785        let leftover = winner.worktree.join("leftover");
15786        std::fs::write(&leftover, "untrusted edits").unwrap();
15787        let path = runner.state.repo.join(".git/updater.lock");
15788        let external = std::fs::File::create(&path).unwrap();
15789        assert_eq!(
15790            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15791            0
15792        );
15793        assert!(
15794            runner
15795                .graft()
15796                .await
15797                .unwrap_err()
15798                .is::<crate::repo_lock::ResourceBlocked>()
15799        );
15800        assert!(matches!(
15801            runner.state.graft.as_ref().unwrap().outcome,
15802            GraftOutcome::Running
15803        ));
15804        assert_eq!(
15805            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15806            unfinished
15807        );
15808        assert!(leftover.exists());
15809        drop(external);
15810        std::fs::remove_file(&path).unwrap();
15811        std::fs::create_dir(&path).unwrap();
15812        assert!(runner.graft().await.is_err());
15813        assert!(matches!(
15814            runner.state.graft.as_ref().unwrap().outcome,
15815            GraftOutcome::Running
15816        ));
15817        assert_eq!(
15818            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15819            unfinished
15820        );
15821        assert!(leftover.exists());
15822        std::fs::remove_dir(&path).unwrap();
15823        runner.graft().await.unwrap();
15824        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15825        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15826        assert!(!leftover.exists());
15827    }
15828
15829    #[tokio::test]
15830    #[cfg(unix)]
15831    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15832        use std::os::fd::AsRawFd as _;
15833        let tmp = tempfile::tempdir().unwrap();
15834        let mut runner = registered_runner(tmp.path()).await;
15835        runner.state.prep_complete = Some(false);
15836        runner.state.config.graph.timeout_resource_wait = 1;
15837        runner.state.save().unwrap();
15838        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15839        assert_eq!(
15840            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15841            0
15842        );
15843        runner.execute().await.unwrap();
15844        let disk = RunState::load(&runner.state.id).unwrap();
15845        assert!(disk.driver_exited);
15846        assert_eq!(disk.driver_pid, None);
15847        assert_eq!(runner.state.status, RunStatus::Blocked);
15848        assert_eq!(
15849            runner.state.resource_block.as_ref().unwrap().kind,
15850            "repository coordination"
15851        );
15852        assert!(runner.state.prep_failure.is_none());
15853        assert!(runner.state.seats.is_empty());
15854        runner.pause.park();
15855        // Include headroom for Git subprocesses under parallel test load;
15856        // the repository contention deadline itself remains one second.
15857        tokio::time::timeout(Duration::from_secs(10), runner.execute())
15858            .await
15859            .unwrap()
15860            .unwrap();
15861        assert!(runner.state.parked);
15862        assert!(runner.state.prep_failure.is_none());
15863        let disk = RunState::load(&runner.state.id).unwrap();
15864        assert!(disk.driver_exited);
15865        assert_eq!(disk.driver_pid, None);
15866    }
15867
15868    #[tokio::test]
15869    #[cfg(unix)]
15870    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
15871        use std::os::fd::AsRawFd as _;
15872        let tmp = tempfile::tempdir().unwrap();
15873        let mut runner = registered_runner(tmp.path()).await;
15874        runner.state.prep_complete = Some(false);
15875        runner.state.config.graph.timeout_resource_wait = 30;
15876        runner.state.save().unwrap();
15877        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15878        assert_eq!(
15879            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15880            0
15881        );
15882        assert!(
15883            tokio::time::timeout(Duration::from_millis(100), runner.execute())
15884                .await
15885                .is_err()
15886        );
15887        let disk = RunState::load(&runner.state.id).unwrap();
15888        assert!(disk.driver_exited);
15889        assert_eq!(disk.driver_pid, None);
15890        assert!(disk.status.resumable());
15891        assert!(runner.state.driver_exited);
15892        assert_eq!(runner.state.driver_pid, None);
15893        runner.state.save().unwrap();
15894        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
15895    }
15896
15897    #[tokio::test]
15898    #[cfg(unix)]
15899    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
15900        let tmp = tempfile::tempdir().unwrap();
15901        let mut runner = registered_runner(tmp.path()).await;
15902        let winner = runner.state.candidates[0].clone();
15903        let cache = tmp.path().join("cache");
15904        let started = tmp.path().join("pre-gate-started");
15905        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
15906        runner.state.config.verify.gate =
15907            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
15908        let home = crate::run::home();
15909        let owner =
15910            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
15911        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
15912            crate::cache::AcquireOutcome::Acquired(g) => g,
15913            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
15914        };
15915        let mut gate = Box::pin(runner.run_gate(&winner));
15916        assert!(
15917            tokio::time::timeout(Duration::from_millis(150), &mut gate)
15918                .await
15919                .is_err()
15920        );
15921        assert!(!started.exists(), "pre-gate must wait for the cache too");
15922        // Simulate the wave that already owns the cache entering invoke.
15923        // It must obtain the editor reservation and finish without waiting
15924        // for the gate that is queued behind its cache.
15925        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
15926        let editor = crate::repo_lock::SeatLease::checkout_with(
15927            &winner.worktree,
15928            true,
15929            crate::config::test_coordination().as_ref(),
15930            &wait,
15931        )
15932        .await
15933        .unwrap();
15934        drop(editor);
15935        guard.release();
15936        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15937            .await
15938            .unwrap()
15939            .unwrap();
15940        drop(gate);
15941        assert!(outcomes.iter().all(CommandOutcome::ok));
15942        assert!(started.exists());
15943    }
15944
15945    #[tokio::test]
15946    #[cfg(unix)]
15947    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
15948        use std::os::fd::AsRawFd as _;
15949
15950        ask_test_home();
15951        let tmp = tempfile::tempdir().unwrap();
15952        let repo = tmp.path().join("repo");
15953        std::fs::create_dir_all(&repo).unwrap();
15954        init_repo(&repo);
15955        let common = repo.join(".git");
15956        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
15957        let mut runner = runner_at(RunStatus::Prep);
15958        runner.state.repo = repo.clone();
15959        runner.state.config.coordination = crate::config::test_coordination();
15960        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15961        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
15962        runner.state.config.graph.advise = false;
15963        runner.roles.implementers = vec![spec("implement")];
15964        runner.roles.judges = vec![spec("judge")];
15965        runner.prep().await.unwrap();
15966        let winner = runner.state.candidates[0].clone();
15967        // Emulate edits already left by a completed seat. The fixture CLI
15968        // only reports completion; it performs no repository operations.
15969        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
15970        let completed = tmp.path().join("seat-completed");
15971        runner.roles.implementers[0].command = vec![
15972            "sh".into(),
15973            "-c".into(),
15974            format!("touch '{}'; echo completed", completed.display()),
15975        ];
15976        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
15977        assert_eq!(
15978            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15979            0
15980        );
15981        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15982        let mut implement = Box::pin(runner.implement());
15983        tokio::select! {
15984            result = &mut implement => panic!("rescue must wait: {result:?}"),
15985            result = tokio::time::timeout(Duration::from_secs(10), async {
15986                while !completed.exists() {
15987                    tokio::time::sleep(Duration::from_millis(20)).await;
15988                }
15989            }) => result.unwrap(),
15990        }
15991        assert!(
15992            tokio::time::timeout(Duration::from_millis(200), &mut implement)
15993                .await
15994                .is_err()
15995        );
15996        assert_eq!(
15997            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15998            before
15999        );
16000        assert_eq!(
16001            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16002            0
16003        );
16004        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16005            .await
16006            .unwrap()
16007            .unwrap();
16008        drop(implement);
16009        assert_ne!(
16010            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16011            before
16012        );
16013        assert!(git::is_clean(&winner.worktree).await.unwrap());
16014
16015        let started = tmp.path().join("pre-gate-started");
16016        let proceed = tmp.path().join("pre-gate-proceed");
16017        let checked = tmp.path().join("gate-ran");
16018        runner.state.config.verify.pre_gate = vec![format!(
16019            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16020            started.display(),
16021            proceed.display()
16022        )];
16023        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16024        assert_eq!(
16025            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16026            0
16027        );
16028        let mut gate = Box::pin(runner.run_gate(&winner));
16029        assert!(
16030            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16031                .await
16032                .is_err()
16033        );
16034        assert!(!started.exists());
16035        assert!(!checked.exists());
16036        assert!(git::is_clean(&winner.worktree).await.unwrap());
16037        assert_eq!(
16038            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16039            0
16040        );
16041        tokio::select! {
16042            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16043            result = tokio::time::timeout(Duration::from_secs(10), async {
16044                while !started.exists() {
16045                    tokio::time::sleep(Duration::from_millis(20)).await;
16046                }
16047            }) => result.unwrap(),
16048        }
16049        assert_eq!(
16050            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16051            -1,
16052            "mechanical edits must hold the real lock"
16053        );
16054        std::fs::write(proceed, "ready").unwrap();
16055        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16056            .await
16057            .unwrap()
16058            .unwrap();
16059        drop(gate);
16060        assert!(outcomes.iter().all(CommandOutcome::ok));
16061        assert!(checked.exists());
16062        assert!(runner.state.pre_gate_commit.is_some());
16063        assert!(git::is_clean(&winner.worktree).await.unwrap());
16064        assert_eq!(
16065            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16066            0,
16067            "gate completion must release coordination"
16068        );
16069        drop(outsider);
16070        std::fs::remove_file(common.join("updater.lock")).unwrap();
16071        std::fs::create_dir(common.join("updater.lock")).unwrap();
16072        std::fs::remove_file(&started).unwrap();
16073        std::fs::remove_file(&checked).unwrap();
16074        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16075        let error = runner.run_gate(&winner).await.unwrap_err();
16076        assert!(
16077            error
16078                .to_string()
16079                .contains("acquire mandatory repository lock")
16080        );
16081        assert!(
16082            !started.exists(),
16083            "failed acquisition must prevent pre-gate"
16084        );
16085        assert!(!checked.exists(), "failed acquisition must prevent gate");
16086        assert!(git::is_clean(&winner.worktree).await.unwrap());
16087        assert_eq!(
16088            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16089            head
16090        );
16091    }
16092
16093    #[tokio::test]
16094    #[cfg(unix)]
16095    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16096        use std::os::fd::AsRawFd as _;
16097        use std::time::Duration;
16098
16099        ask_test_home();
16100        let tmp = tempfile::tempdir().unwrap();
16101        let repo = tmp.path().join("repo");
16102        std::fs::create_dir_all(&repo).unwrap();
16103        init_repo(&repo);
16104        let common = repo.join(".git");
16105        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16106        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16107        assert_eq!(
16108            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16109            0
16110        );
16111        let mut runner = runner_at(RunStatus::Prep);
16112        runner.state.repo = repo.clone();
16113        runner.state.config.coordination = crate::config::test_coordination();
16114        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16115        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16116        runner.state.config.graph.advise = true;
16117        runner.state.config.graph.advisors = 1;
16118        runner.roles.implementers = vec![spec("implement")];
16119        runner.roles.judges = vec![spec("judge")];
16120        let root = runner.state.worktree_root();
16121        let started = tmp.path().join("setup-started");
16122        let proceed = tmp.path().join("setup-proceed");
16123        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16124            run: Some(format!(
16125                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16126                started.display(),
16127                proceed.display()
16128            )),
16129            ..Default::default()
16130        }];
16131        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16132        let config = git::git(&repo, &["config", "--local", "--list"])
16133            .await
16134            .unwrap();
16135        let mut prep = Box::pin(runner.prep());
16136        assert!(
16137            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16138                .await
16139                .is_err()
16140        );
16141        assert!(
16142            !root.exists(),
16143            "contention must prevent even checkout creation"
16144        );
16145        assert!(!started.exists(), "contention must prevent setup");
16146        assert_eq!(
16147            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16148            branches
16149        );
16150        assert_eq!(
16151            git::git(&repo, &["config", "--local", "--list"])
16152                .await
16153                .unwrap(),
16154            config
16155        );
16156        drop(lock);
16157        tokio::select! {
16158            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16159            result = tokio::time::timeout(Duration::from_secs(10), async {
16160                while !started.exists() {
16161                    tokio::time::sleep(Duration::from_millis(20)).await;
16162                }
16163            }) => result.unwrap(),
16164        }
16165        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16166        assert_eq!(
16167            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16168            -1
16169        );
16170        assert!(
16171            tokio::time::timeout(
16172                Duration::from_millis(100),
16173                crate::repo_lock::SeatLease::for_checkout(
16174                    &repo,
16175                    true,
16176                    crate::config::test_coordination().as_ref()
16177                )
16178            )
16179            .await
16180            .is_err(),
16181            "preparation must also exclude local editors"
16182        );
16183        std::fs::write(proceed, "ready").unwrap();
16184        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16185            .await
16186            .unwrap()
16187            .unwrap();
16188        drop(prep);
16189        assert_eq!(runner.state.prep_complete, Some(true));
16190        assert!(root.join("judge-1").exists());
16191        assert!(root.join("advisor-1").exists());
16192        assert_eq!(
16193            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16194            0
16195        );
16196    }
16197
16198    #[tokio::test]
16199    #[cfg(unix)]
16200    async fn preparation_lock_failure_prevents_repository_changes() {
16201        ask_test_home();
16202        let tmp = tempfile::tempdir().unwrap();
16203        let repo = tmp.path().join("repo");
16204        std::fs::create_dir_all(&repo).unwrap();
16205        init_repo(&repo);
16206        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16207        // A directory at the required lock path makes opening the real lock
16208        // fail, rather than merely exercising an invalid registration.
16209        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16210        let mut runner = runner_at(RunStatus::Prep);
16211        runner.state.repo = repo.clone();
16212        runner.state.config.coordination = crate::config::test_coordination();
16213        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16214        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16215        runner.roles.implementers = vec![spec("implement")];
16216        let error = runner.prep().await.unwrap_err();
16217        assert!(
16218            error
16219                .to_string()
16220                .contains("acquire mandatory repository lock")
16221        );
16222        assert!(!runner.state.worktree_root().exists());
16223        assert!(runner.state.candidates.is_empty());
16224        assert!(!repo.join(".git/config.worktree").exists());
16225        assert_eq!(
16226            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16227            "* main"
16228        );
16229    }
16230
16231    #[tokio::test]
16232    async fn preparation_records_creation_intent_before_git_can_fail() {
16233        ask_test_home();
16234        let tmp = tempfile::tempdir().unwrap();
16235        let repo = tmp.path().join("repo");
16236        std::fs::create_dir_all(&repo).unwrap();
16237        init_repo(&repo);
16238        let mut runner = runner_at(RunStatus::Prep);
16239        runner.state.repo = repo.clone();
16240        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16241        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16242        runner.state.config.blind.commit_msg_hook = false;
16243        runner.roles.implementers = vec![spec("one")];
16244        let label = blind::assign_labels(1, runner.state.seed)[0];
16245        let branch = runner.state.branch_for(label);
16246        // A conflicting branch makes Git refuse creation before a candidate
16247        // can be registered. The durable intent must still identify it.
16248        git::git(&repo, &["branch", &branch]).await.unwrap();
16249        assert!(runner.prep().await.is_err());
16250        let saved = RunState::load(&runner.state.id).unwrap();
16251        assert!(saved.candidates.is_empty());
16252        let event = saved
16253            .events
16254            .iter()
16255            .find(|e| e.node == "prep-intent")
16256            .unwrap();
16257        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16258        assert_eq!(intent["branch"], branch);
16259        assert_eq!(intent["start"], runner.state.base_commit);
16260        assert_eq!(
16261            intent["worktree"],
16262            runner
16263                .state
16264                .worktree_root()
16265                .join(format!("cand-{label}"))
16266                .to_string_lossy()
16267                .as_ref()
16268        );
16269        assert_eq!(intent["picks"], serde_json::json!([]));
16270    }
16271
16272    #[tokio::test]
16273    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16274        ask_test_home();
16275        let tmp = tempfile::tempdir().unwrap();
16276        let repo = tmp.path().join("repo");
16277        std::fs::create_dir_all(&repo).unwrap();
16278        init_repo(&repo);
16279        let mut runner = runner_at(RunStatus::Prep);
16280        runner.state.repo = repo.clone();
16281        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16282        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16283        runner.state.sources.pick_commits.push(refs::Input {
16284            token: "missing".into(),
16285            sha: "0".repeat(40),
16286            provenance: refs::Provenance::ExplicitCli,
16287        });
16288        assert!(runner.prep().await.is_err());
16289        assert!(runner.state.candidates.is_empty());
16290        assert!(!runner.state.worktree_root().exists());
16291    }
16292
16293    #[tokio::test]
16294    async fn prose_and_legacy_inference_never_import_into_candidates() {
16295        ask_test_home();
16296        let tmp = tempfile::tempdir().unwrap();
16297        let repo = tmp.path().join("repo");
16298        std::fs::create_dir_all(&repo).unwrap();
16299        init_repo(&repo);
16300        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16301        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16302            .await
16303            .unwrap();
16304        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16305        git::git(&repo, &["add", "."]).await.unwrap();
16306        git::git(&repo, &["commit", "-m", "historical implementation"])
16307            .await
16308            .unwrap();
16309        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16310        git::git(&repo, &["checkout", "main"]).await.unwrap();
16311        for instruction in [
16312            format!("Example: magi/history/A at {source}"),
16313            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16314            format!("Never import magi/history/A or {source}"),
16315            format!("Conversation answer: I mentioned {source} only as background"),
16316        ] {
16317            let mut runner = runner_at(RunStatus::Prep);
16318            runner.state.repo = repo.clone();
16319            runner.state.base_commit = base.clone();
16320            runner.state.instruction = instruction.clone();
16321            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16322            runner.state.config.blind.commit_msg_hook = false;
16323            runner.state.seeds = vec![refs::Seed {
16324                token: "magi/history/A".into(),
16325                sha: source.clone(),
16326                kind: refs::SeedKind::Unmerged,
16327                branch: true,
16328                detail: String::new(),
16329            }];
16330            runner.roles.implementers = vec![spec("one")];
16331            assert_eq!(seeded_instruction(&runner.state), instruction);
16332            // Model an old record with inferred seeds but no structured input field.
16333            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16334            legacy.as_object_mut().unwrap().remove("sources");
16335            runner.state = serde_json::from_value(legacy).unwrap();
16336            assert_eq!(runner.state.sources, refs::Sources::default());
16337            runner.state.save().unwrap();
16338            runner.state = RunState::load(&runner.state.id).unwrap();
16339            runner.prep().await.unwrap();
16340            for candidate in &runner.state.candidates {
16341                assert_eq!(
16342                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16343                    base
16344                );
16345                assert!(!candidate.worktree.join("unwanted").exists());
16346            }
16347        }
16348    }
16349
16350    #[tokio::test]
16351    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16352        ask_test_home();
16353        let tmp = tempfile::tempdir().unwrap();
16354        let repo = tmp.path().join("repo");
16355        std::fs::create_dir_all(&repo).unwrap();
16356        init_repo(&repo);
16357        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16358        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16359        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16360        git::git(&repo, &["add", "."]).await.unwrap();
16361        git::git(&repo, &["commit", "-m", "required seed"])
16362            .await
16363            .unwrap();
16364        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16365        git::git(&repo, &["checkout", "main"]).await.unwrap();
16366        let mut runner = runner_at(RunStatus::Prep);
16367        runner.state.repo = repo.clone();
16368        runner.state.base_commit = base.clone();
16369        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16370        runner.state.config.graph.advise = false;
16371        runner.state.config.blind.commit_msg_hook = false;
16372        runner.state.sources =
16373            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16374                .await
16375                .unwrap();
16376        runner.roles.implementers = vec![spec("one"), spec("two")];
16377        runner.roles.judges = vec![spec("judge")];
16378        let label = blind::assign_labels(2, runner.state.seed)[0];
16379        let branch = runner.state.branch_for(label);
16380        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16381        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16382            .await
16383            .unwrap();
16384        runner.state.candidates.push(Candidate {
16385            index: 0,
16386            label,
16387            agent: "one".into(),
16388            branch,
16389            worktree,
16390            summary: String::new(),
16391            stat: String::new(),
16392            files: 0,
16393            commits: 0,
16394            empty: false,
16395            failed: None,
16396            verified_noop: None,
16397            duration_ms: 0,
16398            folded: false,
16399        });
16400        runner.state.save().unwrap();
16401        // Reload the checkpoint immediately before its first cherry-pick.
16402        runner.state = RunState::load(&runner.state.id).unwrap();
16403        assert_eq!(runner.state.prep_complete, Some(false));
16404        runner.prep().await.unwrap();
16405        assert_eq!(runner.state.prep_complete, Some(true));
16406        assert_eq!(runner.state.candidates.len(), 2);
16407        for candidate in &runner.state.candidates {
16408            assert_eq!(
16409                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16410                git::tree_of(&repo, &seed).await.unwrap()
16411            );
16412            assert_eq!(
16413                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16414                "required commit"
16415            );
16416        }
16417        assert!(runner.state.worktree_root().join("judge-1").exists());
16418        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16419        runner.prep().await.unwrap();
16420        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16421
16422        runner.state.prep_complete = Some(false);
16423        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16424            run: Some(format!(
16425                "test -f '{}'",
16426                tmp.path().join("dependency-ready").display()
16427            )),
16428            ..Default::default()
16429        }];
16430        assert!(runner.prep().await.is_err());
16431        assert!(runner.state.prep_failure.is_some());
16432        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16433        runner.state = RunState::load(&runner.state.id).unwrap();
16434        assert!(
16435            runner.prep().await.is_err(),
16436            "correcting the cause alone must not auto-retry"
16437        );
16438        let failed_at = runner.state.events.last().unwrap().at;
16439        assert!(
16440            runner.retry_preparation(failed_at).is_err(),
16441            "old approvals cannot unlock the hold"
16442        );
16443        let mut task = crate::queue::Task::new(
16444            "retry".into(),
16445            "retry setup".into(),
16446            repo.clone(),
16447            crate::queue::Source::Human,
16448        );
16449        task.start(runner.state.id.clone());
16450        task.hold_machine(Some("setup failed".into()));
16451        task.release_operator("cli", None);
16452        runner
16453            .retry_preparation(task.resumption.as_ref().unwrap().at)
16454            .unwrap();
16455        runner.prep().await.unwrap();
16456        assert!(runner.state.prep_failure.is_none());
16457        assert_eq!(runner.state.prep_complete, Some(true));
16458        assert_eq!(runner.state.candidates.len(), 2);
16459        assert!(runner.state.worktree_root().join("judge-1").exists());
16460        for candidate in &runner.state.candidates {
16461            assert_eq!(
16462                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16463                git::tree_of(&repo, &seed).await.unwrap()
16464            );
16465        }
16466    }
16467
16468    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16469        let mut heads = Vec::new();
16470        for candidate in candidates {
16471            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16472        }
16473        heads
16474    }
16475
16476    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16477        ask_test_home();
16478        let tmp = tempfile::tempdir().unwrap();
16479        let repo = tmp.path().join("repo");
16480        std::fs::create_dir(&repo).unwrap();
16481        init_repo(&repo);
16482        let mut runner = runner_at(RunStatus::Reviewing);
16483        runner.state.repo = repo.clone();
16484        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16485        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16486        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16487            let branch = format!("candidate-{label}");
16488            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16489            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16490                .await
16491                .unwrap();
16492            if label == 'B' {
16493                std::fs::write(worktree.join("change"), "winner").unwrap();
16494                git::rescue_commit(&worktree, "candidate change")
16495                    .await
16496                    .unwrap();
16497            }
16498            runner.state.candidates.push(Candidate {
16499                index,
16500                label,
16501                agent: "alpha".into(),
16502                branch,
16503                worktree,
16504                summary: "completed reply".into(),
16505                stat: String::new(),
16506                files: usize::from(label == 'B'),
16507                commits: usize::from(label == 'B'),
16508                empty: label == 'A',
16509                failed: None,
16510                verified_noop: None,
16511                duration_ms: 1,
16512                folded: false,
16513            });
16514        }
16515        runner.state.judge_skipped = true;
16516        runner.state.tally = Some(Tally {
16517            first_choice: BTreeMap::new(),
16518            borda: BTreeMap::new(),
16519            winner: 'B',
16520            rankings: 0,
16521            unanimous_initial: false,
16522            deliberated: false,
16523            changed_votes: 0,
16524            unanimous_final: false,
16525            tie_break: None,
16526            judges: 0,
16527            present: 0,
16528            quorum: 0,
16529            met_quorum: true,
16530            uncontested: Some("only B produced a change".into()),
16531        });
16532        runner.state.save().unwrap();
16533        (tmp, runner)
16534    }
16535
16536    #[tokio::test]
16537    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16538        let (_tmp, mut runner) = preservation_resume_fixture().await;
16539        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16540        runner.state.config.disk.cache_limit_bytes = 0;
16541        runner.state.config.graph.advise = true;
16542        runner.state.config.graph.advisors = 1;
16543        let advisor = runner.state.worktree_root().join("advisor-1");
16544        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16545            .await
16546            .unwrap();
16547        let home = crate::run::home();
16548        let loser =
16549            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16550        let winner =
16551            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16552        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16553        for target in [&loser, &winner, &advisor] {
16554            std::fs::write(target.join("build-output"), "compiled").unwrap();
16555        }
16556
16557        runner.fold_losers().await.unwrap();
16558
16559        assert!(!loser.join("build-output").exists());
16560        assert!(!advisor.join("build-output").exists());
16561        assert!(winner.join("build-output").is_file());
16562    }
16563
16564    #[tokio::test]
16565    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16566        let (_tmp, mut runner) = preservation_resume_fixture().await;
16567        runner.state.candidates[0].folded = true;
16568        runner.state.config.graph.advise = true;
16569        runner.state.config.graph.advisors = 2;
16570        let repo = runner.state.repo.clone();
16571        let root = runner.state.worktree_root();
16572        let discarded = root.join("advisor-1");
16573        git::worktree_add_detached(&repo, &discarded, "main")
16574            .await
16575            .unwrap();
16576        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16577        let protected = root.join("advisor-2");
16578        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16579            .await
16580            .unwrap();
16581        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16582        runner.state.save().unwrap();
16583
16584        assert!(runner.fold_losers().await.is_err());
16585        assert!(!discarded.exists());
16586        assert!(protected.join("keep").exists());
16587        let saved = RunState::load(&runner.state.id).unwrap();
16588        assert!(saved.events.iter().any(|event| {
16589            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16590        }));
16591    }
16592
16593    #[tokio::test]
16594    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16595        let (tmp, mut runner) = preservation_resume_fixture().await;
16596        let repo = runner.state.repo.clone();
16597        let root = runner.state.worktree_root();
16598        for name in ["advisor-3", "judge-1", "review-2"] {
16599            let path = root.join(name);
16600            git::worktree_add_detached(&repo, &path, "main")
16601                .await
16602                .unwrap();
16603            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16604            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16605            remove_read_seat_worktree(&mut runner.state, &path)
16606                .await
16607                .unwrap();
16608            assert!(!path.exists());
16609        }
16610        let outside = tmp.path().join("advisor-1");
16611        let unknown = root.join("unknown");
16612        let attached = root.join("advisor-4");
16613        git::worktree_add_detached(&repo, &outside, "main")
16614            .await
16615            .unwrap();
16616        git::worktree_add_detached(&repo, &unknown, "main")
16617            .await
16618            .unwrap();
16619        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16620            .await
16621            .unwrap();
16622        let foreign = tmp.path().join("foreign");
16623        std::fs::create_dir(&foreign).unwrap();
16624        init_repo(&foreign);
16625        let wrong_repo = root.join("judge-2");
16626        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16627            .await
16628            .unwrap();
16629        let candidate = runner.state.candidates[0].worktree.clone();
16630        for path in [outside, unknown, attached, wrong_repo, candidate] {
16631            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16632            assert!(
16633                remove_read_seat_worktree(&mut runner.state, &path)
16634                    .await
16635                    .is_err()
16636            );
16637            assert_eq!(
16638                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16639                "keep"
16640            );
16641        }
16642    }
16643
16644    #[tokio::test]
16645    #[cfg(unix)]
16646    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16647        for (solo, failed_checkpoint) in
16648            [(true, false), (false, false), (true, true), (false, true)]
16649        {
16650            let (_tmp, mut runner) = preservation_resume_fixture().await;
16651            if solo {
16652                runner.state.candidates.retain(|c| c.label == 'A');
16653            }
16654            runner.state.candidates[0].empty = false;
16655            runner.state.candidates[0].summary.clear();
16656            runner.state.tally = None;
16657            runner.state.judge_skipped = false;
16658            runner.state.status = RunStatus::Implementing;
16659            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16660            let mut implementer = spec("alpha");
16661            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16662            runner.roles.implementers = vec![implementer];
16663            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16664            if failed_checkpoint {
16665                std::fs::create_dir_all(&patch).unwrap();
16666            }
16667            runner.state.save().unwrap();
16668            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16669            drop(pressure);
16670            runner.state = RunState::load(&runner.state.id).unwrap();
16671            assert_eq!(runner.state.status, RunStatus::Blocked);
16672            assert!(runner.state.interrupted_implementations.contains(&'A'));
16673            assert_eq!(runner.state.candidates[0].commits, 0);
16674            assert!(!runner.state.candidates[0].empty);
16675            assert!(runner.state.candidates[0].failed.is_none());
16676            if failed_checkpoint {
16677                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16678                std::fs::remove_dir(patch).unwrap();
16679            }
16680            runner.state.resource_block = None;
16681            runner.state.config.disk.min_free_bytes = 0;
16682            runner.roles.implementers[0].command = vec![
16683                "sh".into(),
16684                "-c".into(),
16685                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16686            ];
16687            runner.implement().await.unwrap();
16688            assert!(runner.state.interrupted_implementations.is_empty());
16689            assert!(runner.state.candidate_preservation.is_empty());
16690            assert_eq!(runner.state.candidates[0].commits, 1);
16691            assert!(!runner.state.candidates[0].empty);
16692            assert!(
16693                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16694                    .unwrap()
16695                    .contains("retried empty interrupted seat")
16696            );
16697            if !solo {
16698                assert_eq!(runner.state.candidates[1].commits, 1);
16699            }
16700        }
16701    }
16702
16703    #[tokio::test]
16704    #[cfg(unix)]
16705    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16706        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16707            let (_tmp, mut runner) = preservation_resume_fixture().await;
16708            runner.state.candidates.retain(|c| c.label == 'A');
16709            runner.state.candidates[0].empty = false;
16710            runner.state.candidates[0].summary.clear();
16711            runner.state.tally = None;
16712            runner.state.judge_skipped = false;
16713            runner.state.status = RunStatus::Implementing;
16714            // Force only the real post-spawn watchdog, without failing the
16715            // separate admission check. Existing edits predate its measurement.
16716            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16717            let wt = runner.state.candidates[0].worktree.clone();
16718            std::fs::write(
16719                wt.join("interrupted-source"),
16720                "retain implementation work\n",
16721            )
16722            .unwrap();
16723            if committed {
16724                git::rescue_commit(&wt, "implementation checkpoint")
16725                    .await
16726                    .unwrap();
16727            }
16728            let lock = git::git(
16729                &wt,
16730                &[
16731                    "rev-parse",
16732                    "--path-format=absolute",
16733                    "--git-path",
16734                    "index.lock",
16735                ],
16736            )
16737            .await
16738            .unwrap();
16739            if block_rescue {
16740                std::fs::write(&lock, "fixture-owned lock").unwrap();
16741            }
16742            let mut implementer = spec("alpha");
16743            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16744            runner.roles.implementers = vec![implementer];
16745            runner.state.save().unwrap();
16746            let result = runner.implement().await;
16747            drop(pressure);
16748            assert_eq!(result.is_err(), block_rescue);
16749            assert_eq!(
16750                runner.state.resource_block.as_ref().unwrap().kind,
16751                "disk pressure"
16752            );
16753            assert!(
16754                runner
16755                    .state
16756                    .events
16757                    .iter()
16758                    .any(|e| e.message.contains("agent execution interrupted"))
16759            );
16760            assert!(
16761                runner
16762                    .state
16763                    .dir()
16764                    .join("artifacts/candidate-A-recovery/staged.patch")
16765                    .exists()
16766            );
16767            if block_rescue {
16768                let saved = RunState::load(&runner.state.id).unwrap();
16769                assert!(saved.candidate_preservation.contains_key(&'A'));
16770                assert!(!saved.candidates[0].empty);
16771                assert_eq!(
16772                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16773                    "retain implementation work\n"
16774                );
16775                std::fs::remove_file(lock).unwrap();
16776                runner.state = saved;
16777            } else {
16778                assert_eq!(runner.state.status, RunStatus::Blocked);
16779                assert_eq!(runner.state.candidates[0].commits, 1);
16780            }
16781            // Recovery must save the candidate before deciding whether another
16782            // implementation is needed. No implementer is available on retry.
16783            runner.roles.implementers.clear();
16784            runner.state.config.disk.min_free_bytes = 0;
16785            runner.state.resource_block = None;
16786            runner.implement().await.unwrap();
16787            assert!(runner.state.candidate_preservation.is_empty());
16788            assert_eq!(runner.state.candidates[0].commits, 1);
16789            assert!(!runner.state.candidates[0].empty);
16790            assert!(git::is_clean(&wt).await.unwrap());
16791            assert!(
16792                crate::run::read_artifact(&runner.state, "cand-A.patch")
16793                    .unwrap()
16794                    .contains("retain implementation work")
16795            );
16796        }
16797    }
16798
16799    #[tokio::test]
16800    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16801        let (_tmp, mut runner) = preservation_resume_fixture().await;
16802        // Schema 15 already confirmed the unfolded no-change result.
16803        runner.implement().await.unwrap();
16804        assert!(runner.state.candidate_preservation.is_empty());
16805        assert!(
16806            !runner
16807                .state
16808                .dir()
16809                .join("artifacts/candidate-A-recovery")
16810                .exists()
16811        );
16812        runner.fold_losers().await.unwrap();
16813        assert!(!runner.state.candidates[0].worktree.exists());
16814        for schema in [14, crate::run::SCHEMA] {
16815            runner.state.schema = schema;
16816            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16817            runner.state.save().unwrap();
16818            runner.state = RunState::load(&runner.state.id).unwrap();
16819            runner.implement().await.unwrap();
16820            assert!(runner.state.candidate_preservation.is_empty());
16821            assert!(runner.state.candidates[0].folded);
16822            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16823        }
16824    }
16825
16826    #[tokio::test]
16827    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16828        let (_tmp, mut runner) = preservation_resume_fixture().await;
16829        runner.state.candidates.retain(|c| c.label == 'A');
16830        runner.state.tally = None;
16831        runner.state.judge_skipped = false;
16832        let candidate = &mut runner.state.candidates[0];
16833        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16834        candidate.failed = Some("deployment validation unavailable".into());
16835        std::fs::write(
16836            candidate.worktree.join("repair"),
16837            "future launcher policy\n",
16838        )
16839        .unwrap();
16840        runner
16841            .state
16842            .candidate_preservation
16843            .insert('A', "awaiting persistence".into());
16844        runner.persist_candidates().await.unwrap();
16845        let candidate = &runner.state.candidates[0];
16846        assert!(!candidate.empty);
16847        assert_eq!(candidate.commits, 1);
16848        assert_eq!(candidate.files, 1);
16849        assert!(candidate.failed.is_none());
16850        assert!(candidate.summary.contains("EPERM"));
16851        assert!(
16852            crate::run::read_artifact(&runner.state, "cand-A.patch")
16853                .unwrap()
16854                .contains("future launcher policy")
16855        );
16856        assert!(runner.state.candidate_preservation.is_empty());
16857    }
16858
16859    #[tokio::test]
16860    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
16861        let (_tmp, mut runner) = preservation_resume_fixture().await;
16862        let wt = runner.state.candidates[0].worktree.clone();
16863        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
16864        runner.state.schema = 14;
16865        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16866        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16867        let tally = serde_json::to_value(&runner.state.tally).unwrap();
16868        for _ in 0..2 {
16869            assert!(runner.implement().await.is_err());
16870            assert_eq!(runner.state.status, RunStatus::Blocked);
16871            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16872            assert!(
16873                runner.state.candidates[0].empty,
16874                "old verdict must remain unusable"
16875            );
16876            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
16877            assert!(runner.state.judge_skipped);
16878            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
16879            assert!(
16880                crate::run::read_artifact(&runner.state, "cand-A.patch")
16881                    .unwrap()
16882                    .contains("owned edits")
16883            );
16884            assert!(wt.exists());
16885            assert_eq!(
16886                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
16887                    .await
16888                    .unwrap(),
16889                1
16890            );
16891            runner.state = RunState::load(&runner.state.id).unwrap();
16892        }
16893    }
16894
16895    #[tokio::test]
16896    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
16897        let (_tmp, mut runner) = preservation_resume_fixture().await;
16898        let wt = runner.state.candidates[0].worktree.clone();
16899        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
16900        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
16901        let index_lock = PathBuf::from(
16902            git::git(
16903                &wt,
16904                &[
16905                    "rev-parse",
16906                    "--path-format=absolute",
16907                    "--git-path",
16908                    "index.lock",
16909                ],
16910            )
16911            .await
16912            .unwrap(),
16913        );
16914        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16915        runner.state.schema = 14;
16916        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16917        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16918        assert!(runner.implement().await.is_err());
16919        assert!(runner.after_implement().is_err());
16920        assert!(runner.fold_losers().await.is_err());
16921        assert_eq!(
16922            std::fs::read_to_string(wt.join("recovered")).unwrap(),
16923            "failed seat edits"
16924        );
16925        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16926        runner.state = RunState::load(&runner.state.id).unwrap();
16927        std::fs::remove_file(index_lock).unwrap();
16928        // Recovery finds changes that the old uncontested result never judged.
16929        assert!(runner.implement().await.is_err());
16930        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16931        assert!(runner.state.candidates[0].empty);
16932        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16933        assert!(
16934            crate::run::read_artifact(&runner.state, "cand-A.patch")
16935                .unwrap()
16936                .contains("failed seat edits")
16937        );
16938        assert!(wt.exists());
16939    }
16940
16941    #[tokio::test]
16942    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
16943        let (_tmp, mut runner) = preservation_resume_fixture().await;
16944        let repo = runner.state.repo.clone();
16945        let common = git::git(
16946            &repo,
16947            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
16948        )
16949        .await
16950        .unwrap();
16951        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
16952        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
16953        assert!(runner.fold_losers().await.is_err());
16954        assert!(!runner.state.candidates[0].worktree.exists());
16955        assert!(!runner.state.candidates[0].folded);
16956        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
16957        runner.state = RunState::load(&runner.state.id).unwrap();
16958        std::fs::remove_file(branch_lock).unwrap();
16959        let judge = runner.state.worktree_root().join("judge-1");
16960        git::worktree_add_detached(&repo, &judge, "main")
16961            .await
16962            .unwrap();
16963        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
16964        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
16965            .await
16966            .unwrap();
16967        runner.roles.judges = vec![spec("judge")];
16968        assert!(runner.fold_losers().await.is_err());
16969        runner.state = RunState::load(&runner.state.id).unwrap();
16970        assert!(
16971            runner.state.candidates[0].folded,
16972            "candidate progress saved before judge failure"
16973        );
16974        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
16975        assert!(judge.join("uncommitted").exists());
16976        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
16977            .await
16978            .unwrap();
16979        runner.fold_losers().await.unwrap();
16980        assert!(!judge.exists());
16981        runner.fold_losers().await.unwrap();
16982    }
16983
16984    #[tokio::test]
16985    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
16986        let (_tmp, mut runner) = preservation_resume_fixture().await;
16987        runner.state.candidates.retain(|c| c.label == 'B');
16988        runner.state.tally = None;
16989        runner.state.judge_skipped = false;
16990        runner.state.prep_complete = Some(true);
16991        runner.state.config.graph.advise = false;
16992        runner.state.config.graph.selected_implementer = Some("alpha".into());
16993        let wt = runner.state.candidates[0].worktree.clone();
16994        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
16995        runner
16996            .state
16997            .candidate_preservation
16998            .insert('B', "awaiting persistence".into());
16999        let index_lock = git::git(
17000            &wt,
17001            &[
17002                "rev-parse",
17003                "--path-format=absolute",
17004                "--git-path",
17005                "index.lock",
17006            ],
17007        )
17008        .await
17009        .unwrap();
17010        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17011        runner.state.save().unwrap();
17012        assert!(runner.execute_graph().await.is_err());
17013        assert_eq!(runner.state.status, RunStatus::Blocked);
17014        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17015        std::fs::remove_file(index_lock).unwrap();
17016        // Park at the next graph boundary: this tests the real selected-seat
17017        // hold guard without dispatching reviewers or publishing anything.
17018        for _ in 0..2 {
17019            runner.state = RunState::load(&runner.state.id).unwrap();
17020            runner.pause.park();
17021            runner.execute_graph().await.unwrap();
17022            assert_eq!(runner.state.status, RunStatus::Implementing);
17023            assert!(runner.state.candidate_preservation.is_empty());
17024            assert_eq!(runner.state.candidates[0].commits, 2);
17025            assert!(runner.state.tally.is_none());
17026        }
17027        runner.implement().await.unwrap();
17028        assert_eq!(runner.state.status, RunStatus::Judging);
17029        // A genuine selected-implementer hold must still require release.
17030        runner.state.status = RunStatus::Blocked;
17031        runner.state.candidates[0].failed = Some("implementation failed".into());
17032        runner.state.save().unwrap();
17033        let error = runner.execute_graph().await.unwrap_err();
17034        assert!(
17035            error
17036                .to_string()
17037                .contains("selected implementation is held")
17038        );
17039    }
17040
17041    #[tokio::test]
17042    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17043        let (_tmp, mut runner) = preservation_resume_fixture().await;
17044        let repo = runner.state.repo.clone();
17045        let candidate = runner.state.candidates[0].clone();
17046        // Remove only the disposable fixture directory, leaving Git's linked
17047        // worktree registration and branch intact, as in a vanished checkout.
17048        let registered = git::worktree_holding(&repo, &candidate.branch)
17049            .await
17050            .unwrap()
17051            .unwrap();
17052        assert_eq!(
17053            registered.canonicalize().unwrap(),
17054            candidate.worktree.canonicalize().unwrap()
17055        );
17056        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17057        assert_eq!(
17058            git::worktree_holding(&repo, &candidate.branch)
17059                .await
17060                .unwrap(),
17061            Some(registered)
17062        );
17063        assert!(
17064            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17065            "the stale registration initially keeps the branch checked out"
17066        );
17067        runner.fold_losers().await.unwrap();
17068        assert!(runner.state.candidates[0].folded);
17069        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17070        assert_eq!(
17071            git::worktree_holding(&repo, &candidate.branch)
17072                .await
17073                .unwrap(),
17074            None
17075        );
17076        runner.state = RunState::load(&runner.state.id).unwrap();
17077        runner.fold_losers().await.unwrap();
17078    }
17079
17080    #[tokio::test]
17081    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17082        let (_tmp, mut runner) = preservation_resume_fixture().await;
17083        let repo = runner.state.repo.clone();
17084        let candidate = runner.state.candidates[0].clone();
17085        let winner = runner.state.candidates[1].clone();
17086        let registered = git::worktree_holding(&repo, &candidate.branch)
17087            .await
17088            .unwrap()
17089            .unwrap();
17090        assert_eq!(
17091            registered.canonicalize().unwrap(),
17092            candidate.worktree.canonicalize().unwrap()
17093        );
17094        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17095        assert_eq!(
17096            git::worktree_holding(&repo, &candidate.branch)
17097                .await
17098                .unwrap(),
17099            Some(registered)
17100        );
17101        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17102
17103        for _ in 0..2 {
17104            fold_run(&mut runner.state, false, &crate::run::home())
17105                .await
17106                .unwrap();
17107            runner.state = RunState::load(&runner.state.id).unwrap();
17108            assert!(runner.state.candidates[0].folded);
17109            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17110            assert_eq!(
17111                git::worktree_holding(&repo, &candidate.branch)
17112                    .await
17113                    .unwrap(),
17114                None
17115            );
17116            assert!(!runner.state.candidates[1].folded);
17117            assert!(winner.worktree.exists());
17118            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17119        }
17120    }
17121    #[tokio::test]
17122    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17123        for sidecar in [false, true] {
17124            let tmp = tempfile::tempdir().unwrap();
17125            let home = tmp.path().join("home");
17126            let repo = tmp.path().join("repo");
17127            std::fs::create_dir(&repo).unwrap();
17128            init_repo(&repo);
17129            let mut state = runner_at(RunStatus::Superseded).state;
17130            state.repo = repo.clone();
17131            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17132            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17133            state.driver_exited = true;
17134            state.reserve_under(&home).unwrap();
17135            git::git(
17136                &repo,
17137                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17138            )
17139            .await
17140            .unwrap();
17141            let wt = state.worktree_root().join("cand-A");
17142            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17143                .await
17144                .unwrap();
17145            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17146            git::commit_all(&wt, "fixture: independent source")
17147                .await
17148                .unwrap();
17149            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17150            state.candidates.push(Candidate {
17151                index: 0,
17152                label: 'A',
17153                agent: "fixture".into(),
17154                branch: "candidate".into(),
17155                worktree: wt.clone(),
17156                summary: String::new(),
17157                stat: String::new(),
17158                files: 0,
17159                commits: 0,
17160                empty: false,
17161                failed: None,
17162                verified_noop: None,
17163                duration_ms: 0,
17164                folded: false,
17165            });
17166            let mut task = crate::queue::Task::new(
17167                "task".into(),
17168                "task".into(),
17169                repo.clone(),
17170                crate::queue::Source::Human,
17171            );
17172            task.runs.push(state.id.clone());
17173            crate::queue::Queue::at(home.join("queue"))
17174                .put(&mut task)
17175                .unwrap();
17176            if sidecar {
17177                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17178            }
17179            state.save_under(&home).unwrap();
17180            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17181            assert!(
17182                fold_run(&mut state, true, &home)
17183                    .await
17184                    .unwrap_err()
17185                    .to_string()
17186                    .contains(&reason)
17187            );
17188            let mut disk = state.config.disk.clone();
17189            disk.fold_grace_secs = 0;
17190            assert_eq!(
17191                crate::clean::fold_due(
17192                    &home.join("runs"),
17193                    &home,
17194                    &state.worktree_root(),
17195                    &disk,
17196                    Timestamp::now() + std::time::Duration::from_secs(10),
17197                )
17198                .await
17199                .unwrap(),
17200                (0, 0)
17201            );
17202            assert!(wt.exists());
17203            state.status = RunStatus::Blocked;
17204            state.save_under(&home).unwrap();
17205            assert!(
17206                fold_run_overriding_recovery_retention(&mut state, true, &home)
17207                    .await
17208                    .is_err()
17209            );
17210            state.status = RunStatus::Superseded;
17211            state.driver_exited = false;
17212            state.driver_claimed = None;
17213            state.save_under(&home).unwrap();
17214            assert!(
17215                fold_run_overriding_recovery_retention(&mut state, true, &home)
17216                    .await
17217                    .is_err()
17218            );
17219            state.driver_pid = Some(std::process::id());
17220            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17221            state.save_under(&home).unwrap();
17222            assert!(
17223                fold_run_overriding_recovery_retention(&mut state, true, &home)
17224                    .await
17225                    .is_err()
17226            );
17227            state.driver_exited = true;
17228            state.driver_pid = None;
17229            state.driver_started_at = None;
17230            state.save_under(&home).unwrap();
17231            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17232            assert!(
17233                fold_run_overriding_recovery_retention(&mut state, true, &home)
17234                    .await
17235                    .is_err()
17236            );
17237            drop(lease);
17238            #[cfg(unix)]
17239            {
17240                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17241                assert!(
17242                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17243                        .await
17244                        .is_err()
17245                );
17246                drop(output);
17247            }
17248            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17249            assert!(
17250                fold_run_overriding_recovery_retention(&mut state, true, &home)
17251                    .await
17252                    .is_err()
17253            );
17254            drop(owner);
17255            let checkpoint = git::git(
17256                &wt,
17257                &[
17258                    "rev-parse",
17259                    "--path-format=absolute",
17260                    "--git-path",
17261                    "CHERRY_PICK_HEAD",
17262                ],
17263            )
17264            .await
17265            .unwrap();
17266            std::fs::write(&checkpoint, &head).unwrap();
17267            assert!(
17268                fold_run_overriding_recovery_retention(&mut state, true, &home)
17269                    .await
17270                    .is_err()
17271            );
17272            std::fs::remove_file(checkpoint).unwrap();
17273            std::fs::write(wt.join("dirty"), "keep").unwrap();
17274            assert!(
17275                fold_run_overriding_recovery_retention(&mut state, true, &home)
17276                    .await
17277                    .is_err()
17278            );
17279            assert!(wt.join("dirty").exists());
17280            std::fs::remove_file(wt.join("dirty")).unwrap();
17281            let evidence = home
17282                .join("runs")
17283                .join(&state.id)
17284                .join("artifacts/fold-evidence");
17285            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17286            std::fs::write(&evidence, "blocked archive").unwrap();
17287            assert!(
17288                fold_run_overriding_recovery_retention(&mut state, true, &home)
17289                    .await
17290                    .is_err()
17291            );
17292            assert!(wt.exists());
17293            assert!(
17294                !RunState::load_under(&state.id, &home)
17295                    .unwrap()
17296                    .events
17297                    .iter()
17298                    .any(|event| event.message.contains("--override-recovery-retention"))
17299            );
17300            std::fs::remove_file(&evidence).unwrap();
17301            fold_run_overriding_recovery_retention(&mut state, true, &home)
17302                .await
17303                .unwrap();
17304            assert!(!wt.exists());
17305            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17306            assert!(
17307                git::worktree_holding(&repo, "candidate")
17308                    .await
17309                    .unwrap()
17310                    .is_none()
17311            );
17312            assert!(
17313                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17314                    .unwrap()
17315                    .contains("retained implementation")
17316            );
17317            assert!(evidence.join(format!("{head}.index")).is_file());
17318            let saved = RunState::load_under(&state.id, &home).unwrap();
17319            assert_eq!(saved.status, RunStatus::Superseded);
17320            assert!(saved.candidates[0].folded);
17321            assert!(saved.events.iter().any(|event| {
17322                event.message.contains("--override-recovery-retention")
17323                    && event.message.contains(&state.id)
17324                    && event.message.contains(&reason)
17325            }));
17326            assert_eq!(
17327                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17328                sidecar
17329            );
17330        }
17331    }
17332
17333    #[tokio::test]
17334    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17335        ask_test_home();
17336        let tmp = tempfile::tempdir().unwrap();
17337        let repo = tmp.path().join("repo");
17338        std::fs::create_dir(&repo).unwrap();
17339        init_repo(&repo);
17340        let mut runner = runner_at(RunStatus::Implementing);
17341        runner.state.repo = repo.clone();
17342        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17343        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17344        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17345            let branch = format!("candidate-{label}");
17346            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17347            git::worktree_add_branch(&repo, &wt, &branch, "main")
17348                .await
17349                .unwrap();
17350            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17351            git::git(&wt, &["add", "README.md"]).await.unwrap();
17352            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17353            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17354            runner.state.candidates.push(Candidate {
17355                index,
17356                label,
17357                agent: "alpha".to_owned(),
17358                branch,
17359                worktree: wt,
17360                summary: "completed implementation".to_owned(),
17361                stat: String::new(),
17362                files: 0,
17363                commits: 0,
17364                empty: false,
17365                failed: None,
17366                verified_noop: None,
17367                duration_ms: 42,
17368                folded: false,
17369            });
17370            runner
17371                .state
17372                .candidate_preservation
17373                .insert(label, "awaiting persistence".to_owned());
17374        }
17375        let wt = runner.state.candidates[0].worktree.clone();
17376        let index_lock = git::git(
17377            &wt,
17378            &[
17379                "rev-parse",
17380                "--path-format=absolute",
17381                "--git-path",
17382                "index.lock",
17383            ],
17384        )
17385        .await
17386        .unwrap();
17387        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17388        runner.state.save().unwrap();
17389        assert!(runner.persist_candidates().await.is_err());
17390        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17391        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17392        assert_eq!(
17393            runner.state.candidates[1].commits, 1,
17394            "other results are still collected"
17395        );
17396        assert!(
17397            !runner.state.candidates[0].empty,
17398            "failed rescue is not no change"
17399        );
17400        assert_eq!(
17401            runner.state.candidates[0].summary,
17402            "completed implementation"
17403        );
17404        assert!(runner.after_implement().is_err());
17405        let home = tmp.path().join("fold-home");
17406        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17407        assert!(wt.join("new-file").exists());
17408        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17409        assert!(recovery.join("staged.patch").exists());
17410        assert!(recovery.join("unstaged.patch").exists());
17411        assert_eq!(
17412            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17413            "untracked edits\n"
17414        );
17415        runner.state.begin_pass();
17416        runner.state.end_pass_parked(ParkCause::Upgrade {
17417            from: "1.0".into(),
17418            to: Some("1.1".into()),
17419        });
17420        runner.state.save().unwrap();
17421        runner.state = RunState::load(&runner.state.id).unwrap();
17422        assert!(matches!(
17423            runner.state.passes.last().unwrap().end,
17424            Some(crate::run::PassEnd::Parked {
17425                cause: ParkCause::Upgrade { .. }
17426            })
17427        ));
17428        std::fs::remove_file(index_lock).unwrap();
17429        // No implementer is configured: a persistence retry cannot dispatch a seat.
17430        runner.implement().await.unwrap();
17431        assert!(runner.state.candidate_preservation.is_empty());
17432        assert!(
17433            runner
17434                .state
17435                .candidates
17436                .iter()
17437                .all(|c| c.commits == 1 && !c.empty)
17438        );
17439        assert!(git::is_clean(&wt).await.unwrap());
17440        assert!(
17441            crate::run::read_artifact(&runner.state, "cand-A.patch")
17442                .unwrap()
17443                .contains("later tracked edits")
17444        );
17445    }
17446
17447    #[tokio::test]
17448    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17449        ask_test_home();
17450        let tmp = tempfile::tempdir().unwrap();
17451        let repo = tmp.path().join("repo");
17452        std::fs::create_dir(&repo).unwrap();
17453        init_repo(&repo);
17454        let wt = tmp.path().join("candidate");
17455        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17456            .await
17457            .unwrap();
17458        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17459        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17460        assert!(wt.join("uncommitted").exists());
17461        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17462        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17463        let mut runner = runner_at(RunStatus::Implementing);
17464        runner.state.repo = repo.clone();
17465        runner.state.base_commit = "missing-base".to_owned();
17466        runner.state.candidates.push(Candidate {
17467            index: 0,
17468            label: 'A',
17469            agent: "alpha".into(),
17470            branch: "candidate".into(),
17471            worktree: wt.clone(),
17472            summary: "completed".into(),
17473            stat: String::new(),
17474            files: 0,
17475            commits: 0,
17476            empty: false,
17477            failed: None,
17478            verified_noop: None,
17479            duration_ms: 1,
17480            folded: false,
17481        });
17482        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17483        assert!(
17484            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17485                .await
17486                .is_err()
17487        );
17488        assert!(!runner.state.candidates[0].folded);
17489        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17490        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17491        runner
17492            .state
17493            .candidate_preservation
17494            .insert('A', "pending".into());
17495        assert!(runner.persist_candidates().await.is_err());
17496        assert!(!runner.state.candidates[0].empty);
17497        assert!(!runner.state.candidates[0].folded);
17498        assert!(wt.exists());
17499        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17500        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17501        std::fs::create_dir_all(&patch_path).unwrap();
17502        assert!(
17503            runner.persist_candidates().await.is_err(),
17504            "artifact failure stays pending"
17505        );
17506        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17507        assert!(!runner.state.candidates[0].empty);
17508        std::fs::remove_dir(patch_path).unwrap();
17509        runner.persist_candidates().await.unwrap();
17510        assert!(
17511            runner.state.candidates[0].empty,
17512            "only successful inspection confirms no change"
17513        );
17514    }
17515
17516    fn init_repo(dir: &Path) {
17517        let run = |args: &[&str]| {
17518            let out = std::process::Command::new("git")
17519                .args(args)
17520                .current_dir(dir)
17521                .quiet()
17522                .output()
17523                .expect("spawn git");
17524            assert!(
17525                out.status.success(),
17526                "git {args:?} failed: {}",
17527                String::from_utf8_lossy(&out.stderr)
17528            );
17529        };
17530        run(&["init", "-b", "main"]);
17531        run(&["config", "user.name", "magi test"]);
17532        run(&["config", "user.email", "magi@example.com"]);
17533        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17534        run(&["add", "-A"]);
17535        run(&["commit", "-m", "init"]);
17536    }
17537
17538    // `settle_questions` is what closes the ghost the phone showed: a run's
17539    // seat asked something, the run then ended, and nothing was left to
17540    // abandon the question it left `open`. `HOME` is a process-wide
17541    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17542    // first time it runs in the binary — every test below still reaches the
17543    // same directory whichever call won, and each gets its own run id from
17544    // `RunState::new`, so they never collide there.
17545    fn ask_test_home() {
17546        crate::run::pin_test_home();
17547    }
17548
17549    #[test]
17550    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17551        ask_test_home();
17552        let mut runner = runner_at(RunStatus::Prep);
17553        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17554        // A blocked temporary output path makes the terminal save fail while
17555        // preserving the already published reservation.
17556        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17557        let error = guard
17558            .finish(
17559                &mut runner.state,
17560                Err(
17561                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17562                        .into(),
17563                ),
17564            )
17565            .unwrap_err();
17566        assert_eq!(
17567            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17568            std::io::ErrorKind::PermissionDenied
17569        );
17570        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17571        let message = format!("{error:#}");
17572        assert!(message.contains("original refusal"));
17573        assert!(!message.contains("could not save terminal"));
17574        assert_eq!(
17575            error.chain().count(),
17576            2,
17577            "only startup attribution wraps the original error"
17578        );
17579        let saved = RunState::load(&runner.state.id).unwrap();
17580        assert_eq!(saved.status, RunStatus::Blocked);
17581        assert!(!saved.startup.unwrap().complete);
17582    }
17583
17584    #[test]
17585    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17586        ask_test_home();
17587        let mut runner = runner_at(RunStatus::Prep);
17588        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17589        let id = runner.state.id.clone();
17590        drop(guard);
17591        let saved = RunState::load(&id).unwrap();
17592        assert_eq!(saved.status, RunStatus::Blocked);
17593        assert!(!saved.startup.as_ref().unwrap().complete);
17594        assert!(
17595            saved
17596                .startup
17597                .unwrap()
17598                .failure
17599                .unwrap()
17600                .contains("interrupted")
17601        );
17602        assert!(Runner::resume(&id).is_err());
17603    }
17604
17605    #[test]
17606    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17607        ask_test_home();
17608        let mut runner = runner_at(RunStatus::Prep);
17609        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17610        let error = guard
17611            .finish(
17612                &mut runner.state,
17613                Err(
17614                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17615                        .into(),
17616                ),
17617            )
17618            .unwrap_err();
17619        assert_eq!(
17620            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17621            std::io::ErrorKind::PermissionDenied
17622        );
17623        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17624        let mut task = crate::queue::Task::new(
17625            "review".into(),
17626            "criteria".into(),
17627            runner.state.repo.clone(),
17628            crate::queue::Source::Human,
17629        );
17630        task.record_startup_failure(failure.clone());
17631        task.record_startup_failure(failure.clone());
17632        assert_eq!(task.startup_failures.len(), 1);
17633        assert!(task.runs.is_empty());
17634        assert_eq!(task.attempts, 0);
17635    }
17636
17637    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17638        ask_test_home();
17639        let tmp = tempfile::tempdir().unwrap();
17640        let repo = tmp.path().join("repo");
17641        std::fs::create_dir(&repo).unwrap();
17642        init_repo(&repo);
17643        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17644        let origin = tmp.path().join("origin.git");
17645        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17646            .await
17647            .unwrap();
17648        git::git(
17649            &repo,
17650            &["remote", "add", "origin", origin.to_str().unwrap()],
17651        )
17652        .await
17653        .unwrap();
17654        git::git(&repo, &["checkout", "-b", "fix/retained"])
17655            .await
17656            .unwrap();
17657        std::fs::write(repo.join("retained"), "retained change").unwrap();
17658        git::git(&repo, &["add", "."]).await.unwrap();
17659        git::git(&repo, &["commit", "-m", "retained implementation"])
17660            .await
17661            .unwrap();
17662        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17663        git::git(&repo, &["checkout", "main"]).await.unwrap();
17664        std::fs::write(repo.join("base-change"), "new base").unwrap();
17665        git::git(&repo, &["add", "."]).await.unwrap();
17666        git::git(&repo, &["commit", "-m", "base moved"])
17667            .await
17668            .unwrap();
17669        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17670        git::git(&repo, &["checkout", "fix/retained"])
17671            .await
17672            .unwrap();
17673        let mut runner = runner_at(RunStatus::Voting);
17674        runner.state.repo = repo.clone();
17675        runner.state.base_commit = base;
17676        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17677        runner.state.config.disk.min_free_bytes = 0;
17678        runner.state.config.graph.review_rounds = 1;
17679        runner.state.config.verify.e2e = vec!["true".into()];
17680        runner.state.config.verify.gate = vec!["true".into()];
17681        runner.state.candidates = vec![Candidate {
17682            index: 0,
17683            label: 'A',
17684            agent: "fixture".into(),
17685            branch: "fix/retained".into(),
17686            worktree: repo.clone(),
17687            summary: String::new(),
17688            stat: String::new(),
17689            files: 1,
17690            commits: 1,
17691            empty: false,
17692            failed: None,
17693            verified_noop: None,
17694            duration_ms: 0,
17695            folded: false,
17696        }];
17697        runner.state.tally = Some(Tally {
17698            first_choice: BTreeMap::new(),
17699            borda: BTreeMap::new(),
17700            winner: 'A',
17701            rankings: 0,
17702            unanimous_initial: true,
17703            deliberated: false,
17704            changed_votes: 0,
17705            unanimous_final: true,
17706            tie_break: None,
17707            judges: 0,
17708            present: 0,
17709            quorum: 0,
17710            met_quorum: true,
17711            uncontested: Some("review-only".into()),
17712        });
17713        let mut task = crate::queue::Task::new(
17714            "fixture".into(),
17715            "fixture".into(),
17716            repo,
17717            crate::queue::Source::Human,
17718        );
17719        task.link_run(&runner.state.id);
17720        crate::queue::Queue::open().put(&mut task).unwrap();
17721        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17722        runner.state.base_sync = Some(BaseSync {
17723            tip: String::new(),
17724            behind: 1,
17725            attempts: BASE_SYNC_ROUNDS,
17726            conflict: None,
17727            already_in: None,
17728        });
17729        runner.sync_to_base().await.unwrap();
17730        assert_eq!(runner.state.status, RunStatus::Blocked);
17731        (tmp, runner, head, task.id)
17732    }
17733
17734    #[tokio::test]
17735    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17736        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17737        runner.state.status = RunStatus::Voting;
17738        runner.state.base_sync = None;
17739        runner.state.base_sync_recovery = Default::default();
17740        let scratch = runner.state.dir().join("base-sync");
17741        std::fs::create_dir_all(&scratch).unwrap();
17742        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17743        runner.sync_to_base().await.unwrap();
17744        assert!(runner.state.resource_block.is_some());
17745        assert!(!runner.state.base_sync_blocked());
17746        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 0);
17747        assert_eq!(runner.state.base_episode_used(), 0);
17748        assert!(runner.state.base_sync_recovery.operations.is_empty());
17749        assert!(runner.state.rebase_fixes.is_empty());
17750        assert_eq!(
17751            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17752            head
17753        );
17754        std::fs::remove_dir_all(&scratch).unwrap();
17755        runner.state.resource_block = None;
17756        runner.sync_to_base().await.unwrap();
17757        assert!(!runner.state.base_sync_blocked());
17758        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17759        assert_eq!(runner.state.base_episode_used(), 1);
17760        assert!(runner.state.base_sync_recovery.operations[0].finished);
17761        assert!(runner.state.rebase_fixes.is_empty());
17762        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17763        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17764    }
17765
17766    #[cfg(unix)]
17767    #[tokio::test]
17768    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
17769        for routed in [false, true] {
17770            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17771            let home = crate::run::home();
17772            let queue = crate::queue::Queue::open();
17773            let task = queue.get(&owner).unwrap();
17774            runner.state.task_instruction = Some(task.instruction.clone());
17775            runner.state.driver_exited = true;
17776            runner.state.save().unwrap();
17777            let questions = crate::ask::Questions::at(home.join("questions"));
17778            let mut q = crate::ask::Question::new(
17779                runner.state.id.clone(),
17780                "base-recovery".into(),
17781                "owner".into(),
17782                "Recover bounded base movement?".into(),
17783                String::new(),
17784                vec!["recover".into()],
17785            );
17786            q.actions.insert(
17787                "recover".into(),
17788                crate::ask::ChoiceAction::RecoverBase {
17789                    run: runner.state.id.clone(),
17790                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
17791                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
17792                },
17793            );
17794            q.routed_task = Some(owner.clone());
17795            q.answer(crate::ask::Answer::Choice("recover".into()))
17796                .unwrap();
17797            questions.put(&mut q).unwrap();
17798            crate::base_recovery_control::recover(
17799                &queue,
17800                &home,
17801                crate::base_recovery_control::Request {
17802                    run: runner.state.id.clone(),
17803                    head: head.clone(),
17804                    actor: "decisions".into(),
17805                    request: q.id.clone(),
17806                    decision: Some((owner.clone(), q.answered_at.unwrap())),
17807                    expected_stop: Some((
17808                        runner.state.base_sync_recovery.stop.clone().unwrap(),
17809                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
17810                    )),
17811                },
17812            )
17813            .await
17814            .unwrap();
17815            if routed {
17816                questions
17817                    .update(&q.id, |q| {
17818                        q.routed_task = Some("another-owner".into());
17819                        Ok(())
17820                    })
17821                    .unwrap();
17822            } else {
17823                let mut task = queue.get(&owner).unwrap();
17824                task.hold_manual(Some("new owner decision".into()));
17825                // Keep the generation to exercise the separate owner-decision binding.
17826                task.status = crate::queue::TaskStatus::Queued;
17827                queue.put(&mut task).unwrap();
17828            }
17829            runner.state = RunState::load(&runner.state.id).unwrap();
17830            runner.sync_to_base().await.unwrap();
17831            let approval = runner
17832                .state
17833                .base_sync_recovery
17834                .authorizations
17835                .last()
17836                .unwrap();
17837            assert!(approval.consumed);
17838            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
17839                "routing"
17840            } else {
17841                "owner decision"
17842            }));
17843            assert_eq!(
17844                runner.state.base_sync.as_ref().unwrap().attempts,
17845                BASE_SYNC_ROUNDS
17846            );
17847            assert_eq!(
17848                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17849                head
17850            );
17851        }
17852    }
17853
17854    #[cfg(unix)]
17855    #[tokio::test]
17856    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
17857        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
17858        if std::env::var_os(CHILD).is_none() {
17859            let home = tempfile::tempdir().unwrap();
17860            let output = std::process::Command::new(std::env::current_exe().unwrap())
17861                .args([
17862                    "--exact",
17863                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
17864                    "--nocapture",
17865                ])
17866                .env(CHILD, "1")
17867                .env("MAGI_HOME", home.path())
17868                .env("MAGI_WORKER_HOME", home.path())
17869                .env("MAGI_WORKER_ID", "abcdef")
17870                .output()
17871                .unwrap();
17872            assert!(
17873                output.status.success()
17874                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17875                "{}\n{}",
17876                String::from_utf8_lossy(&output.stdout),
17877                String::from_utf8_lossy(&output.stderr)
17878            );
17879            return;
17880        }
17881        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
17882        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17883        let home = crate::run::home();
17884        let queue = crate::queue::Queue::open();
17885        let mut owner = queue.get(&task).unwrap();
17886        owner.release_operator("test-release", None);
17887        owner.start(runner.state.id.clone());
17888        queue.put(&mut owner).unwrap();
17889        runner.state.driver_exited = true;
17890        runner.state.task_instruction = Some(owner.instruction.clone());
17891        runner.state.save().unwrap();
17892        let _claim = queue.claim(&task).unwrap();
17893        let reserve = |id: &str| {
17894            let directory = home.join("workers/jobs").join(id);
17895            std::fs::create_dir_all(&directory).unwrap();
17896            let job = crate::worker::Job {
17897                id: id.into(),
17898                sequence: 1,
17899                kind: "task".into(),
17900                key: format!("task:{task}"),
17901                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
17902                generation: "fixture-generation".into(),
17903                version: None,
17904                status: crate::worker::Status::Running,
17905                result: None,
17906                pid: Some(std::process::id()),
17907                created_at: 0,
17908                finished_at: None,
17909            };
17910            std::fs::write(
17911                directory.join("job.json"),
17912                serde_json::to_vec(&job).unwrap(),
17913            )
17914            .unwrap();
17915            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
17916        };
17917        let _own = reserve("abcdef");
17918        let other = reserve("fedcba");
17919        assert!(
17920            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17921                .await
17922                .is_err()
17923        );
17924        assert!(
17925            RunState::load(&runner.state.id)
17926                .unwrap()
17927                .base_sync_recovery
17928                .authorizations
17929                .is_empty()
17930        );
17931        drop(other);
17932        assert!(crate::daemon::is_working_on(
17933            &home,
17934            &runner.state.id,
17935            Timestamp::now()
17936        ));
17937        assert!(
17938            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
17939        );
17940        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17941            .await
17942            .unwrap();
17943        assert!(
17944            RunState::load(&runner.state.id)
17945                .unwrap()
17946                .base_recovery_pending()
17947        );
17948    }
17949
17950    #[cfg(unix)]
17951    #[tokio::test]
17952    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
17953        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17954        let home = crate::run::home();
17955        runner.state.driver_pid = Some(std::process::id());
17956        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
17957        runner.state.driver_exited = false;
17958        runner.state.begin_pass();
17959        runner.state.save().unwrap();
17960        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
17961        driver.record(&runner.state).unwrap();
17962        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
17963        // Preserve the durable claim as if the process died before Drop saved.
17964        drop(driver);
17965        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
17966        assert_eq!(
17967            runner.state.liveness_under(&home, false),
17968            crate::run::Liveness::Dead
17969        );
17970        let queue = crate::queue::Queue::open();
17971        let _claim = queue.claim(&task).unwrap();
17972        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17973            .await
17974            .unwrap();
17975        let disk = RunState::load(&runner.state.id).unwrap();
17976        assert!(!disk.driver_exited);
17977        assert!(disk.base_recovery_pending());
17978    }
17979
17980    #[cfg(unix)]
17981    #[tokio::test]
17982    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
17983        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
17984        if std::env::var_os(CHILD).is_none() {
17985            use std::os::unix::fs::PermissionsExt;
17986            let tmp = tempfile::tempdir().unwrap();
17987            let gh = tmp.path().join("gh");
17988            std::fs::write(&gh, r#"#!/bin/sh
17989case "$1 $2" in
17990  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
17991  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
17992  *) exit 2 ;;
17993esac
17994"#).unwrap();
17995            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
17996            let mut paths = vec![tmp.path().to_path_buf()];
17997            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
17998            let output = std::process::Command::new(std::env::current_exe().unwrap())
17999                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18000                .env(CHILD, "1")
18001                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18002                .env("PATH", std::env::join_paths(paths).unwrap())
18003                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18004                .output().unwrap();
18005            assert!(
18006                output.status.success()
18007                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18008                "{}\n{}",
18009                String::from_utf8_lossy(&output.stdout),
18010                String::from_utf8_lossy(&output.stderr)
18011            );
18012            return;
18013        }
18014        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18015        let repo = runner.state.repo.clone();
18016        git::git(&repo, &["checkout", "main"]).await.unwrap();
18017        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18018        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18019        git::git(&repo, &["checkout", "fix/retained"])
18020            .await
18021            .unwrap();
18022        runner.state.pr = Some(crate::run::PrRecord {
18023            url: "https://example.test/project/pull/1".into(),
18024            number: 1,
18025            state: "open".into(),
18026            checks: "unknown".into(),
18027            round: 0,
18028            rounds: 1,
18029            red_at_merge: Vec::new(),
18030        });
18031        runner.sync_to_base().await.unwrap();
18032        assert_eq!(runner.state.status, RunStatus::Blocked);
18033        assert_eq!(
18034            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18035            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18036        );
18037        assert!(runner.state.base_sync_closure_pending());
18038        assert!(crate::handover::can_resume(&runner.state));
18039        let queue = crate::queue::Queue::open();
18040        assert!(!crate::base_sync_recovery::held_task(
18041            &queue,
18042            &queue.get(&task).unwrap()
18043        ));
18044        assert!(runner.state.authorize_base_sync(&task).is_err());
18045        // Legacy closure stops have no typed stop but must retain the checkpoint.
18046        runner.state.base_sync_recovery.stop = None;
18047        runner.state.status = RunStatus::Voting;
18048        runner.state.gate_ran = true;
18049        runner.state.config.graph.review_rounds = 0;
18050        runner.state.save().unwrap();
18051        assert!(crate::handover::can_resume(&runner.state));
18052        runner.state = RunState::load(&runner.state.id).unwrap();
18053        runner.execute_graph().await.unwrap();
18054        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18055        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18056        assert_eq!(
18057            runner.state.base_sync.as_ref().unwrap().attempts,
18058            BASE_SYNC_ROUNDS
18059        );
18060        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18061        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18062        assert!(runner.state.reviews.is_empty());
18063        assert!(runner.state.gate.is_empty());
18064    }
18065
18066    #[cfg(unix)]
18067    #[tokio::test]
18068    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18069        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18070        runner.state.driver_exited = true;
18071        runner.state.save().unwrap();
18072        let home = crate::run::home();
18073        let queue = crate::queue::Queue::open();
18074        let _claim = queue.claim(&task).unwrap();
18075        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18076        assert!(
18077            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18078                .await
18079                .is_err()
18080        );
18081        drop(lease);
18082        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18083        assert!(
18084            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18085                .await
18086                .is_err()
18087        );
18088        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18089        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18090            .await
18091            .unwrap();
18092        let disk = RunState::load(&runner.state.id).unwrap();
18093        assert!(disk.base_recovery_pending());
18094        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18095        assert!(
18096            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18097                .await
18098                .is_err()
18099        );
18100        assert_eq!(
18101            RunState::load(&runner.state.id)
18102                .unwrap()
18103                .base_sync_recovery
18104                .authorizations
18105                .len(),
18106            1
18107        );
18108        let mut owner = queue.get(&task).unwrap();
18109        owner.runs.push("20260101-000000-ffff".into());
18110        queue.put(&mut owner).unwrap();
18111        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18112            .await
18113            .unwrap_err();
18114        assert!(error.to_string().contains("run task ownership changed"));
18115    }
18116
18117    #[cfg(unix)]
18118    #[tokio::test]
18119    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18120        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18121        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18122        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18123        legacy["status"] = serde_json::json!("voting");
18124        runner.state = serde_json::from_value(legacy).unwrap();
18125        runner.state.save().unwrap();
18126        for _ in 0..3 {
18127            runner.execute_graph().await.unwrap();
18128            assert_eq!(runner.state.status, RunStatus::Blocked);
18129            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18130            assert!(!crate::handover::can_resume(&runner.state));
18131            assert_eq!(
18132                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18133                head
18134            );
18135            assert!(runner.state.reviews.is_empty());
18136            assert!(!runner.state.gate_ran);
18137        }
18138        let notice = crate::notices::run_ended(&runner.state).unwrap();
18139        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18140        runner.state.begin_pass();
18141        runner.state.status = RunStatus::Voting;
18142        runner.deliberate().await.unwrap();
18143        runner.vote().await.unwrap();
18144        runner.finish_after_tally().await.unwrap();
18145        assert_eq!(runner.state.status, RunStatus::Blocked);
18146        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18147        assert_eq!(
18148            crate::notices::run_ended(&runner.state).unwrap().since,
18149            notice.since
18150        );
18151    }
18152
18153    #[cfg(unix)]
18154    #[tokio::test]
18155    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18156        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18157        for detail in [
18158            "fix/retained conflicts with origin/main and did not rebase: conflict",
18159            "rebased fix/retained locally but origin refused the push",
18160            "unknown failure",
18161        ] {
18162            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18163            runner.state.record_base_sync_stop(&head);
18164            assert!(runner.state.authorize_base_sync(&task).is_err());
18165            runner.state.status = RunStatus::Voting;
18166            runner.execute_graph().await.unwrap();
18167            assert_eq!(runner.state.status, RunStatus::Blocked);
18168            assert!(!crate::handover::can_resume(&runner.state));
18169            assert_eq!(
18170                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18171                head
18172            );
18173        }
18174    }
18175
18176    #[cfg(unix)]
18177    #[tokio::test]
18178    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18179        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18180        runner.state.authorize_base_sync(&task).unwrap();
18181        assert!(runner.state.consume_base_recovery(&head));
18182        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18183        runner.state.reserve_base_operation(&head, &tip);
18184        runner.state.save().unwrap();
18185        runner.state = RunState::load(&runner.state.id).unwrap();
18186        assert!(!runner.state.consume_base_recovery(&head));
18187        runner.sync_to_base().await.unwrap();
18188        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18189        assert_eq!(runner.state.base_episode_used(), 1);
18190        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18191        assert!(
18192            runner
18193                .state
18194                .base_sync_recovery
18195                .operations
18196                .last()
18197                .unwrap()
18198                .finished
18199        );
18200        assert!(!runner.state.base_sync_blocked());
18201        runner.sync_to_base().await.unwrap();
18202        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18203    }
18204
18205    #[cfg(unix)]
18206    #[tokio::test]
18207    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18208        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18209        // Both historical diagnostic spellings retain an exhaustion identity.
18210        let original = runner
18211            .state
18212            .base_sync
18213            .as_ref()
18214            .unwrap()
18215            .conflict
18216            .clone()
18217            .unwrap();
18218        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18219            original
18220                .replace("synchronization(s)", "rebase(s)")
18221                .replace("synchronizing", "rebasing"),
18222        );
18223        runner.state.base_sync_recovery = Default::default();
18224        runner.state.record_base_sync_stop(&head);
18225        assert_eq!(
18226            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18227            crate::base_sync_recovery::StopKind::Exhausted
18228        );
18229        runner.state.authorize_base_sync(&task).unwrap();
18230        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18231        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18232            .as_object_mut()
18233            .unwrap();
18234        auth.remove("interval");
18235        auth.remove("scope");
18236        runner.state = serde_json::from_value(legacy).unwrap();
18237        assert!(runner.state.consume_base_recovery(&head));
18238        assert_eq!(runner.state.base_episode_used(), 3);
18239        runner.sync_to_base().await.unwrap();
18240        assert_eq!(runner.state.base_episode_used(), 4);
18241        runner.state.resource_block = Some(crate::run::ResourceBlock {
18242            node: "gate".into(),
18243            kind: "cache".into(),
18244            detail: "legacy wait".into(),
18245            at: Timestamp::now(),
18246            cause: crate::run::ResourceBlockCause::Unrecorded,
18247        });
18248        runner.state.save().unwrap();
18249        assert!(
18250            runner
18251                .state
18252                .base_sync_recovery
18253                .episodes
18254                .last()
18255                .unwrap()
18256                .boundary
18257                .is_none()
18258        );
18259        runner.state.resource_block = None;
18260        advance_base_fixture(&runner).await;
18261        runner.sync_to_base().await.unwrap();
18262        assert!(runner.state.base_sync_blocked());
18263        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18264    }
18265
18266    #[cfg(unix)]
18267    async fn advance_base_fixture(runner: &Runner) {
18268        let repo = &runner.state.repo;
18269        for args in [
18270            vec!["checkout", "main"],
18271            vec!["commit", "--allow-empty", "-m", "base advanced"],
18272            vec!["push", "origin", "main"],
18273            vec!["checkout", "fix/retained"],
18274        ] {
18275            git::git(repo, &args).await.unwrap();
18276        }
18277    }
18278
18279    #[cfg(unix)]
18280    fn fresh_base_interval_fixture(runner: &mut Runner) {
18281        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18282        runner.state.base_sync.as_mut().unwrap().conflict = None;
18283        runner.state.base_sync_recovery = Default::default();
18284        runner.state.status = RunStatus::Voting;
18285    }
18286
18287    #[cfg(unix)]
18288    #[tokio::test]
18289    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18290        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18291        fresh_base_interval_fixture(&mut runner);
18292        runner.state.begin_pass();
18293        runner.sync_to_base().await.unwrap();
18294        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18295        runner.state.resource_block = Some(crate::run::ResourceBlock {
18296            node: "gate".into(),
18297            kind: "build cache".into(),
18298            detail: "busy".into(),
18299            at: Timestamp::now(),
18300            cause: crate::run::ResourceBlockCause::Timeout {
18301                waited_secs: 1,
18302                limit_secs: 1,
18303            },
18304        });
18305        runner.state.save().unwrap();
18306        let queue = crate::queue::Queue::open();
18307        let mut owner = queue.get(&task).unwrap();
18308        runner.state.task_instruction = Some(owner.instruction.clone());
18309        owner.release_operator("fixture-owner", None);
18310        queue.put(&mut owner).unwrap();
18311        let approval = owner.resumption.clone().unwrap();
18312        runner.state.resource_block = None;
18313        runner.state.save().unwrap();
18314        runner.state = RunState::load(&runner.state.id).unwrap();
18315        advance_base_fixture(&runner).await;
18316        runner.sync_to_base().await.unwrap();
18317        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18318        assert_eq!(runner.state.base_episode_used(), 1);
18319        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18320        assert!(
18321            runner.state.base_sync_recovery.episodes[0]
18322                .boundary
18323                .as_ref()
18324                .unwrap()
18325                .consumed
18326        );
18327        assert!(
18328            !runner
18329                .state
18330                .renew_base_episode(&task, &approval, &head, "base")
18331        );
18332        for _ in 0..3 {
18333            owner.release_operator("fixture-owner", None);
18334            queue.put(&mut owner).unwrap();
18335            runner.state = RunState::load(&runner.state.id).unwrap();
18336            runner.state.begin_pass();
18337            runner.sync_to_base().await.unwrap();
18338            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18339            assert_eq!(runner.state.base_episode_used(), 1);
18340        }
18341        runner.state.resource_block = Some(crate::run::ResourceBlock {
18342            node: "gate".into(),
18343            kind: "disk pressure".into(),
18344            detail: "free space required".into(),
18345            at: Timestamp::now(),
18346            cause: crate::run::ResourceBlockCause::Other,
18347        });
18348        runner.state.end_pass_parked(ParkCause::Interrupt {
18349            reason: "disk pressure".into(),
18350        });
18351        runner.state.save().unwrap();
18352        owner.release_operator("fixture-owner-after-disk", None);
18353        queue.put(&mut owner).unwrap();
18354        runner.state.resource_block = None;
18355        advance_base_fixture(&runner).await;
18356        runner.sync_to_base().await.unwrap();
18357        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18358        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18359        assert_eq!(runner.state.base_episode_used(), 1);
18360        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18361    }
18362
18363    #[cfg(unix)]
18364    #[tokio::test]
18365    async fn base_recovery_continuous_advancement_stops_at_four() {
18366        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18367        fresh_base_interval_fixture(&mut runner);
18368        for spent in 1..=BASE_SYNC_ROUNDS {
18369            runner.sync_to_base().await.unwrap();
18370            assert!(!runner.state.base_sync_blocked());
18371            assert_eq!(runner.state.base_episode_used(), spent);
18372            advance_base_fixture(&runner).await;
18373        }
18374        runner.sync_to_base().await.unwrap();
18375        assert_eq!(
18376            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18377            crate::base_sync_recovery::StopKind::Exhausted
18378        );
18379        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18380        assert!(stop.unverified_sync);
18381        let action = runner.state.base_sync_next_action();
18382        assert!(action.contains("never reached its gate"));
18383        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18384        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18385        runner.state = RunState::load(&runner.state.id).unwrap();
18386        runner.sync_to_base().await.unwrap();
18387        assert_eq!(runner.state.base_episode_used(), 4);
18388        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18389    }
18390
18391    #[cfg(unix)]
18392    #[tokio::test]
18393    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18394        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18395        runner.state.ensure_base_episode();
18396        // Verification progress alone is not evidence of a successful sync.
18397        runner.state.record_base_progress(&head);
18398        runner.state.base_sync_recovery.stop = None;
18399        runner.state.record_base_sync_stop(&head);
18400        assert!(
18401            !runner
18402                .state
18403                .base_sync_recovery
18404                .stop
18405                .as_ref()
18406                .unwrap()
18407                .unverified_sync
18408        );
18409
18410        runner.state.finish_base_operation(Some(&head));
18411        // A gate for another head cannot verify this synchronization.
18412        runner.state.gate_ran = true;
18413        runner.state.gate_head = Some("older-head".into());
18414        runner.state.base_sync_recovery.stop = None;
18415        runner.state.record_base_sync_stop(&head);
18416        runner.state.save().unwrap();
18417        runner.state = RunState::load(&runner.state.id).unwrap();
18418        assert!(
18419            runner
18420                .state
18421                .base_sync_recovery
18422                .stop
18423                .as_ref()
18424                .unwrap()
18425                .unverified_sync
18426        );
18427
18428        runner.state.gate_head = Some(head.clone());
18429        runner.state.base_sync_recovery.stop = None;
18430        runner.state.record_base_sync_stop(&head);
18431        assert!(
18432            !runner
18433                .state
18434                .base_sync_recovery
18435                .stop
18436                .as_ref()
18437                .unwrap()
18438                .unverified_sync
18439        );
18440        assert!(
18441            !runner
18442                .state
18443                .base_sync_next_action()
18444                .contains("never reached its gate")
18445        );
18446
18447        // Historical records cannot establish the missing synchronization evidence.
18448        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18449        legacy["base_sync_recovery"]["stop"]
18450            .as_object_mut()
18451            .unwrap()
18452            .remove("unverified_sync");
18453        legacy["base_sync_recovery"]["episodes"][0]
18454            .as_object_mut()
18455            .unwrap()
18456            .remove("last_sync_head");
18457        runner.state = serde_json::from_value(legacy).unwrap();
18458        assert!(
18459            !runner
18460                .state
18461                .base_sync_recovery
18462                .stop
18463                .as_ref()
18464                .unwrap()
18465                .unverified_sync
18466        );
18467        assert!(
18468            runner.state.base_sync_recovery.episodes[0]
18469                .last_sync_head
18470                .is_none()
18471        );
18472    }
18473
18474    #[cfg(unix)]
18475    #[tokio::test]
18476    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18477        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18478        runner.state.authorize_base_sync(&task).unwrap();
18479        assert!(
18480            runner
18481                .state
18482                .base_sync_next_action()
18483                .contains("Approval recorded")
18484        );
18485        assert!(
18486            runner
18487                .state
18488                .base_sync_next_action()
18489                .contains("4/4 in episode 0, 4 lifetime")
18490        );
18491        assert!(runner.state.consume_base_recovery(&head));
18492        assert!(
18493            runner
18494                .state
18495                .base_sync_next_action()
18496                .contains("0/4 in episode 1, 4 lifetime")
18497        );
18498    }
18499
18500    #[cfg(unix)]
18501    #[tokio::test]
18502    async fn base_recovery_changed_head_invalidates_without_spending() {
18503        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18504        runner.state.authorize_base_sync(&task).unwrap();
18505        git::git(
18506            &runner.state.repo,
18507            &["commit", "--allow-empty", "-m", "external head change"],
18508        )
18509        .await
18510        .unwrap();
18511        runner.sync_to_base().await.unwrap();
18512        let a = runner
18513            .state
18514            .base_sync_recovery
18515            .authorizations
18516            .last()
18517            .unwrap();
18518        assert!(a.consumed);
18519        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18520        runner.state = RunState::load(&runner.state.id).unwrap();
18521        assert!(
18522            runner
18523                .state
18524                .base_sync_next_action()
18525                .contains("Approval invalidated")
18526        );
18527        assert!(!runner.state.base_recovery_pending());
18528        assert!(runner.state.base_sync_blocked());
18529        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18530    }
18531
18532    #[cfg(unix)]
18533    #[tokio::test]
18534    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18535        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18536        runner.state.driver_exited = true;
18537        runner.state.save().unwrap();
18538        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18539            .await
18540            .unwrap();
18541        runner.state = RunState::load(&runner.state.id).unwrap();
18542        advance_base_fixture(&runner).await;
18543        runner.sync_to_base().await.unwrap();
18544        let a = runner
18545            .state
18546            .base_sync_recovery
18547            .authorizations
18548            .last()
18549            .unwrap();
18550        assert!(
18551            a.consumed
18552                && a.invalidated
18553                    .as_deref()
18554                    .unwrap()
18555                    .contains("fetched base changed")
18556        );
18557        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18558        assert_eq!(
18559            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18560            head
18561        );
18562        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18563            .await
18564            .unwrap();
18565        runner.state = RunState::load(&runner.state.id).unwrap();
18566        runner.sync_to_base().await.unwrap();
18567        assert!(!runner.state.base_sync_blocked());
18568        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18569    }
18570
18571    #[cfg(unix)]
18572    #[tokio::test]
18573    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18574        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18575        runner.state.authorize_base_sync(&task).unwrap();
18576        assert!(runner.state.consume_base_recovery(&head));
18577        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18578        runner.state.reserve_base_operation(&head, &tip);
18579        runner.state.save().unwrap();
18580        let scratch = runner.state.dir().join("base-sync");
18581        assert_eq!(
18582            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18583                .await
18584                .unwrap(),
18585            crate::rebase::Rebased::Applied
18586        );
18587        runner.state = RunState::load(&runner.state.id).unwrap();
18588        runner.sync_to_base().await.unwrap();
18589        assert!(
18590            runner
18591                .state
18592                .base_sync_recovery
18593                .operations
18594                .last()
18595                .unwrap()
18596                .finished
18597        );
18598        assert_eq!(runner.state.base_episode_used(), 1);
18599        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18600        assert!(!runner.state.base_sync_blocked());
18601    }
18602
18603    #[cfg(unix)]
18604    #[tokio::test]
18605    async fn base_recovery_crash_preserves_untracked_files() {
18606        for ignored in [false, true] {
18607            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18608            runner.state.authorize_base_sync(&task).unwrap();
18609            assert!(runner.state.consume_base_recovery(&head));
18610            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18611            runner.state.reserve_base_operation(&head, &tip);
18612            runner.state.save().unwrap();
18613            let scratch = runner.state.dir().join("base-sync");
18614            assert_eq!(
18615                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18616                    .await
18617                    .unwrap(),
18618                crate::rebase::Rebased::Applied
18619            );
18620            let repo = &runner.state.repo;
18621            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18622            assert_ne!(result, head);
18623            if ignored {
18624                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18625                    .await
18626                    .unwrap();
18627                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18628            }
18629            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18630            assert!(
18631                git::git_raw(repo, &["diff", "--quiet", &head])
18632                    .await
18633                    .unwrap()
18634                    .ok()
18635            );
18636            // Resume after the branch moved, before its checkout was reset.
18637            runner.state = RunState::load(&runner.state.id).unwrap();
18638            runner.sync_to_base().await.unwrap();
18639            assert!(runner.state.base_sync_blocked());
18640            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18641            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18642            assert_eq!(
18643                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18644                result
18645            );
18646            assert_eq!(
18647                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18648                "retained work\n"
18649            );
18650            assert!(
18651                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18652                    .await
18653                    .unwrap()
18654                    .ok()
18655            );
18656        }
18657    }
18658
18659    #[cfg(unix)]
18660    #[tokio::test]
18661    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18662        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18663        runner.state.authorize_base_sync(&task).unwrap();
18664        assert!(runner.state.consume_base_recovery(&head));
18665        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18666        runner.state.reserve_base_operation(&head, &tip);
18667        runner.state.save().unwrap();
18668        let scratch = runner.state.dir().join("base-sync");
18669        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18670            .await
18671            .unwrap();
18672        git::sync_to_head(&runner.state.repo).await.unwrap();
18673        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18674        git::git(&runner.state.repo, &["add", "foreign"])
18675            .await
18676            .unwrap();
18677        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18678            .await
18679            .unwrap();
18680        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18681        runner.state = RunState::load(&runner.state.id).unwrap();
18682        runner.sync_to_base().await.unwrap();
18683        assert!(runner.state.base_sync_blocked());
18684        assert!(
18685            !runner
18686                .state
18687                .base_sync_recovery
18688                .operations
18689                .last()
18690                .unwrap()
18691                .finished
18692        );
18693        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18694        assert_eq!(
18695            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18696            foreign_head
18697        );
18698    }
18699
18700    #[cfg(unix)]
18701    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18702    {
18703        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18704        fresh_base_interval_fixture(&mut runner);
18705        let repo = &runner.state.repo;
18706        git::git(repo, &["checkout", "main"]).await.unwrap();
18707        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18708        git::git(repo, &["add", "retained"]).await.unwrap();
18709        git::git(repo, &["commit", "-m", "upstream retained change"])
18710            .await
18711            .unwrap();
18712        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18713        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18714        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18715        let scratch = runner.state.dir().join("base-sync");
18716        assert!(matches!(
18717            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18718                .await
18719                .unwrap(),
18720            git::RebaseStart::Conflicted(_)
18721        ));
18722        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18723            agent: "fixture".into(),
18724            paths: vec!["retained".into()],
18725            from: Some(head.clone()),
18726            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18727            index_outside: None,
18728            finished: false,
18729            error: None,
18730            launcher: None,
18731            infra: None,
18732            outage: None,
18733        });
18734        (tmp, runner, head, tip, scratch)
18735    }
18736
18737    #[cfg(unix)]
18738    #[tokio::test]
18739    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18740        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18741        // A resource stop from before reservations existed, with resolved
18742        // contents left for the launcher's ordinary staging continuation.
18743        std::fs::write(
18744            scratch.join("retained"),
18745            "upstream and retained resolution\n",
18746        )
18747        .unwrap();
18748        runner.state.resource_block = Some(crate::run::ResourceBlock {
18749            node: "rebase".into(),
18750            kind: "repository coordination".into(),
18751            detail: "busy".into(),
18752            at: Timestamp::now(),
18753            cause: crate::run::ResourceBlockCause::Other,
18754        });
18755        runner.state.save().unwrap();
18756        // Advance the remote without moving either checkout participating
18757        // in the standing rebase.
18758        let newer = git::git(
18759            &runner.state.repo,
18760            &[
18761                "commit-tree",
18762                "main^{tree}",
18763                "-p",
18764                "main",
18765                "-m",
18766                "base advanced during wait",
18767            ],
18768        )
18769        .await
18770        .unwrap();
18771        git::git(
18772            &runner.state.repo,
18773            &[
18774                "push",
18775                "origin",
18776                &format!("{}:refs/heads/main", newer.trim()),
18777            ],
18778        )
18779        .await
18780        .unwrap();
18781        runner.state = RunState::load(&runner.state.id).unwrap();
18782        runner.state.resource_block = None;
18783        runner.sync_to_base().await.unwrap();
18784        assert!(!runner.state.base_sync_blocked());
18785        let op = &runner.state.base_sync_recovery.operations[0];
18786        assert_eq!(op.head, head);
18787        assert_eq!(op.tip, tip);
18788        assert!(op.finished);
18789        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18790        assert_eq!(runner.state.rebase_fixes.len(), 1);
18791        let latest = git::rev_parse(&runner.state.repo, "origin/main")
18792            .await
18793            .unwrap();
18794        assert_ne!(latest, tip);
18795        runner.state = RunState::load(&runner.state.id).unwrap();
18796        runner.sync_to_base().await.unwrap();
18797        assert!(!runner.state.base_sync_blocked());
18798        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
18799        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
18800        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18801    }
18802
18803    #[cfg(unix)]
18804    #[tokio::test]
18805    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
18806        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18807        runner.state.reserve_base_operation(&head, &tip);
18808        runner.state.save().unwrap();
18809        std::fs::write(
18810            scratch.join("retained"),
18811            "upstream and retained resolution\n",
18812        )
18813        .unwrap();
18814        git::git(&scratch, &["add", "retained"]).await.unwrap();
18815        git::git(
18816            &scratch,
18817            &["-c", "core.editor=true", "rebase", "--continue"],
18818        )
18819        .await
18820        .unwrap();
18821        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18822        assert!(
18823            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18824                .await
18825                .unwrap()
18826                .is_empty()
18827        );
18828        assert_eq!(
18829            crate::rebase::finish(
18830                &mut runner.state,
18831                &scratch,
18832                "fix/retained",
18833                &head,
18834                &tip,
18835                &["retained".into()],
18836                ""
18837            )
18838            .await
18839            .unwrap(),
18840            crate::rebase::Rebased::Applied
18841        );
18842        assert!(!scratch.exists());
18843        // Simulate losing the caller before finish_base_operation/save.
18844        runner.state = RunState::load(&runner.state.id).unwrap();
18845        let op = &runner.state.base_sync_recovery.operations[0];
18846        assert!(!op.finished);
18847        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
18848        runner.sync_to_base().await.unwrap();
18849        assert!(!runner.state.base_sync_blocked());
18850        assert!(runner.state.base_sync_recovery.operations[0].finished);
18851        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18852        assert_eq!(runner.state.rebase_fixes.len(), 1);
18853        let winner = runner.state.winner().unwrap().clone();
18854        let wait = runner.repository_wait();
18855        assert!(
18856            verify_current_head(&mut runner.state, &winner, &wait)
18857                .await
18858                .unwrap()
18859        );
18860        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18861    }
18862
18863    #[cfg(unix)]
18864    #[tokio::test]
18865    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
18866        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
18867            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18868            runner.state.reserve_base_operation(&head, &tip);
18869            runner.state.save().unwrap();
18870            std::fs::write(
18871                scratch.join("retained"),
18872                "upstream and retained resolution\n",
18873            )
18874            .unwrap();
18875            git::git(&scratch, &["add", "retained"]).await.unwrap();
18876            git::git(
18877                &scratch,
18878                &["-c", "core.editor=true", "rebase", "--continue"],
18879            )
18880            .await
18881            .unwrap();
18882            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18883            assert!(!git::rebase_in_progress(&scratch).await);
18884            assert!(
18885                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18886                    .await
18887                    .unwrap()
18888                    .is_empty()
18889            );
18890            match damage {
18891                Some("record") => {
18892                    let path =
18893                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
18894                            .await
18895                            .unwrap();
18896                    std::fs::write(scratch.join(path), "").unwrap();
18897                }
18898                Some("foreign") => {
18899                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
18900                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
18901                    git::git(&scratch, &["commit", "-m", "foreign work"])
18902                        .await
18903                        .unwrap();
18904                }
18905                Some("dirty") => {
18906                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
18907                }
18908                _ => {}
18909            }
18910            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18911            // Crash immediately after Git continuation, before finish runs.
18912            runner.state = RunState::load(&runner.state.id).unwrap();
18913            assert!(
18914                runner.state.base_sync_recovery.operations[0]
18915                    .validated_head
18916                    .is_none()
18917            );
18918            runner.sync_to_base().await.unwrap();
18919            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18920            assert_eq!(runner.state.base_episode_used(), 1);
18921            assert_eq!(runner.state.rebase_fixes.len(), 1);
18922            assert_eq!(
18923                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18924                retained_head
18925            );
18926            if damage.is_some() {
18927                assert!(runner.state.base_sync_blocked());
18928                assert!(scratch.exists());
18929                assert!(!runner.state.base_sync_recovery.operations[0].finished);
18930                assert!(
18931                    runner.state.base_sync_recovery.operations[0]
18932                        .validated_head
18933                        .is_none()
18934                );
18935            } else {
18936                assert!(!runner.state.base_sync_blocked());
18937                assert!(!scratch.exists());
18938                assert!(runner.state.base_sync_recovery.operations[0].finished);
18939                assert_eq!(
18940                    runner.state.base_sync_recovery.operations[0]
18941                        .validated_head
18942                        .as_deref(),
18943                    Some(result.as_str())
18944                );
18945                let winner = runner.state.winner().unwrap().clone();
18946                let wait = runner.repository_wait();
18947                assert!(
18948                    verify_current_head(&mut runner.state, &winner, &wait)
18949                        .await
18950                        .unwrap()
18951                );
18952                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18953                runner.state = RunState::load(&runner.state.id).unwrap();
18954                runner.sync_to_base().await.unwrap();
18955                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18956            }
18957        }
18958    }
18959
18960    #[cfg(unix)]
18961    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
18962        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18963        // This is an ordinary gate stop, not an authorized base-budget recovery.
18964        runner.state.prep_complete = Some(true);
18965        runner.state.base_sync = None;
18966        runner.state.base_sync_recovery = Default::default();
18967        runner.state.config.graph.gate_fix_rounds = 1;
18968        let mut review = review_round(true, 0, 1, 1, false, true);
18969        review.head = head.clone();
18970        review.verified_head = Some(head.clone());
18971        runner.state.reviews = vec![review];
18972        runner.state.gate = vec![CommandOutcome {
18973            command: "old gate".into(),
18974            code: Some(1),
18975            output_tail: "old failure".into(),
18976            duration_ms: 0,
18977            resource_blocked: false,
18978            ..Default::default()
18979        }];
18980        runner.state.gate_head = Some(head.clone());
18981        runner.state.gate_ran = true;
18982        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
18983            agent: "fixture".into(),
18984            failed: runner.state.gate.clone(),
18985            notes: "spent".into(),
18986            committed: false,
18987            error: None,
18988        }];
18989        runner.state.land_approval = Some(crate::run::LandApproval {
18990            question: "old approval".into(),
18991            head: head.clone(),
18992        });
18993        runner.state.status = RunStatus::Blocked;
18994        (tmp, runner, head)
18995    }
18996
18997    #[cfg(unix)]
18998    #[tokio::test]
18999    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19000        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19001            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19002            let phases = tmp.path().join("phases");
19003            runner.state.config.verify.e2e = vec![format!(
19004                "echo e2e >> '{}'; {}",
19005                phases.display(),
19006                if e2e_ok {
19007                    "true"
19008                } else {
19009                    "echo new-e2e-failure; false"
19010                }
19011            )];
19012            runner.state.config.verify.gate = vec![format!(
19013                "echo gate >> '{}'; {}",
19014                phases.display(),
19015                if gate_ok {
19016                    "true"
19017                } else {
19018                    "echo new-gate-failure; false"
19019                }
19020            )];
19021            runner.state.save().unwrap();
19022            runner.state = RunState::load(&runner.state.id).unwrap();
19023            runner.sync_to_base().await.unwrap();
19024            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19025            assert_ne!(head, old);
19026            // Reentry after Git updated but before verification was invalidated.
19027            runner.state = RunState::load(&runner.state.id).unwrap();
19028            runner.execute_graph().await.unwrap();
19029            assert_eq!(runner.state.gate_fixes.len(), 1);
19030            assert_eq!(runner.state.reviews.len(), 1);
19031            assert_eq!(runner.state.reviews[0].head, old);
19032            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19033            assert_eq!(runner.state.verification_history.len(), 1);
19034            let history = &runner.state.verification_history[0];
19035            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19036            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19037            assert!(history.archived_at.is_some());
19038            assert_eq!(history.fixes_spent, Some(1));
19039            assert_eq!(history.gate[0].output_tail, "old failure");
19040            let archive_events: Vec<_> = runner
19041                .state
19042                .events
19043                .iter()
19044                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19045                .collect();
19046            assert_eq!(archive_events.len(), 1);
19047            assert!(archive_events[0].message.contains(&short(&old)));
19048            assert!(archive_events[0].message.contains(&short(&head)));
19049            assert!(
19050                archive_events[0]
19051                    .message
19052                    .contains("1 gate-fix round(s) already spent stay spent")
19053            );
19054            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19055            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19056            if e2e_ok {
19057                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19058                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19059            } else {
19060                assert!(!runner.state.gate_ran);
19061            }
19062            assert_eq!(
19063                runner.state.status,
19064                if e2e_ok && gate_ok {
19065                    RunStatus::Ready
19066                } else {
19067                    RunStatus::Blocked
19068                }
19069            );
19070            if !e2e_ok || !gate_ok {
19071                let cause = runner.state.verification_blocking_cause().unwrap();
19072                assert!(cause.contains(&head));
19073                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19074                // A later successful progress event must not become the cause.
19075                runner.state.event("land", "rebased successfully");
19076                let notice = crate::notices::run_ended(&runner.state).unwrap();
19077                assert!(!format!("{notice:?}").contains("rebased successfully"));
19078                assert!(runner.state.merge.is_none());
19079            }
19080            let before = std::fs::read_to_string(&phases).unwrap();
19081            runner.state.save().unwrap();
19082            runner.state = RunState::load(&runner.state.id).unwrap();
19083            runner.review_loop().await.unwrap();
19084            runner.gate().await.unwrap();
19085            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19086            assert_eq!(runner.state.verification_history.len(), 1);
19087            let history = &runner.state.verification_history[0];
19088            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19089            assert!(history.archived_at.is_some());
19090            assert_eq!(history.fixes_spent, Some(1));
19091        }
19092    }
19093
19094    #[cfg(unix)]
19095    #[tokio::test]
19096    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19097        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19098        let marker = tmp.path().join("gate-ran");
19099        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19100        runner.review_loop().await.unwrap();
19101        runner.gate().await.unwrap();
19102        assert_eq!(runner.state.status, RunStatus::Blocked);
19103        assert!(!marker.exists());
19104        assert!(runner.state.verification_history.is_empty());
19105        runner.state.gate_head = None;
19106        runner.gate().await.unwrap();
19107        assert!(marker.exists());
19108        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19109        assert_eq!(runner.state.verification_history.len(), 1);
19110        assert_eq!(runner.state.gate_fixes.len(), 1);
19111    }
19112
19113    #[cfg(unix)]
19114    #[tokio::test]
19115    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19116        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19117        runner.sync_to_base().await.unwrap();
19118        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19119        runner.state.reconcile_verification_head(&head);
19120        // Both crash-before-command and resource wait are unresolved evidence.
19121        for outcomes in [
19122            Vec::new(),
19123            vec![CommandOutcome {
19124                command: "true".into(),
19125                code: None,
19126                output_tail: "cache unavailable".into(),
19127                duration_ms: 0,
19128                resource_blocked: true,
19129                ..Default::default()
19130            }],
19131        ] {
19132            runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19133                head: head.clone(),
19134                passed: false,
19135                outcomes,
19136            });
19137            runner.state.gate_ran = false;
19138            runner.state.gate.clear();
19139            runner.state.save().unwrap();
19140            runner.state = RunState::load(&runner.state.id).unwrap();
19141            runner.merge().await.unwrap();
19142            assert!(runner.state.merge.is_none());
19143            runner.review_loop().await.unwrap();
19144            runner.gate().await.unwrap();
19145            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19146            assert!(runner.state.gate_allows_progress());
19147            assert_eq!(runner.state.gate_fixes.len(), 1);
19148            assert!(runner.state.merge.is_none());
19149        }
19150        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19151        git::git(
19152            &runner.state.repo,
19153            &["commit", "--allow-empty", "-m", "external update"],
19154        )
19155        .await
19156        .unwrap();
19157        runner.merge().await.unwrap();
19158        assert!(runner.state.merge.is_none());
19159        assert_eq!(runner.state.status, RunStatus::Blocked);
19160    }
19161
19162    #[cfg(unix)]
19163    #[tokio::test]
19164    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19165        for waiting_on_gate in [false, true] {
19166            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19167            runner.sync_to_base().await.unwrap();
19168            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19169            runner.state.reconcile_verification_head(&head);
19170            if waiting_on_gate {
19171                runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19172                    head: head.clone(),
19173                    passed: true,
19174                    outcomes: Vec::new(),
19175                });
19176            }
19177            let cache = tmp.path().join("cache");
19178            runner.state.config.verify.e2e =
19179                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19180            runner.state.config.verify.gate = vec!["true".into()];
19181            runner.state.config.graph.timeout_resource_wait = 1;
19182            let owner =
19183                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19184            let guard =
19185                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19186                    crate::cache::AcquireOutcome::Acquired(g) => g,
19187                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19188                };
19189            runner.review_loop().await.unwrap();
19190            runner.gate().await.unwrap();
19191            assert!(!runner.state.gate_ran);
19192            assert_eq!(runner.state.gate_fixes.len(), 1);
19193            assert!(runner.state.resource_block.is_some());
19194            runner.merge().await.unwrap();
19195            assert!(runner.state.merge.is_none());
19196            drop(guard);
19197            runner.state = RunState::load(&runner.state.id).unwrap();
19198            // The driver clears the previous pass's resource stop on resume.
19199            runner.state.resource_block = None;
19200            runner.review_loop().await.unwrap();
19201            runner.gate().await.unwrap();
19202            assert!(runner.state.gate_allows_progress());
19203            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19204            assert_eq!(runner.state.gate_fixes.len(), 1);
19205        }
19206    }
19207
19208    #[cfg(unix)]
19209    #[tokio::test]
19210    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19211        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19212        runner.sync_to_base().await.unwrap();
19213        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19214        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19215        // Verification passes before pre_gate and fails on the mechanically changed head.
19216        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19217        runner.review_loop().await.unwrap();
19218        runner.gate().await.unwrap();
19219        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19220        assert_ne!(before, after);
19221        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19222        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19223        assert!(!runner.state.gate_allows_progress());
19224        runner.merge().await.unwrap();
19225        assert!(runner.state.merge.is_none());
19226        assert!(
19227            runner
19228                .state
19229                .verification_history
19230                .iter()
19231                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19232        );
19233
19234        // An incomplete review is still an independent hold on a changed head.
19235        runner.state.reviews[0].clean = false;
19236        runner.state.reviews[0].answered = 0;
19237        runner.state.config.verify.e2e = vec!["true".into()];
19238        runner.review_loop().await.unwrap();
19239        runner.gate().await.unwrap();
19240        runner.merge().await.unwrap();
19241        assert_eq!(runner.state.status, RunStatus::Blocked);
19242        assert!(runner.state.merge.is_none());
19243        assert!(
19244            runner
19245                .state
19246                .verification_blocking_cause()
19247                .unwrap()
19248                .contains("review blocked")
19249        );
19250    }
19251
19252    #[cfg(unix)]
19253    #[tokio::test]
19254    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19255        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19256        runner.state.gate_head = None;
19257        runner.state.config.verify.gate =
19258            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19259        runner.review_loop().await.unwrap();
19260        runner.gate().await.unwrap();
19261        assert_ne!(
19262            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19263            old
19264        );
19265        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19266        assert!(!runner.state.gate_allows_progress());
19267        assert_eq!(runner.state.status, RunStatus::Blocked);
19268        runner.merge().await.unwrap();
19269        assert!(runner.state.merge.is_none());
19270    }
19271
19272    #[cfg(unix)]
19273    #[tokio::test]
19274    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19275        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19276        let mut old_review = review_round(true, 0, 1, 1, false, true);
19277        old_review.head = head.clone();
19278        old_review.verified_head = Some(head.clone());
19279        runner.state.reviews = vec![old_review];
19280        runner.state.gate = vec![CommandOutcome {
19281            command: "old gate".into(),
19282            code: None,
19283            output_tail: "timed out after 2400s".into(),
19284            duration_ms: 2_400_000,
19285            resource_blocked: false,
19286            ..Default::default()
19287        }];
19288        runner.state.gate_ran = true;
19289        runner.state.gate_head = Some(head.clone());
19290        runner.state.land_approval = Some(crate::run::LandApproval {
19291            question: "old-head-approval".into(),
19292            head: head.clone(),
19293        });
19294        runner.state.authorize_base_sync(&task).unwrap();
19295        runner.sync_to_base().await.unwrap();
19296        assert!(!runner.state.base_sync_blocked());
19297        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19298        assert_ne!(head, fresh);
19299        assert_eq!(runner.state.reviews.len(), 1);
19300        assert!(!runner.state.gate_ran);
19301        let saved = &runner.state.base_sync_recovery.authorizations[0];
19302        assert_eq!(saved.reviews[0].head, head);
19303        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19304        assert!(saved.gate_ran);
19305        assert!(!saved.gate[0].ok());
19306        runner.review_loop().await.unwrap();
19307        runner.gate().await.unwrap();
19308        assert_eq!(runner.state.reviews[0].head, head);
19309        assert_eq!(
19310            runner.state.reviews[0].verified_head.as_deref(),
19311            Some(head.as_str())
19312        );
19313        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19314        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19315        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19316        assert!(runner.state.gate_ran);
19317        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19318        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19319        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19320        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19321        assert_eq!(
19322            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19323            "retained change"
19324        );
19325    }
19326
19327    #[cfg(unix)]
19328    #[tokio::test]
19329    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19330        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19331        let queue = crate::queue::Queue::open();
19332        let mut owner = queue.get(&task).unwrap();
19333        owner.release_operator("test-resume", None);
19334        queue.put(&mut owner).unwrap();
19335        let generation = owner.resumption.as_ref().unwrap().generation;
19336        runner.state.task_instruction = Some(owner.instruction.clone());
19337        runner.state.driver_exited = true;
19338        runner.state.save().unwrap();
19339        let home = crate::run::home();
19340        let _claim = queue.claim(&task).unwrap();
19341        owner.resumption.as_mut().unwrap().at =
19342            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19343        queue.put(&mut owner).unwrap();
19344        assert!(
19345            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19346                .await
19347                .is_err(),
19348            "an approval from before the stop grants nothing"
19349        );
19350        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19351        queue.put(&mut owner).unwrap();
19352        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19353            .await
19354            .unwrap();
19355        assert!(
19356            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19357                .await
19358                .is_err()
19359        );
19360        runner.state = RunState::load(&runner.state.id).unwrap();
19361        assert_eq!(
19362            runner.state.base_sync_recovery.authorizations[0].generation,
19363            Some(generation)
19364        );
19365        runner.sync_to_base().await.unwrap();
19366        let repo = runner.state.repo.clone();
19367        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19368        git::git(&repo, &["checkout", "main"]).await.unwrap();
19369        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19370        git::git(&repo, &["add", "."]).await.unwrap();
19371        git::git(&repo, &["commit", "-m", "move base again"])
19372            .await
19373            .unwrap();
19374        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19375        git::git(&repo, &["checkout", "fix/retained"])
19376            .await
19377            .unwrap();
19378        runner.sync_to_base().await.unwrap();
19379        assert!(!runner.state.base_sync_blocked());
19380        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19381        assert_eq!(runner.state.base_episode_used(), 2);
19382        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19383        assert_ne!(fresh, head);
19384        assert!(!runner.state.base_recovery_pending());
19385        // Even replaying the generation with a later timestamp grants nothing.
19386        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19387        queue.put(&mut owner).unwrap();
19388        assert!(
19389            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19390                .await
19391                .is_err()
19392        );
19393        runner.state = RunState::load(&runner.state.id).unwrap();
19394        runner.sync_to_base().await.unwrap();
19395        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19396        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19397        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19398    }
19399
19400    #[cfg(unix)]
19401    #[tokio::test]
19402    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19403        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19404        runner.state.base_sync = None;
19405        runner.state.status = RunStatus::Blocked;
19406        let mut second = runner.state.candidates[0].clone();
19407        second.label = 'B';
19408        runner.state.candidates.push(second);
19409        assert!(runner.state.votes.is_empty());
19410        assert!(runner.state.deliberation.is_empty());
19411        runner.deliberate().await.unwrap();
19412        runner.vote().await.unwrap();
19413        assert_eq!(runner.state.status, RunStatus::Blocked);
19414        assert!(runner.state.votes.is_empty());
19415        assert!(runner.state.deliberation.is_empty());
19416    }
19417
19418    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19419    /// reads nothing else off it.
19420    fn runner_at(status: RunStatus) -> Runner {
19421        let mut state = RunState::new(
19422            PathBuf::from("/nonexistent/repo"),
19423            "main".to_owned(),
19424            "deadbeef".to_owned(),
19425            "task".to_owned(),
19426            Config::default(),
19427        );
19428        // These fixtures test execution flow, independent of host disk capacity.
19429        state.config.disk.min_free_bytes = 0;
19430        // These fixtures share one home and save concurrently. Short clock
19431        // IDs can collide, making an ownership test read another test's run.
19432        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19433        state.id = format!(
19434            "20000101-000000-{:04x}",
19435            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19436        );
19437        state.status = status;
19438        Runner {
19439            state,
19440            roles: ResolvedRoles {
19441                implementers: Vec::new(),
19442                judges: Vec::new(),
19443                reviewers: Vec::new(),
19444                fixer: None,
19445                conductor: conductor(),
19446                implementer_roster: Vec::new(),
19447                judge_roster: Vec::new(),
19448                reviewer_roster: Vec::new(),
19449            },
19450            sem: Arc::new(Semaphore::new(1)),
19451            pause: Pause::new(),
19452            interrupt: Pause::new(),
19453        }
19454    }
19455
19456    #[tokio::test]
19457    async fn targeted_fix_refuses_independent_ownership_conflicts() {
19458        crate::run::pin_test_home();
19459        let home = crate::run::home();
19460        let mut runner = runner_at(RunStatus::Ready);
19461        runner.state.driver_exited = true;
19462        runner.state.save().unwrap();
19463        let id = runner.state.id.clone();
19464        let path = runner.state.dir().join("run.json");
19465        let ids = ["R1-1-1".into()];
19466        let lease = crate::driver::maintenance(&home, &id).unwrap();
19467        for (guard, expected) in [
19468            (Some(lease), "currently being worked on"),
19469            (None, "ownership is being updated"),
19470        ] {
19471            let owner = if guard.is_none() {
19472                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
19473            } else {
19474                None
19475            };
19476            let before = std::fs::read(&path).unwrap();
19477            let err = runner
19478                .fix_selected(&ids, "ownership conflict", false)
19479                .await
19480                .unwrap_err();
19481            assert!(format!("{err:#}").contains(expected), "{err:#}");
19482            assert_eq!(std::fs::read(&path).unwrap(), before);
19483            assert!(!runner.state.dir().join("fix.lock").exists());
19484            drop(owner);
19485            drop(guard);
19486        }
19487        let mut disk = RunState::load(&id).unwrap();
19488        disk.driver_exited = false;
19489        disk.driver_pid = Some(std::process::id());
19490        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
19491        disk.save().unwrap();
19492        assert_eq!(
19493            disk.liveness_under(&home, false),
19494            crate::run::Liveness::Live
19495        );
19496        let before = std::fs::read(&path).unwrap();
19497        let err = runner
19498            .fix_selected(&ids, "live driver", false)
19499            .await
19500            .unwrap_err();
19501        assert!(
19502            err.to_string().contains("currently being worked on"),
19503            "{err:#}"
19504        );
19505        assert_eq!(std::fs::read(&path).unwrap(), before);
19506        assert!(!runner.state.dir().join("fix.lock").exists());
19507        disk.driver_exited = true;
19508        disk.driver_pid = None;
19509        disk.driver_started_at = None;
19510        disk.status = RunStatus::Reviewing;
19511        disk.save().unwrap();
19512        let before = std::fs::read(&path).unwrap();
19513        let err = runner
19514            .fix_selected(&ids, "stale state", false)
19515            .await
19516            .unwrap_err();
19517        assert!(
19518            err.to_string().contains("run changed since it was loaded"),
19519            "{err:#}"
19520        );
19521        assert_eq!(std::fs::read(&path).unwrap(), before);
19522        assert!(!runner.state.dir().join("fix.lock").exists());
19523        assert!(runner.state.operator_fixes.is_empty());
19524    }
19525
19526    #[tokio::test]
19527    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
19528        use std::future::Future;
19529        use std::task::Poll;
19530
19531        crate::run::pin_test_home();
19532        let home = crate::run::home();
19533        let repo = tempfile::tempdir().unwrap();
19534        let mut runner = runner_at(RunStatus::Ready);
19535        runner.state.repo = repo.path().to_path_buf();
19536        runner.state.driver_exited = true;
19537        runner.state.candidates.push(Candidate {
19538            index: 0,
19539            label: 'A',
19540            agent: "mock".into(),
19541            branch: "magi/test/A".into(),
19542            worktree: repo.path().join("wt"),
19543            summary: String::new(),
19544            stat: String::new(),
19545            files: 0,
19546            commits: 0,
19547            empty: false,
19548            failed: None,
19549            verified_noop: None,
19550            duration_ms: 0,
19551            folded: false,
19552        });
19553        runner.state.tally = Some(Tally {
19554            first_choice: BTreeMap::from([('A', 1)]),
19555            borda: BTreeMap::new(),
19556            winner: 'A',
19557            rankings: 1,
19558            unanimous_initial: true,
19559            deliberated: false,
19560            changed_votes: 0,
19561            unanimous_final: true,
19562            tie_break: None,
19563            judges: 1,
19564            present: 1,
19565            quorum: 1,
19566            met_quorum: true,
19567            uncontested: None,
19568        });
19569        runner.state.save().unwrap();
19570        let id = runner.state.id.clone();
19571        let dir = runner.state.dir();
19572        let before = std::fs::read(dir.join("run.json")).unwrap();
19573        let ids = ["R1-1-1".into()];
19574        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
19575        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
19576            Poll::Pending => Poll::Ready(()),
19577            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
19578        })
19579        .await;
19580        assert!(FixClaim::acquire(&dir).is_err());
19581        assert!(crate::driver::maintenance(&home, &id).is_err());
19582        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
19583        drop(fix);
19584        assert!(FixClaim::acquire(&dir).is_ok());
19585        assert!(crate::driver::maintenance(&home, &id).is_ok());
19586        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
19587    }
19588
19589    #[tokio::test]
19590    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19591        crate::run::pin_test_home();
19592        let temp = tempfile::tempdir().unwrap();
19593        let root = temp.path().canonicalize().unwrap();
19594        let repo = root.join("repo");
19595        std::fs::create_dir(&repo).unwrap();
19596        init_repo(&repo);
19597        git::git(&repo, &["config", "core.autocrlf", "false"])
19598            .await
19599            .unwrap();
19600        let mut runner = runner_at(RunStatus::Blocked);
19601        runner.state.repo = repo.clone();
19602        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19603        runner.state.config.agents = vec![conductor()];
19604        runner.state.config.graph.selected_implementer = Some("conductor".into());
19605        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19606        let (shell, command, setup_output) = if cfg!(windows) {
19607            (
19608                vec!["cmd".into(), "/C".into()],
19609                "echo ready>seat-ready",
19610                "ready\r\n",
19611            )
19612        } else {
19613            (
19614                vec!["sh".into(), "-c".into()],
19615                "printf ready > seat-ready",
19616                "ready",
19617            )
19618        };
19619        runner.state.config.verify.shell = Some(shell);
19620        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19621            run: Some(command.into()),
19622            ..Default::default()
19623        }];
19624        runner.state.save().unwrap();
19625        let path = runner.state.worktree_root().join("judge-1");
19626        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19627            .await
19628            .unwrap();
19629        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19630        git::git(&path, &["add", "."]).await.unwrap();
19631        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19632        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19633            .await
19634            .unwrap();
19635        git::git(&path, &["checkout", "--detach", &head])
19636            .await
19637            .unwrap();
19638        let evidence = crate::fold_evidence::snapshot(
19639            &runner.state,
19640            &crate::run::home().canonicalize().unwrap(),
19641            &head,
19642            64 * 1024 * 1024,
19643        )
19644        .await
19645        .unwrap();
19646        let mut contents = BTreeMap::new();
19647        contents.insert(
19648            repo.join("logs/HEAD"),
19649            format!("{head} {head} fixture\n").into_bytes(),
19650        );
19651        let record = serde_json::json!({
19652            "version":1, "run":runner.state.id, "source":path, "head":head,
19653            "evidence":evidence, "admin":{}, "admin_contents":contents,
19654            "history":{head.clone():evidence}, "phase":"evicted"
19655        });
19656        std::fs::write(
19657            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19658            serde_json::to_vec(&record).unwrap(),
19659        )
19660        .unwrap();
19661        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19662        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19663            .await
19664            .unwrap();
19665        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19666        assert!(
19667            !git::git_raw(&repo, &["cat-file", "-e", &head])
19668                .await
19669                .unwrap()
19670                .ok()
19671        );
19672        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19673        let error = resumed.execute().await.unwrap_err();
19674        assert!(
19675            error
19676                .to_string()
19677                .contains("selected implementation is held"),
19678            "{error:#}"
19679        );
19680        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19681        assert_eq!(
19682            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19683            setup_output
19684        );
19685        assert_eq!(
19686            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19687            "unrelated seat"
19688        );
19689        let error = resumed.execute().await.unwrap_err();
19690        assert!(
19691            error
19692                .to_string()
19693                .contains("selected implementation is held"),
19694            "{error:#}"
19695        );
19696        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19697        git::git(&path, &["add", "."]).await.unwrap();
19698        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19699        let next = git::git(
19700            &path,
19701            &[
19702                "commit-tree",
19703                &next_tree,
19704                "-p",
19705                &head,
19706                "-m",
19707                "next review checkpoint",
19708            ],
19709        )
19710        .await
19711        .unwrap();
19712        git::git(&path, &["checkout", "--detach", &next])
19713            .await
19714            .unwrap();
19715        resumed.state.reviews.push(
19716            serde_json::from_value(serde_json::json!({
19717                "round":1, "head":next, "reviews":[]
19718            }))
19719            .unwrap(),
19720        );
19721        resumed.state.save().unwrap();
19722        let error = resumed.execute().await.unwrap_err();
19723        assert!(
19724            error
19725                .to_string()
19726                .contains("selected implementation is held"),
19727            "{error:#}"
19728        );
19729        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
19730    }
19731
19732    #[tokio::test]
19733    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
19734        crate::run::pin_test_home();
19735        let mut runner = runner_at(RunStatus::Gating);
19736        runner.state.save().unwrap();
19737        let id = runner.state.id.clone();
19738        let passes = runner.state.passes.len();
19739        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19740        let mut claiming = Box::pin(runner.claim_driver(None));
19741        std::future::poll_fn(|cx| {
19742            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
19743            std::task::Poll::Ready(())
19744        })
19745        .await;
19746        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
19747        drop(owner);
19748        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
19749            .await
19750            .unwrap()
19751            .unwrap();
19752        assert_eq!(execution.runner.state.passes.len(), passes + 1);
19753        assert!(execution.runner.state.resource_block.is_none());
19754        assert_eq!(
19755            execution.runner.state.liveness(false),
19756            crate::run::Liveness::Live
19757        );
19758        drop(execution);
19759        assert!(RunState::load(&id).unwrap().driver_exited);
19760    }
19761
19762    #[tokio::test]
19763    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
19764        crate::run::pin_test_home();
19765        let mut runner = runner_at(RunStatus::Gating);
19766        runner.state.save().unwrap();
19767        // run.json can commit, but the subsequent lease metadata write fails.
19768        // Cleanup must run after releasing the short ownership lock.
19769        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
19770        assert!(runner.claim_driver(None).await.is_err());
19771        assert!(runner.state.driver_exited);
19772        assert_eq!(runner.state.driver_pid, None);
19773        let disk = RunState::load(&runner.state.id).unwrap();
19774        assert!(disk.driver_exited);
19775        assert_eq!(disk.driver_pid, None);
19776        assert_eq!(disk.status, RunStatus::Gating);
19777    }
19778
19779    #[tokio::test]
19780    async fn an_early_graph_error_releases_its_driver() {
19781        crate::run::pin_test_home();
19782        let mut runner = runner_at(RunStatus::Blocked);
19783        runner.state.config.graph.selected_implementer = Some("selected".into());
19784        runner.state.save().unwrap();
19785        assert!(runner.execute().await.is_err());
19786        let disk = RunState::load(&runner.state.id).unwrap();
19787        assert!(disk.driver_exited);
19788        assert_eq!(disk.driver_pid, None);
19789        assert_eq!(disk.status, RunStatus::Blocked);
19790    }
19791
19792    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
19793        crate::run::MergeRepair {
19794            question: "repair-question".into(),
19795            head: "old-head".into(),
19796            pr: "https://github.com/o/r/pull/42".into(),
19797            reviews: vec![review_round(false, 1, 1, 1, false, true)],
19798            gate: vec![outcome(Some(0), false)],
19799            gate_head: Some("old-head".into()),
19800            gate_fixes: Vec::new(),
19801            pre_gate: Vec::new(),
19802            phase,
19803            failure: None,
19804        }
19805    }
19806
19807    #[tokio::test]
19808    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
19809        crate::run::pin_test_home();
19810        let mut runner = runner_at(RunStatus::Landing);
19811        runner.state.merge_repairs.push(merge_repair_request(
19812            crate::run::MergeRepairPhase::Requested,
19813        ));
19814        runner.state.save().unwrap();
19815        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
19816        assert!(
19817            runner
19818                .execute()
19819                .await
19820                .unwrap_err()
19821                .to_string()
19822                .contains("already running")
19823        );
19824        assert_eq!(
19825            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19826            crate::run::MergeRepairPhase::Requested
19827        );
19828        drop(claim);
19829        let mut disk = runner.state.clone();
19830        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
19831        disk.save().unwrap();
19832        assert!(
19833            runner
19834                .execute()
19835                .await
19836                .unwrap_err()
19837                .to_string()
19838                .contains("decision changed")
19839        );
19840        assert_eq!(
19841            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19842            crate::run::MergeRepairPhase::Complete
19843        );
19844    }
19845
19846    #[test]
19847    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
19848        crate::run::pin_test_home();
19849        let mut runner = runner_at(RunStatus::Landing);
19850        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
19851        runner.state.reviews = request.reviews.clone();
19852        runner.state.gate = request.gate.clone();
19853        runner.state.gate_ran = true;
19854        runner.state.land_approval = Some(crate::run::LandApproval {
19855            question: "old".into(),
19856            head: "old-head".into(),
19857        });
19858        runner.state.merge_repairs.push(request);
19859        runner.begin_merge_repair_review(0).unwrap();
19860        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
19861        assert!(!runner.state.gate_status().ok());
19862        assert!(runner.state.land_approval.is_none());
19863        let disk = RunState::load(&runner.state.id).unwrap();
19864        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
19865        assert!(disk.merge_repairs[0].gate[0].ok());
19866        assert_eq!(
19867            disk.merge_repairs[0].phase,
19868            crate::run::MergeRepairPhase::Reviewing
19869        );
19870        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
19871        assert!(disk.reviews.is_empty());
19872    }
19873
19874    #[tokio::test]
19875    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
19876        crate::run::pin_test_home();
19877        for phase in [
19878            crate::run::MergeRepairPhase::Fixing,
19879            crate::run::MergeRepairPhase::Requested,
19880        ] {
19881            let mut runner = runner_at(RunStatus::Landing);
19882            runner.state.config.graph.land_rounds = 0;
19883            runner.state.merge_repairs.push(merge_repair_request(phase));
19884            runner.state.save().unwrap();
19885            assert!(!runner.repair_merge_review().await.unwrap());
19886            assert_eq!(runner.state.status, RunStatus::Blocked);
19887            assert_eq!(
19888                runner.state.merge_repairs[0].phase,
19889                crate::run::MergeRepairPhase::Failed
19890            );
19891            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
19892            assert!(
19893                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
19894                    "interrupted"
19895                } else {
19896                    "budget exhausted"
19897                })
19898            );
19899            assert!(runner.state.merge.is_none());
19900        }
19901    }
19902
19903    /// `park_here` folding in the reason `Pause::park_because` recorded -
19904    /// this is what lets an operator reading a run's events tell an
19905    /// interrupt-driven park from an ordinary shutdown park.
19906    #[test]
19907    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
19908        crate::run::pin_test_home();
19909        let mut runner = runner_at(RunStatus::Implementing);
19910        let interrupt = Pause::new();
19911        runner.watch_interrupt(interrupt.clone());
19912
19913        interrupt.park_because("task a1b2 asked to run first");
19914
19915        assert!(runner.park_here().expect("park_here"));
19916        assert!(runner.state.parked);
19917        let last = runner.state.events.last().expect("a park event");
19918        assert_eq!(last.node, "park");
19919        assert!(
19920            last.message.contains("task a1b2 asked to run first"),
19921            "expected the interrupt reason in {:?}",
19922            last.message
19923        );
19924    }
19925
19926    /// The cause is stored on the pass when it parks, and the first cause a
19927    /// shared pause was given is the one that stays.
19928    #[test]
19929    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
19930        crate::run::pin_test_home();
19931        let mut runner = runner_at(RunStatus::Implementing);
19932        runner.state.begin_pass();
19933        let shutdown = Pause::new();
19934        runner.on_pause(shutdown.clone());
19935        let upgrade = ParkCause::Upgrade {
19936            from: "0.121.0".to_owned(),
19937            to: Some("0.121.1".to_owned()),
19938        };
19939        shutdown.park_for(upgrade.clone());
19940        shutdown.park_for(ParkCause::Operator);
19941
19942        assert!(runner.park_here().expect("park_here"));
19943        assert_eq!(
19944            runner.state.passes[0].end,
19945            Some(crate::run::PassEnd::Parked { cause: upgrade })
19946        );
19947        let last = runner.state.events.last().expect("a park event");
19948        assert!(last.message.contains("0.121.0"), "{}", last.message);
19949    }
19950
19951    #[tokio::test]
19952    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
19953        crate::run::pin_test_home();
19954        let mut runner = runner_at(RunStatus::Reviewing);
19955        runner.state.save().unwrap();
19956        let mut execution = runner.claim_driver(None).await.expect("first execution");
19957        assert_eq!(execution.runner.state.passes.len(), 1);
19958        execution
19959            .driver
19960            .finish(&mut execution.runner.state)
19961            .await
19962            .unwrap();
19963    }
19964
19965    #[tokio::test]
19966    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
19967        crate::run::pin_test_home();
19968        let mut runner = runner_at(RunStatus::Reviewing);
19969        runner.state.config.agents = vec![conductor()];
19970        runner.state.config.graph.timeout_resource_wait = 0;
19971        runner.state.save().unwrap();
19972        let id = runner.state.id.clone();
19973        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19974        assert!(runner.claim_driver(None).await.is_err());
19975        drop(owner);
19976        drop(runner);
19977        let mut resumed = Runner::resume(&id).unwrap();
19978        assert_eq!(resumed.state.driver_claimed, Some(false));
19979        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
19980        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
19981        let mut execution = resumed
19982            .claim_driver(None)
19983            .await
19984            .expect("retry initial claim after reload");
19985        assert_eq!(execution.runner.state.driver_claimed, Some(true));
19986        assert_eq!(execution.runner.state.passes.len(), 1);
19987        execution
19988            .driver
19989            .finish(&mut execution.runner.state)
19990            .await
19991            .unwrap();
19992    }
19993
19994    #[tokio::test]
19995    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
19996        crate::run::pin_test_home();
19997        let mut runner = runner_at(RunStatus::Reviewing);
19998        runner.state.config.agents = vec![conductor()];
19999        runner.state.save().unwrap();
20000        let id = runner.state.id.clone();
20001        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20002        let mut resumed = Runner::resume(&id).unwrap();
20003        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20004        assert!(resumed.claim_driver(None).await.is_err());
20005        assert!(RunState::load(&id).unwrap().passes.is_empty());
20006        drop(lease);
20007        let mut execution = resumed.claim_driver(None).await.unwrap();
20008        execution
20009            .driver
20010            .finish(&mut execution.runner.state)
20011            .await
20012            .unwrap();
20013    }
20014
20015    #[tokio::test]
20016    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20017        crate::run::pin_test_home();
20018        let mut runner = runner_at(RunStatus::Reviewing);
20019        let state = &mut runner.state;
20020        state.config.agents = vec![conductor()];
20021        state.driver_claimed = None;
20022        state.driver_pid = Some(std::process::id());
20023        state.driver_started_at = None;
20024        state.begin_pass();
20025        state.save().unwrap();
20026        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20027        std::fs::write(
20028            state.dir().join("driver.json"),
20029            serde_json::to_vec(&serde_json::json!({
20030                "pid": state.driver_pid, "started_at": null,
20031                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20032            }))
20033            .unwrap(),
20034        )
20035        .unwrap();
20036        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20037        drop(lease);
20038        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20039        let mut resumed = Runner::resume(&state.id).unwrap();
20040        assert!(!resumed.state.driver_exited);
20041        let mut execution = resumed
20042            .claim_driver(None)
20043            .await
20044            .expect("lease proves previous execution ended");
20045        assert_eq!(execution.runner.state.passes.len(), 2);
20046        execution
20047            .driver
20048            .finish(&mut execution.runner.state)
20049            .await
20050            .unwrap();
20051    }
20052
20053    #[tokio::test]
20054    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20055        crate::run::pin_test_home();
20056        let mut runner = runner_at(RunStatus::Reviewing);
20057        let mut json = serde_json::to_value(&runner.state).unwrap();
20058        json.as_object_mut().unwrap().remove("driver_claimed");
20059        runner.state = serde_json::from_value(json).unwrap();
20060        assert_eq!(runner.state.driver_claimed, None);
20061        runner.state.save().unwrap();
20062        let mut execution = runner
20063            .claim_driver(None)
20064            .await
20065            .expect("the execution lease, not a missing marker, excludes a second driver");
20066        assert_eq!(execution.runner.state.passes.len(), 1);
20067        execution
20068            .driver
20069            .finish(&mut execution.runner.state)
20070            .await
20071            .unwrap();
20072    }
20073
20074    #[tokio::test]
20075    async fn driver_admission_refuses_a_proven_live_driver() {
20076        crate::run::pin_test_home();
20077        let mut runner = runner_at(RunStatus::Reviewing);
20078        let pid = std::process::id();
20079        runner.state.driver_pid = Some(pid);
20080        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20081        assert!(runner.state.driver_started_at.is_some());
20082        runner.state.save().unwrap();
20083        let error = runner
20084            .claim_driver(None)
20085            .await
20086            .err()
20087            .expect("a live driver must refuse");
20088        assert!(error.to_string().contains("live driver"), "{error:#}");
20089        let saved = RunState::load(&runner.state.id).unwrap();
20090        assert_eq!(saved.driver_pid, Some(pid));
20091        assert_eq!(saved.status, RunStatus::Reviewing);
20092        assert!(saved.passes.is_empty());
20093    }
20094
20095    #[test]
20096    fn parking_resource_halt_persists_the_pass_once() {
20097        crate::run::pin_test_home();
20098        let mut runner = runner_at(RunStatus::Reviewing);
20099        runner.state.begin_pass();
20100        runner.state.resource_block = Some(crate::run::ResourceBlock {
20101            node: "fix".into(),
20102            kind: "shared build cache".into(),
20103            detail: "cancelled".into(),
20104            at: Timestamp::now(),
20105            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20106        });
20107        let cause = ParkCause::Upgrade {
20108            from: "old".into(),
20109            to: Some("new".into()),
20110        };
20111        runner.pause.park_for(cause.clone());
20112        // Both direct fixer exits and graph resource boundaries must complete
20113        // parking, rather than returning a stale Reviewing record.
20114        runner.stop_for_resource().unwrap();
20115        assert!(runner.resource_halt().unwrap());
20116        assert!(runner.park_here().unwrap());
20117        let saved = RunState::load(&runner.state.id).unwrap();
20118        assert!(saved.parked);
20119        assert_eq!(saved.status, RunStatus::Reviewing);
20120        assert!(saved.passes[0].ended_at.is_some());
20121        assert_eq!(
20122            saved.passes[0].end,
20123            Some(crate::run::PassEnd::Parked {
20124                cause: cause.clone()
20125            })
20126        );
20127        assert_eq!(
20128            saved.resource_block.unwrap().cause,
20129            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20130        );
20131        assert_eq!(
20132            saved
20133                .events
20134                .iter()
20135                .filter(|event| event.node == "park")
20136                .count(),
20137            1
20138        );
20139    }
20140
20141    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20142    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20143    /// cleared) must not make a *different* run - one only watching its own,
20144    /// unshared interrupt `Pause` - see itself as parked. If a future change
20145    /// ever collapsed these back into one handle, the interrupt scheduler
20146    /// would park every run for the rest of the daemon's life, not just the
20147    /// one it meant to interrupt.
20148    #[test]
20149    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20150        crate::run::pin_test_home();
20151        let mut runner = runner_at(RunStatus::Implementing);
20152        let shutdown = Pause::new();
20153        runner.on_pause(shutdown.clone());
20154        let interrupt = Pause::new();
20155        runner.watch_interrupt(interrupt.clone());
20156
20157        // Nobody has asked for anything yet.
20158        assert!(!runner.park_here().expect("park_here"));
20159        assert!(!runner.state.parked);
20160
20161        // Only the interrupt handle fires; the shutdown handle stays clear.
20162        interrupt.park_because("test");
20163        assert!(!shutdown.parked());
20164        assert!(runner.park_here().expect("park_here"));
20165    }
20166
20167    /// The property every prior attempt at this feature failed to pin down:
20168    /// asking a run to park while one of its nodes has a real, in-flight
20169    /// async operation running (an agent call, in production) must not cut
20170    /// that operation short. `park_here` is only ever consulted *between*
20171    /// `execute`'s node calls - see its own doc - so nothing inside a node
20172    /// can observe a park request until the node itself returns. This proves
20173    /// that structurally, with real `tokio` concurrency and a channel
20174    /// handshake (never a sleep, which would only prove "usually", not
20175    /// "cannot"): the "node" below reports that it has genuinely started,
20176    /// and only then is the park requested; the node still has to be told to
20177    /// finish before `park_here` is ever called, exactly mirroring every
20178    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20179    /// in `execute`.
20180    #[tokio::test]
20181    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20182        crate::run::pin_test_home();
20183        let mut runner = runner_at(RunStatus::Implementing);
20184        let interrupt = Pause::new();
20185        runner.watch_interrupt(interrupt.clone());
20186
20187        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20188        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20189
20190        // Stands in for one node's in-flight agent call: it proves it has
20191        // genuinely started, then blocks - exactly as a spawned CLI process
20192        // does - until told to finish.
20193        let node = async move {
20194            started_tx.send(()).expect("send started");
20195            finish_rx.await.expect("recv finish");
20196            "node finished"
20197        };
20198
20199        let interrupter = async move {
20200            started_rx.await.expect("recv started");
20201            // The call is now genuinely in flight. Ask it to park.
20202            interrupt.park_because("higher-priority task waiting");
20203            // Nothing the node does can observe this yet - there is no
20204            // check inside it, by construction - so let the executor run
20205            // anything pending and then let the node finish on its own.
20206            tokio::task::yield_now().await;
20207            finish_tx.send(()).expect("send finish");
20208        };
20209
20210        let (node_result, ()) = tokio::join!(node, interrupter);
20211        assert_eq!(
20212            node_result, "node finished",
20213            "the in-flight call ran to completion"
20214        );
20215
20216        // Only now, at the boundary the real `execute` would check right
20217        // after this node, does the park take effect.
20218        assert!(runner.park_here().expect("park_here"));
20219        assert!(runner.state.parked);
20220    }
20221
20222    /// A run parked mid-competition carries every field it had accumulated
20223    /// through the exact same disk round-trip an ordinary resume uses -
20224    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20225    /// Nothing about parking for an interrupt is a special case of that path;
20226    /// this is what proves it rather than assuming it.
20227    #[test]
20228    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20229        crate::run::pin_test_home();
20230        let mut runner = runner_at(RunStatus::Judging);
20231        // `Runner::resume` re-resolves roles from the saved config, which
20232        // refuses an empty roster - give it the same minimal one `conductor`
20233        // itself uses.
20234        runner.state.config.agents = vec![conductor()];
20235        runner.state.candidates = vec![Candidate {
20236            index: 0,
20237            label: 'A',
20238            agent: "alpha".to_owned(),
20239            branch: "magi/x/A".to_owned(),
20240            worktree: PathBuf::from("/nonexistent/worktree"),
20241            summary: "did the thing".to_owned(),
20242            stat: "1 file changed".to_owned(),
20243            files: 1,
20244            commits: 1,
20245            empty: false,
20246            failed: None,
20247            verified_noop: None,
20248            duration_ms: 1234,
20249            folded: false,
20250        }];
20251        let run_id = runner.state.id.clone();
20252
20253        let interrupt = Pause::new();
20254        runner.watch_interrupt(interrupt.clone());
20255        interrupt.park_because("task c3d4 asked to run first");
20256        assert!(runner.park_here().expect("park_here"));
20257
20258        let resumed = Runner::resume(&run_id).expect("resume");
20259        assert_eq!(resumed.state.candidates.len(), 1);
20260        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20261        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20262        assert_eq!(resumed.state.status, runner.state.status);
20263        assert!(
20264            resumed.state.parked,
20265            "still parked until `execute` actually walks the graph again"
20266        );
20267        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20268    }
20269
20270    /// A fresh open question on `run`, stored and handed back for assertions.
20271    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20272        let mut q = ask::Question::new(
20273            run.to_owned(),
20274            "implement".to_owned(),
20275            "impl-A".to_owned(),
20276            "Which storage backend should the cache use?".to_owned(),
20277            String::new(),
20278            vec!["SQLite".to_owned(), "Redis".to_owned()],
20279        );
20280        store.put(&mut q).unwrap();
20281        q
20282    }
20283
20284    #[test]
20285    fn a_failed_runs_open_question_is_abandoned() {
20286        ask_test_home();
20287        let store = ask::Questions::open();
20288        let mut runner = runner_at(RunStatus::Failed);
20289        let run = runner.state.id.clone();
20290        let q = ask_open_question(&store, &run);
20291
20292        runner.settle_questions();
20293
20294        let back = store.get(&q.id).unwrap();
20295        assert!(
20296            !back.status.open(),
20297            "the seat that asked died with the run; nobody is left to read an answer"
20298        );
20299        assert!(
20300            back.detail.contains(&run) && back.detail.contains("failed"),
20301            "the reason names what the run became, not just that it is gone: {}",
20302            back.detail
20303        );
20304    }
20305
20306    #[test]
20307    fn a_merged_runs_open_question_is_abandoned_too() {
20308        ask_test_home();
20309        let store = ask::Questions::open();
20310        // A run that finishes cleanly still leaves nobody to read an answer -
20311        // this is not only a failure-path cleanup.
20312        for status in [RunStatus::Merged, RunStatus::Ready] {
20313            let mut runner = runner_at(status);
20314            let run = runner.state.id.clone();
20315            let q = ask_open_question(&store, &run);
20316
20317            runner.settle_questions();
20318
20319            let back = store.get(&q.id).unwrap();
20320            assert!(
20321                !back.status.open(),
20322                "{status:?} run's question must not outlive the run"
20323            );
20324        }
20325    }
20326
20327    #[test]
20328    fn a_still_resumable_runs_open_question_is_left_alone() {
20329        ask_test_home();
20330        let store = ask::Questions::open();
20331        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20332        // review round and the seat sessions are all still on disk — so a
20333        // question asked mid-round may yet get a real answer from a real
20334        // resume. Sweeping it here would be exactly the failure mode this
20335        // whole feature exists to avoid on the other side.
20336        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20337            let mut runner = runner_at(status);
20338            let run = runner.state.id.clone();
20339            let q = ask_open_question(&store, &run);
20340
20341            runner.settle_questions();
20342
20343            let back = store.get(&q.id).unwrap();
20344            assert!(
20345                back.status.open(),
20346                "{status:?} is still alive; the question must still be waiting"
20347            );
20348        }
20349    }
20350
20351    #[test]
20352    fn settle_questions_never_touches_an_already_answered_question() {
20353        ask_test_home();
20354        let store = ask::Questions::open();
20355        let mut runner = runner_at(RunStatus::Failed);
20356        let run = runner.state.id.clone();
20357        let mut q = ask_open_question(&store, &run);
20358        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20359            .unwrap();
20360        store.put(&mut q).unwrap();
20361
20362        // Called twice, the way a crash-recovered daemon reclaim and the
20363        // graph's own cleanup both can for the same run — `abandon_for_run`
20364        // only ever touches what is still open, so this must be inert both
20365        // times, not merely the second.
20366        runner.settle_questions();
20367        runner.settle_questions();
20368
20369        let back = store.get(&q.id).unwrap();
20370        assert_eq!(
20371            back.status,
20372            ask::QuestionStatus::Answered,
20373            "a real answer is a decision on record, never overwritten by a sweep"
20374        );
20375    }
20376
20377    #[tokio::test]
20378    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20379        let tmp = tempfile::tempdir().unwrap();
20380        let home = tmp.path().join("home");
20381        let repo = tmp.path().join("repo");
20382        std::fs::create_dir(&home).unwrap();
20383        std::fs::create_dir(&repo).unwrap();
20384        init_repo(&repo);
20385
20386        let mut config = Config::default();
20387        config.graph.worktree_root = Some(tmp.path().join("wt"));
20388        config.verify.build_cache = crate::config::BuildCache::Isolated;
20389        let mut state = RunState::new(
20390            repo.clone(),
20391            "main".into(),
20392            "base".into(),
20393            "fold fixture".into(),
20394            config,
20395        );
20396        let root = state.worktree_root();
20397        let mut outputs = Vec::new();
20398        for name in ["idle", "busy"] {
20399            let checkout = root.join(name);
20400            git::worktree_add_detached(&repo, &checkout, "main")
20401                .await
20402                .unwrap();
20403            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20404            let output = target.join("generated");
20405            std::fs::write(&output, name).unwrap();
20406            outputs.push((target, output));
20407        }
20408        let unknown = crate::build_target::root(&home)
20409            .join("00000000-0000-0000-0000-000000000000")
20410            .join("target");
20411        std::fs::create_dir_all(&unknown).unwrap();
20412        let unowned = unknown.join("generated");
20413        std::fs::write(&unowned, "keep").unwrap();
20414        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20415        let crate::cache::AcquireOutcome::Acquired(_lease) =
20416            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20417        else {
20418            panic!("fixture target must be free");
20419        };
20420
20421        fold_run(&mut state, true, &home).await.unwrap();
20422        assert!(!root.exists());
20423        assert!(!outputs[0].1.exists());
20424        assert!(outputs[1].1.is_file());
20425        assert!(unowned.is_file());
20426    }
20427
20428    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20429    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20430    /// without merging, whose winner is still the operator's answer to read.
20431    /// Nothing previously called `fold_run` itself with a real `tally`, so
20432    /// this is the first test to pin down the one distinction the whole
20433    /// automatic-fold feature depends on: the winner's worktree and branch
20434    /// must survive, everything else sharing the run's worktree bay - a
20435    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20436    /// second sweep treats every non-winner directory under the bay alike -
20437    /// must not.
20438    #[tokio::test]
20439    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20440        crate::run::pin_test_home();
20441        let tmp = tempfile::tempdir().expect("tempdir");
20442        let repo = tmp.path().join("repo");
20443        std::fs::create_dir_all(&repo).unwrap();
20444        init_repo(&repo);
20445
20446        let mut config = Config::default();
20447        config.graph.worktree_root = Some(tmp.path().join("wt"));
20448
20449        let mut state = RunState::new(
20450            repo.clone(),
20451            "main".to_owned(),
20452            "deadbeef".to_owned(),
20453            "task".to_owned(),
20454            config,
20455        );
20456        let root = state.worktree_root();
20457        let wt_a = root.join("cand-A");
20458        let wt_b = root.join("cand-B");
20459        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20460            .await
20461            .expect("worktree A");
20462        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20463            .await
20464            .expect("worktree B");
20465
20466        state.candidates = vec![
20467            Candidate {
20468                index: 0,
20469                label: 'A',
20470                agent: "alpha".to_owned(),
20471                branch: "magi/x/A".to_owned(),
20472                worktree: wt_a.clone(),
20473                summary: String::new(),
20474                stat: String::new(),
20475                files: 0,
20476                commits: 0,
20477                empty: false,
20478                failed: None,
20479                verified_noop: None,
20480                duration_ms: 0,
20481                folded: false,
20482            },
20483            Candidate {
20484                index: 1,
20485                label: 'B',
20486                agent: "beta".to_owned(),
20487                branch: "magi/x/B".to_owned(),
20488                worktree: wt_b.clone(),
20489                summary: String::new(),
20490                stat: String::new(),
20491                files: 0,
20492                commits: 0,
20493                empty: false,
20494                failed: None,
20495                verified_noop: None,
20496                duration_ms: 0,
20497                folded: false,
20498            },
20499        ];
20500        state.tally = Some(Tally {
20501            first_choice: BTreeMap::from([('A', 1)]),
20502            borda: BTreeMap::new(),
20503            winner: 'A',
20504            rankings: 1,
20505            unanimous_initial: true,
20506            deliberated: false,
20507            changed_votes: 0,
20508            unanimous_final: true,
20509            tie_break: None,
20510            judges: 1,
20511            present: 1,
20512            quorum: 1,
20513            met_quorum: true,
20514            uncontested: None,
20515        });
20516        state.status = RunStatus::Ready;
20517
20518        fold_run(&mut state, false, &crate::run::home())
20519            .await
20520            .expect("fold_run");
20521
20522        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20523        assert!(
20524            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20525            "the unmerged winner's branch survives"
20526        );
20527        assert!(
20528            !state.candidates[0].folded,
20529            "the winner is not marked folded"
20530        );
20531
20532        assert!(!wt_b.exists(), "the loser's worktree is removed");
20533        assert!(
20534            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20535            "the loser's branch is removed"
20536        );
20537        assert!(state.candidates[1].folded, "the loser is marked folded");
20538    }
20539
20540    #[tokio::test]
20541    #[cfg(unix)]
20542    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20543        use std::os::fd::AsRawFd as _;
20544        use std::time::Duration;
20545
20546        let tmp = tempfile::tempdir().unwrap();
20547        let repo = tmp.path().join("repo");
20548        std::fs::create_dir_all(&repo).unwrap();
20549        init_repo(&repo);
20550        let common = repo.join(".git");
20551        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20552        let home = tmp.path().join("home");
20553        let mut config = Config::default();
20554        config.coordination = crate::config::test_coordination();
20555        config.graph.worktree_root = Some(tmp.path().join("wt"));
20556        config.graph.timeout_resource_wait = 1;
20557        let mut state = RunState::new(
20558            repo.clone(),
20559            "main".into(),
20560            "deadbeef".into(),
20561            "task".into(),
20562            config,
20563        );
20564        let root = state.worktree_root();
20565        let candidate = root.join("cand-A");
20566        let reviewer = root.join("review-1");
20567        let branch = state.branch_for('A');
20568        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20569            .await
20570            .unwrap();
20571        git::worktree_add_detached(&repo, &reviewer, "main")
20572            .await
20573            .unwrap();
20574        git::acquire_worktree_config(&repo).await.unwrap();
20575        state.enabled_worktree_config = true;
20576        state.status = RunStatus::Ready;
20577        state.candidates.push(Candidate {
20578            index: 0,
20579            label: 'A',
20580            agent: "implement".into(),
20581            branch: branch.clone(),
20582            worktree: candidate.clone(),
20583            summary: String::new(),
20584            stat: String::new(),
20585            files: 0,
20586            commits: 0,
20587            empty: false,
20588            failed: None,
20589            verified_noop: None,
20590            duration_ms: 0,
20591            folded: false,
20592        });
20593        state.save_under(&home).unwrap();
20594        let config_before = std::fs::read(common.join("config")).unwrap();
20595        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20596            .await
20597            .unwrap();
20598        // A separate OS handle bypasses the launcher's local gate, exactly as
20599        // an external updater does, and must still prevent all folding work.
20600        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20601        assert_eq!(
20602            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20603            0
20604        );
20605        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20606        assert!(
20607            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20608                .await
20609                .is_err()
20610        );
20611        assert!(candidate.exists());
20612        assert!(reviewer.exists());
20613        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20614        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20615        assert_eq!(
20616            git::git(&repo, &["worktree", "list", "--porcelain"])
20617                .await
20618                .unwrap(),
20619            worktrees_before
20620        );
20621        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20622            .await
20623            .unwrap()
20624            .unwrap_err();
20625        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20626        drop(fold);
20627        assert!(candidate.exists() && reviewer.exists());
20628        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20629        assert_eq!(
20630            state.resource_block.as_ref().unwrap().kind,
20631            "repository coordination"
20632        );
20633        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20634        drop(external);
20635        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20636        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20637            .await
20638            .unwrap()
20639            .unwrap();
20640        drop(fold);
20641        assert!(removed.contains(&branch));
20642        assert!(!root.exists());
20643        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20644        assert!(state.candidates[0].folded);
20645        assert!(!state.enabled_worktree_config);
20646        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20647        let enabled = git::git_raw(
20648            &repo,
20649            &["config", "--local", "--get", "extensions.worktreeConfig"],
20650        )
20651        .await
20652        .unwrap();
20653        assert!(!enabled.ok(), "the last config reference was released");
20654    }
20655
20656    /// A branch handed to a later run is that run's (and its pull request's):
20657    /// folding the run that released it must not delete it.
20658    #[tokio::test]
20659    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20660        let tmp = tempfile::tempdir().expect("tempdir");
20661        let repo = tmp.path().join("repo");
20662        std::fs::create_dir_all(&repo).unwrap();
20663        init_repo(&repo);
20664        let home = tmp.path().join("home");
20665
20666        let mut config = Config::default();
20667        config.graph.worktree_root = Some(tmp.path().join("wt"));
20668        let mut state = RunState::new(
20669            repo.clone(),
20670            "main".to_owned(),
20671            "deadbeef".to_owned(),
20672            "task".to_owned(),
20673            config,
20674        );
20675        // The worktree is already gone (released); the branch survives.
20676        git::git(&repo, &["branch", "magi/x/A", "main"])
20677            .await
20678            .expect("branch");
20679        state.candidates = vec![Candidate {
20680            index: 0,
20681            label: 'A',
20682            agent: "alpha".to_owned(),
20683            branch: "magi/x/A".to_owned(),
20684            worktree: state.worktree_root().join("cand-A"),
20685            summary: String::new(),
20686            stat: String::new(),
20687            files: 0,
20688            commits: 0,
20689            empty: false,
20690            failed: None,
20691            verified_noop: None,
20692            duration_ms: 0,
20693            folded: true,
20694        }];
20695        state.released_to = Some("20260901-000000-new1".to_owned());
20696        state.released_branches = vec!["magi/x/A".to_owned()];
20697
20698        fold_run(&mut state, true, &home).await.expect("fold_run");
20699        state.status = RunStatus::Merged;
20700        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20701        state.merge = Some(crate::run::MergeOutcome {
20702            mode: MergeMode::Pr,
20703            ok: true,
20704            detail: "confirmed merged".into(),
20705            empty: false,
20706        });
20707        fold_run(&mut state, true, &home)
20708            .await
20709            .expect("merged fold");
20710
20711        assert!(
20712            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20713            "the handed-over branch survives a fold"
20714        );
20715    }
20716
20717    /// A winner with nothing ahead of the base is caught before `gh` is ever
20718    /// asked for a pull request, and the message carries what the task's
20719    /// references resolved to.
20720    #[tokio::test]
20721    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
20722        let tmp = tempfile::tempdir().expect("tempdir");
20723        let repo = tmp.path().join("repo");
20724        std::fs::create_dir_all(&repo).unwrap();
20725        init_repo(&repo);
20726        let run = |args: &[&str]| {
20727            let out = std::process::Command::new("git")
20728                .quiet()
20729                .args(args)
20730                .current_dir(&repo)
20731                .output()
20732                .expect("spawn git");
20733            assert!(out.status.success(), "git {args:?}");
20734        };
20735        run(&["branch", "magi/x/A"]);
20736        run(&["checkout", "-q", "-b", "magi/x/B"]);
20737        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
20738        run(&["add", "-A"]);
20739        run(&["commit", "-q", "-m", "work"]);
20740        run(&["checkout", "-q", "main"]);
20741
20742        // A pull request is compared against the remote's base, so the
20743        // fixture needs one. Before it exists nothing can be read, and the
20744        // answer must be "not empty".
20745        let probe = RunState::new(
20746            repo.clone(),
20747            "main".to_owned(),
20748            "deadbeef".to_owned(),
20749            "task".to_owned(),
20750            Config::default(),
20751        );
20752        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
20753        let bare = tmp.path().join("origin.git");
20754        let out = std::process::Command::new("git")
20755            .quiet()
20756            .args(["init", "-q", "--bare"])
20757            .arg(&bare)
20758            .output()
20759            .expect("spawn git");
20760        assert!(out.status.success(), "git init --bare");
20761        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
20762        run(&["push", "-q", "origin", "main"]);
20763
20764        let mut state = RunState::new(
20765            repo.clone(),
20766            "main".to_owned(),
20767            "deadbeef".to_owned(),
20768            "task".to_owned(),
20769            Config::default(),
20770        );
20771        state.seeds = vec![refs::Seed {
20772            token: "magi/27b2/A".to_owned(),
20773            kind: refs::SeedKind::Unresolved,
20774            sha: String::new(),
20775            branch: true,
20776            detail: "no branch or commit named magi/27b2/A".to_owned(),
20777        }];
20778
20779        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
20780        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
20781        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
20782        let detail = empty_candidate_detail(&state, "main");
20783        assert!(detail.starts_with("empty candidate"), "{detail}");
20784        assert!(!detail.contains("magi/27b2/A"), "{detail}");
20785        assert!(detail.contains("--start-from"), "{detail}");
20786    }
20787
20788    /// `status == Ready` used to be read as "this is the harmless
20789    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
20790    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
20791    /// run's PR was closed without merging — and reentering `merge` with
20792    /// `mode` still `Pr` does not know the difference, so it pushed and
20793    /// opened a second pull request. `mode == Local` reproduces the same
20794    /// blind spot without a network call: reentry must not attempt another
20795    /// git merge once this node has already recorded an outcome.
20796    #[tokio::test]
20797    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
20798        let tmp = tempfile::tempdir().expect("tempdir");
20799        let repo = tmp.path().join("repo");
20800        std::fs::create_dir_all(&repo).unwrap();
20801        init_repo(&repo);
20802
20803        let mut config = Config::default();
20804        config.merge.mode = MergeMode::Local;
20805
20806        let mut state = RunState::new(
20807            repo.clone(),
20808            "main".to_owned(),
20809            "deadbeef".to_owned(),
20810            "task".to_owned(),
20811            config,
20812        );
20813        state.candidates = vec![Candidate {
20814            index: 0,
20815            label: 'A',
20816            agent: "alpha".to_owned(),
20817            branch: "does-not-exist".to_owned(),
20818            worktree: repo.clone(),
20819            summary: String::new(),
20820            stat: String::new(),
20821            files: 0,
20822            commits: 0,
20823            empty: false,
20824            failed: None,
20825            verified_noop: None,
20826            duration_ms: 0,
20827            folded: false,
20828        }];
20829        state.tally = Some(Tally {
20830            first_choice: BTreeMap::from([('A', 1)]),
20831            borda: BTreeMap::new(),
20832            winner: 'A',
20833            rankings: 1,
20834            unanimous_initial: true,
20835            deliberated: false,
20836            changed_votes: 0,
20837            unanimous_final: true,
20838            tie_break: None,
20839            judges: 0,
20840            present: 0,
20841            quorum: 0,
20842            met_quorum: true,
20843            uncontested: Some("only candidate A produced a change".to_owned()),
20844        });
20845        state.reviews = vec![ReviewRound {
20846            round: 1,
20847            head: "deadbeef".to_owned(),
20848            verified_head: None,
20849            verified_at: None,
20850            reviews: Vec::new(),
20851            e2e: Vec::new(),
20852            fix: None,
20853            blocking: 0,
20854            answered: 0,
20855            expected: 0,
20856            clean: true,
20857            verify_retried: false,
20858            e2e_deferred: false,
20859            e2e_defer_reason: None,
20860            progressed: false,
20861            vote_split: false,
20862            reconsideration: Vec::new(),
20863            verdict: None,
20864        }];
20865        state.gate = vec![CommandOutcome {
20866            command: "test".to_owned(),
20867            code: Some(0),
20868            output_tail: String::new(),
20869            duration_ms: 0,
20870            resource_blocked: false,
20871            ..Default::default()
20872        }];
20873        state.gate_ran = true;
20874        // Reached its conclusion already — e.g. `land` closing the PR without
20875        // merging it, which (like the honest `MergeMode::None` path) leaves
20876        // `status` at `Ready`. The recorded outcome is what actually marks
20877        // this node done.
20878        state.status = RunStatus::Ready;
20879        state.merge = Some(MergeOutcome {
20880            mode: MergeMode::Local,
20881            ok: false,
20882            detail: "already concluded".to_owned(),
20883            empty: false,
20884        });
20885
20886        let mut runner = Runner {
20887            state,
20888            roles: ResolvedRoles {
20889                implementers: Vec::new(),
20890                judges: Vec::new(),
20891                reviewers: Vec::new(),
20892                fixer: None,
20893                conductor: conductor(),
20894                implementer_roster: Vec::new(),
20895                judge_roster: Vec::new(),
20896                reviewer_roster: Vec::new(),
20897            },
20898            sem: Arc::new(Semaphore::new(1)),
20899            pause: Pause::new(),
20900            interrupt: Pause::new(),
20901        };
20902
20903        runner.merge().await.expect("merge");
20904
20905        assert_eq!(
20906            runner.state.status,
20907            RunStatus::Ready,
20908            "a concluded run's status must not change on reentry"
20909        );
20910        assert_eq!(
20911            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
20912            Some("already concluded"),
20913            "merge must not run again once the node already recorded an outcome"
20914        );
20915    }
20916
20917    /// `gate` leaves `state.gate_ran` false both before it has ever run and
20918    /// when its last attempt was resource-blocked (the shared build cache
20919    /// could not be acquired or confirmed fresh in time - see
20920    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
20921    /// `Vec` this also leaves behind used to read as "nothing failed" and let
20922    /// a run merge a tree the gate never actually checked - exactly the case
20923    /// a contended cache produces on every retry until it clears. `merge`
20924    /// must refuse until `gate` has actually recorded an attempt.
20925    #[tokio::test]
20926    async fn merge_refuses_a_gate_that_has_not_actually_run() {
20927        let tmp = tempfile::tempdir().expect("tempdir");
20928        let repo = tmp.path().join("repo");
20929        std::fs::create_dir_all(&repo).unwrap();
20930        init_repo(&repo);
20931
20932        let mut config = Config::default();
20933        config.merge.mode = MergeMode::Local;
20934
20935        let mut state = RunState::new(
20936            repo.clone(),
20937            "main".to_owned(),
20938            "deadbeef".to_owned(),
20939            "task".to_owned(),
20940            config,
20941        );
20942        state.candidates = vec![Candidate {
20943            index: 0,
20944            label: 'A',
20945            agent: "alpha".to_owned(),
20946            branch: "does-not-exist".to_owned(),
20947            worktree: repo.clone(),
20948            summary: String::new(),
20949            stat: String::new(),
20950            files: 0,
20951            commits: 0,
20952            empty: false,
20953            failed: None,
20954            verified_noop: None,
20955            duration_ms: 0,
20956            folded: false,
20957        }];
20958        state.tally = Some(Tally {
20959            first_choice: BTreeMap::from([('A', 1)]),
20960            borda: BTreeMap::new(),
20961            winner: 'A',
20962            rankings: 1,
20963            unanimous_initial: true,
20964            deliberated: false,
20965            changed_votes: 0,
20966            unanimous_final: true,
20967            tie_break: None,
20968            judges: 0,
20969            present: 0,
20970            quorum: 0,
20971            met_quorum: true,
20972            uncontested: Some("only candidate A produced a change".to_owned()),
20973        });
20974        state.reviews = vec![ReviewRound {
20975            round: 1,
20976            head: "deadbeef".to_owned(),
20977            verified_head: None,
20978            verified_at: None,
20979            reviews: Vec::new(),
20980            e2e: Vec::new(),
20981            fix: None,
20982            blocking: 0,
20983            answered: 0,
20984            expected: 0,
20985            clean: true,
20986            verify_retried: false,
20987            e2e_deferred: false,
20988            e2e_defer_reason: None,
20989            progressed: false,
20990            vote_split: false,
20991            reconsideration: Vec::new(),
20992            verdict: None,
20993        }];
20994        // The point: `gate` has not recorded anything yet.
20995        state.gate = Vec::new();
20996        state.gate_ran = false;
20997        state.status = RunStatus::Gating;
20998
20999        let mut runner = Runner {
21000            state,
21001            roles: ResolvedRoles {
21002                implementers: Vec::new(),
21003                judges: Vec::new(),
21004                reviewers: Vec::new(),
21005                fixer: None,
21006                conductor: conductor(),
21007                implementer_roster: Vec::new(),
21008                judge_roster: Vec::new(),
21009                reviewer_roster: Vec::new(),
21010            },
21011            sem: Arc::new(Semaphore::new(1)),
21012            pause: Pause::new(),
21013            interrupt: Pause::new(),
21014        };
21015
21016        runner.merge().await.expect("merge");
21017
21018        assert!(
21019            runner.state.merge.is_none(),
21020            "an empty gate must never be read as a passing one: {:?}",
21021            runner.state.merge
21022        );
21023    }
21024
21025    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21026    /// commands configured and `merge.mode` is `none` (a review-only run).
21027    /// `gate` must still record a real attempt — zero commands, vacuously
21028    /// passed — rather than leaving `state.gate` empty in a way `merge`
21029    /// cannot tell apart from "never ran"; otherwise the run reaches
21030    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21031    #[tokio::test]
21032    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21033        let tmp = tempfile::tempdir().expect("tempdir");
21034        let repo = tmp.path().join("repo");
21035        std::fs::create_dir_all(&repo).unwrap();
21036        init_repo(&repo);
21037
21038        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21039        let config = Config::default();
21040
21041        let mut state = RunState::new(
21042            repo.clone(),
21043            "main".to_owned(),
21044            "deadbeef".to_owned(),
21045            "task".to_owned(),
21046            config,
21047        );
21048        state.candidates = vec![Candidate {
21049            index: 0,
21050            label: 'A',
21051            agent: "alpha".to_owned(),
21052            branch: "does-not-exist".to_owned(),
21053            worktree: repo.clone(),
21054            summary: String::new(),
21055            stat: String::new(),
21056            files: 0,
21057            commits: 0,
21058            empty: false,
21059            failed: None,
21060            verified_noop: None,
21061            duration_ms: 0,
21062            folded: false,
21063        }];
21064        state.tally = Some(Tally {
21065            first_choice: BTreeMap::from([('A', 1)]),
21066            borda: BTreeMap::new(),
21067            winner: 'A',
21068            rankings: 1,
21069            unanimous_initial: true,
21070            deliberated: false,
21071            changed_votes: 0,
21072            unanimous_final: true,
21073            tie_break: None,
21074            judges: 0,
21075            present: 0,
21076            quorum: 0,
21077            met_quorum: true,
21078            uncontested: Some("only candidate A produced a change".to_owned()),
21079        });
21080        state.reviews = vec![ReviewRound {
21081            round: 1,
21082            head: "deadbeef".to_owned(),
21083            verified_head: None,
21084            verified_at: None,
21085            reviews: Vec::new(),
21086            e2e: Vec::new(),
21087            fix: None,
21088            blocking: 0,
21089            answered: 0,
21090            expected: 0,
21091            clean: true,
21092            verify_retried: false,
21093            e2e_deferred: false,
21094            e2e_defer_reason: None,
21095            progressed: false,
21096            vote_split: false,
21097            reconsideration: Vec::new(),
21098            verdict: None,
21099        }];
21100
21101        let mut runner = Runner {
21102            state,
21103            roles: ResolvedRoles {
21104                implementers: Vec::new(),
21105                judges: Vec::new(),
21106                reviewers: Vec::new(),
21107                fixer: None,
21108                conductor: conductor(),
21109                implementer_roster: Vec::new(),
21110                judge_roster: Vec::new(),
21111                reviewer_roster: Vec::new(),
21112            },
21113            sem: Arc::new(Semaphore::new(1)),
21114            pause: Pause::new(),
21115            interrupt: Pause::new(),
21116        };
21117
21118        runner.gate().await.expect("gate");
21119        assert!(
21120            runner.state.gate_ran,
21121            "zero configured commands is still a real attempt, not an unrun gate"
21122        );
21123        assert!(runner.state.gate.is_empty());
21124        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21125        assert_ne!(
21126            runner.state.status,
21127            RunStatus::Blocked,
21128            "a gate with nothing to check must not read as failed"
21129        );
21130
21131        runner.merge().await.expect("merge");
21132        assert_eq!(
21133            runner.state.status,
21134            RunStatus::Ready,
21135            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21136        );
21137    }
21138
21139    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21140    /// `verify.gate` (so the e2e leg and the final gate never build against
21141    /// different directories). With zero `verify.gate` commands but a
21142    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21143    /// that lease before discovering it had nothing to run - so a repo with
21144    /// no gate commands could come back `resource_blocked` (and therefore
21145    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21146    /// cache, exactly the contention this run's own zero commands could
21147    /// never have touched. `gate` must recognise there is nothing to check
21148    /// before it ever asks for the lease.
21149    #[tokio::test]
21150    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21151        crate::run::pin_test_home();
21152        let home = crate::run::home();
21153
21154        let tmp = tempfile::tempdir().expect("tempdir");
21155        let repo = tmp.path().join("repo");
21156        std::fs::create_dir_all(&repo).unwrap();
21157        init_repo(&repo);
21158        // Unique to this test, so holding its lease cannot collide with
21159        // another test sharing the same process-wide `home`.
21160        let cache_dir = tmp.path().join("target");
21161
21162        let mut config = Config::default();
21163        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21164        // `verify.gate` stays empty (the default). Any accidental cache
21165        // acquisition must report contention immediately, regardless of how
21166        // long unrelated Git subprocesses take under parallel test load.
21167        config.graph.timeout_verify = Some(2);
21168        config.graph.timeout_resource_wait = 0;
21169
21170        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21171        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21172            .expect("no io error acquiring directly")
21173        {
21174            crate::cache::AcquireOutcome::Acquired(g) => g,
21175            crate::cache::AcquireOutcome::Busy(b) => {
21176                panic!("expected the direct acquire to win the lease first: {b:?}")
21177            }
21178        };
21179
21180        let mut state = RunState::new(
21181            repo.clone(),
21182            "main".to_owned(),
21183            "deadbeef".to_owned(),
21184            "task".to_owned(),
21185            config,
21186        );
21187        state.candidates = vec![Candidate {
21188            index: 0,
21189            label: 'A',
21190            agent: "alpha".to_owned(),
21191            branch: "does-not-exist".to_owned(),
21192            worktree: repo.clone(),
21193            summary: String::new(),
21194            stat: String::new(),
21195            files: 0,
21196            commits: 0,
21197            empty: false,
21198            failed: None,
21199            verified_noop: None,
21200            duration_ms: 0,
21201            folded: false,
21202        }];
21203        state.tally = Some(Tally {
21204            first_choice: BTreeMap::from([('A', 1)]),
21205            borda: BTreeMap::new(),
21206            winner: 'A',
21207            rankings: 1,
21208            unanimous_initial: true,
21209            deliberated: false,
21210            changed_votes: 0,
21211            unanimous_final: true,
21212            tie_break: None,
21213            judges: 0,
21214            present: 0,
21215            quorum: 0,
21216            met_quorum: true,
21217            uncontested: Some("only candidate A produced a change".to_owned()),
21218        });
21219        state.reviews = vec![ReviewRound {
21220            round: 1,
21221            head: "deadbeef".to_owned(),
21222            verified_head: None,
21223            verified_at: None,
21224            reviews: Vec::new(),
21225            e2e: Vec::new(),
21226            fix: None,
21227            blocking: 0,
21228            answered: 0,
21229            expected: 0,
21230            clean: true,
21231            verify_retried: false,
21232            e2e_deferred: false,
21233            e2e_defer_reason: None,
21234            progressed: false,
21235            vote_split: false,
21236            reconsideration: Vec::new(),
21237            verdict: None,
21238        }];
21239
21240        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21241        state.reviews[0].e2e = vec![CommandOutcome {
21242            command: state.config.verify.e2e[0].clone(),
21243            code: Some(0),
21244            output_tail: String::new(),
21245            duration_ms: 0,
21246            resource_blocked: false,
21247            ..Default::default()
21248        }];
21249        let mut runner = Runner {
21250            state,
21251            roles: ResolvedRoles {
21252                implementers: Vec::new(),
21253                judges: Vec::new(),
21254                reviewers: Vec::new(),
21255                fixer: None,
21256                conductor: conductor(),
21257                implementer_roster: Vec::new(),
21258                judge_roster: Vec::new(),
21259                reviewer_roster: Vec::new(),
21260            },
21261            sem: Arc::new(Semaphore::new(1)),
21262            pause: Pause::new(),
21263            interrupt: Pause::new(),
21264        };
21265
21266        runner.gate().await.expect("gate");
21267        assert!(runner.state.resource_block.is_none());
21268        assert!(
21269            !runner
21270                .state
21271                .events
21272                .iter()
21273                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21274            "a gate with nothing to run must never request the held cache lease"
21275        );
21276        assert!(
21277            runner.state.gate_ran,
21278            "zero commands is still a real, immediate attempt"
21279        );
21280        assert!(runner.state.gate.is_empty());
21281        assert_ne!(
21282            runner.state.status,
21283            RunStatus::Blocked,
21284            "must not read as resource-blocked on a lease it never asked for"
21285        );
21286    }
21287
21288    /// A separate process carries a live worker's environment throughout all
21289    /// verification entry points; the parallel harness never changes its env.
21290    #[cfg(unix)]
21291    #[tokio::test]
21292    async fn verification_is_standalone_inside_a_live_worker() {
21293        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21294        if std::env::var_os(CHILD).is_none() {
21295            let home = tempfile::tempdir().unwrap();
21296            let generation = crate::worker::pin_current(home.path()).unwrap();
21297            let output = std::process::Command::new(std::env::current_exe().unwrap())
21298                .args([
21299                    "--exact",
21300                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21301                    "--nocapture",
21302                ])
21303                .env(CHILD, "1")
21304                .env("MAGI_HOME", home.path())
21305                .env("MAGI_WORKER_HOME", home.path())
21306                .env("MAGI_WORKER_ID", "abcdef")
21307                .env("MAGI_WORKER_GENERATION", &generation.id)
21308                .env("MAGI_WORKER_EXE", &generation.executable)
21309                .env("MAGI_RUN", "verification-parent")
21310                .env("MAGI_NODE", "gate")
21311                .env("MAGI_SEAT", "worker-fixture")
21312                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21313                .env("MAGI_NO_AUTOUPDATE", "0")
21314                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21315                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21316                .env(
21317                    "VERIFY_EXPECT_TOOLCHAIN",
21318                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21319                )
21320                .env(
21321                    "VERIFY_EXPECT_CACHE",
21322                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21323                )
21324                .output()
21325                .unwrap();
21326            assert!(
21327                output.status.success()
21328                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21329                "{}\n{}",
21330                String::from_utf8_lossy(&output.stdout),
21331                String::from_utf8_lossy(&output.stderr)
21332            );
21333            return;
21334        }
21335        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21336        let home = crate::run::home();
21337        let directory = home.join("workers/jobs/abcdef");
21338        std::fs::create_dir_all(&directory).unwrap();
21339        let job = crate::worker::Job {
21340            id: "abcdef".into(),
21341            sequence: 1,
21342            kind: "task".into(),
21343            key: "task:verification".into(),
21344            payload: serde_json::json!({}),
21345            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21346            version: Some(env!("CARGO_PKG_VERSION").into()),
21347            status: crate::worker::Status::Running,
21348            result: None,
21349            pid: Some(std::process::id()),
21350            created_at: 0,
21351            finished_at: None,
21352        };
21353        std::fs::write(
21354            directory.join("job.json"),
21355            serde_json::to_vec(&job).unwrap(),
21356        )
21357        .unwrap();
21358        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21359        let assert_worker = || {
21360            assert_eq!(
21361                crate::worker::current_job(&home).unwrap().unwrap().id,
21362                job.id
21363            );
21364            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21365            assert_eq!(
21366                crate::worker::helper_executable(&home).unwrap(),
21367                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21368            );
21369            assert!(
21370                crate::updater::Checker::new(&crate::config::Update {
21371                    mode: crate::config::UpdateMode::Notify,
21372                    interval: None,
21373                    auto_restart: false,
21374                })
21375                .is_none(),
21376                "the driver remains pinned, even while tests are standalone"
21377            );
21378        };
21379        assert_worker();
21380        let repo = home.join("repo");
21381        std::fs::create_dir_all(&repo).unwrap();
21382        init_repo(&repo);
21383        // Keep storage, seat/control context, containment and tool lookup.
21384        // No inherited values (or credentials) are printed on success.
21385        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21386            test -z "${MAGI_WORKER_GENERATION+x}" &&
21387            test -z "${MAGI_WORKER_HOME+x}" &&
21388            test -z "${MAGI_WORKER_EXE+x}" &&
21389            test "$MAGI_HOME/repo" -ef . &&
21390            test "$MAGI_RUN" = verification-parent &&
21391            test "$MAGI_NODE" = gate &&
21392            test "$MAGI_SEAT" = worker-fixture &&
21393            test -n "$MAGI_PROCESS_OWNER" &&
21394            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21395            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21396            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21397            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21398        // Negative control: an ordinary child inherits the contamination.
21399        assert!(
21400            !std::process::Command::new("sh")
21401                .args(["-c", probe])
21402                .current_dir(&repo)
21403                .status()
21404                .unwrap()
21405                .success()
21406        );
21407        let unrelated_home = tempfile::tempdir().unwrap();
21408        assert!(
21409            crate::worker::current_job(unrelated_home.path()).is_err(),
21410            "an inherited worker id cannot be resolved in a unit fixture's home"
21411        );
21412        let mut runner = runner_at(RunStatus::Gating);
21413        runner.state.repo = repo.clone();
21414        runner.state.config.disk.min_free_bytes = 0;
21415        runner.state.config.coordination = crate::config::test_coordination();
21416        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21417        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21418        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21419        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21420        let winner = Candidate {
21421            index: 0,
21422            label: 'A',
21423            agent: "fixture".into(),
21424            branch: "main".into(),
21425            worktree: repo.clone(),
21426            summary: String::new(),
21427            stat: String::new(),
21428            files: 0,
21429            commits: 0,
21430            empty: false,
21431            failed: None,
21432            verified_noop: None,
21433            duration_ms: 0,
21434            folded: false,
21435        };
21436        let (e2e, retried, pids) = run_e2e_with_retry(
21437            &mut runner.state,
21438            &["sh".into(), "-c".into()],
21439            &[format!("{probe} && printf initial")],
21440            &repo,
21441            Duration::from_secs(10),
21442            "initial",
21443            None,
21444        )
21445        .await;
21446        assert!(!retried && pids.is_empty());
21447        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21448        assert_eq!(e2e[0].output_tail, "initial");
21449        let gate = runner.run_gate(&winner).await.unwrap();
21450        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21451        // An interrupted repair must recheck e2e from saved state. Landing
21452        // reuses that state and must run both pre-gate and gate again.
21453        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
21454            head: git::rev_parse(&repo, "HEAD").await.unwrap(),
21455            passed: false,
21456            outcomes: Vec::new(),
21457        });
21458        runner.state.save().unwrap();
21459        let mut resumed = RunState::load(&runner.state.id).unwrap();
21460        let wait = crate::repo_lock::WaitPolicy::default();
21461        assert!(matches!(
21462            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21463                .await
21464                .unwrap(),
21465            GateFix::Retry
21466        ));
21467        let saved = RunState::load(&resumed.id).unwrap();
21468        let repair = saved.gate_repair_e2e.unwrap();
21469        assert!(repair.passed);
21470        assert_eq!(repair.outcomes.len(), 1);
21471        assert!(repair.outcomes[0].ok());
21472        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21473            .await
21474            .unwrap();
21475        assert_eq!(landing.len(), 1);
21476        assert!(landing[0].ok(), "{landing:?}");
21477        assert_eq!(
21478            std::fs::read_to_string(repo.join("phases")).unwrap(),
21479            "pre\ngate\ne2e\npre\ngate\n"
21480        );
21481        assert_worker();
21482    }
21483
21484    #[cfg(unix)]
21485    #[tokio::test]
21486    async fn verification_keeps_the_panic_and_the_full_output() {
21487        crate::run::pin_test_home();
21488        let tmp = tempfile::tempdir().unwrap();
21489        let mut config = Config::default();
21490        config.disk.min_free_bytes = 0;
21491        let mut state = RunState::new(
21492            tmp.path().to_owned(),
21493            "main".into(),
21494            "base".into(),
21495            "verification evidence".into(),
21496            config,
21497        );
21498        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21499                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21500                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21501        let mut names = Vec::new();
21502        for _ in 0..2 {
21503            let (outcomes, _) = run_commands(
21504                &mut state,
21505                "gate",
21506                "gate",
21507                0,
21508                &["sh".into(), "-c".into()],
21509                &[script.into()],
21510                tmp.path(),
21511                Duration::from_secs(60),
21512            )
21513            .await;
21514            let tail = &outcomes[0].output_tail;
21515            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21516            assert!(tail.contains("boom assertion"));
21517            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21518            let line = tail.lines().next().unwrap();
21519            names.push(line.to_owned());
21520        }
21521        assert_ne!(names[0], names[1], "the second run must not overwrite");
21522        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21523        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21524        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21525
21526        // Storage failures are evidence too; preserve the command's verdict.
21527        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21528        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21529        let (outcomes, _) = run_commands(
21530            &mut state,
21531            "gate",
21532            "gate",
21533            0,
21534            &["sh".into(), "-c".into()],
21535            &["echo failure-output; exit 7".into()],
21536            tmp.path(),
21537            Duration::from_secs(10),
21538        )
21539        .await;
21540        assert_eq!(outcomes[0].code, Some(7));
21541        assert!(state.events.iter().any(|e| {
21542            e.node == "gate" && e.message.contains("could not save the full gate output:")
21543        }));
21544    }
21545
21546    #[cfg(unix)]
21547    #[tokio::test]
21548    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21549        crate::run::pin_test_home();
21550        let tmp = tempfile::tempdir().unwrap();
21551        let mut config = Config::default();
21552        config.disk.min_free_bytes = 0;
21553        let mut state = RunState::new(
21554            tmp.path().to_owned(),
21555            "main".into(),
21556            "base".into(),
21557            "verification evidence".into(),
21558            config,
21559        );
21560        let (outcomes, pids) = run_commands(
21561            &mut state,
21562            "gate",
21563            "gate",
21564            1,
21565            &["sh".into(), "-c".into()],
21566            &[
21567                "printf before-timeout; exec sleep 30".into(),
21568                "kill -TERM $$".into(),
21569                "exit 7".into(),
21570                "printf success".into(),
21571            ],
21572            tmp.path(),
21573            Duration::from_secs(1),
21574        )
21575        .await;
21576        wait_for_timed_out_children_to_die(&pids).await;
21577        assert_eq!(
21578            pids.len(),
21579            1,
21580            "unleased timeout retains its death-check PID"
21581        );
21582        assert_eq!(outcomes.len(), 4);
21583        assert_eq!(outcomes[0].code, None);
21584        assert!(outcomes[0].output_tail.contains("before-timeout"));
21585        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21586        assert_eq!(outcomes[1].code, None);
21587        assert!(outcomes[1].output_tail.contains("command terminated:"));
21588        assert!(!outcomes[1].output_tail.contains("timed out"));
21589        assert_eq!(outcomes[2].code, Some(7));
21590        assert!(!outcomes[2].output_tail.contains("timed out"));
21591        assert_eq!(outcomes[3].code, Some(0));
21592        assert_eq!(outcomes[3].output_tail, "success");
21593        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21594    }
21595
21596    /// The addendum's second gap: a `verify.gate` command running for real
21597    /// wall-clock time had nothing at all to show for it in `active` before
21598    /// `run_commands` learned to record it — a run could sit in `Gating` for
21599    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21600    /// what was actually happening. Proven with a genuinely still-running
21601    /// command, not just a before/after check on the final state: a poller
21602    /// task reads the same `run.json` `gate()` is writing, the same way the
21603    /// phone or `magi show` would, while the shell command is still blocked
21604    /// on its own release marker.
21605    #[tokio::test]
21606    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21607        crate::run::pin_test_home();
21608
21609        let tmp = tempfile::tempdir().expect("tempdir");
21610        let repo = tmp.path().join("repo");
21611        std::fs::create_dir_all(&repo).unwrap();
21612        init_repo(&repo);
21613
21614        let mut config = Config::default();
21615        config.disk.min_free_bytes = 0;
21616        config.verify.gate = vec![
21617            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21618             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21619                .to_owned(),
21620        ];
21621
21622        let mut state = RunState::new(
21623            repo.clone(),
21624            "main".to_owned(),
21625            "deadbeef".to_owned(),
21626            "task".to_owned(),
21627            config,
21628        );
21629        let run_id = state.id.clone();
21630        state.candidates = vec![Candidate {
21631            index: 0,
21632            label: 'A',
21633            agent: "alpha".to_owned(),
21634            branch: "does-not-exist".to_owned(),
21635            worktree: repo.clone(),
21636            summary: String::new(),
21637            stat: String::new(),
21638            files: 0,
21639            commits: 0,
21640            empty: false,
21641            failed: None,
21642            verified_noop: None,
21643            duration_ms: 0,
21644            folded: false,
21645        }];
21646        state.tally = Some(Tally {
21647            first_choice: BTreeMap::from([('A', 1)]),
21648            borda: BTreeMap::new(),
21649            winner: 'A',
21650            rankings: 1,
21651            unanimous_initial: true,
21652            deliberated: false,
21653            changed_votes: 0,
21654            unanimous_final: true,
21655            tie_break: None,
21656            judges: 0,
21657            present: 0,
21658            quorum: 0,
21659            met_quorum: true,
21660            uncontested: Some("only candidate A produced a change".to_owned()),
21661        });
21662        state.reviews = vec![ReviewRound {
21663            round: 1,
21664            head: "deadbeef".to_owned(),
21665            verified_head: None,
21666            verified_at: None,
21667            reviews: Vec::new(),
21668            e2e: Vec::new(),
21669            fix: None,
21670            blocking: 0,
21671            answered: 0,
21672            expected: 0,
21673            clean: true,
21674            verify_retried: false,
21675            e2e_deferred: false,
21676            e2e_defer_reason: None,
21677            progressed: false,
21678            vote_split: false,
21679            reconsideration: Vec::new(),
21680            verdict: None,
21681        }];
21682
21683        let mut runner = Runner {
21684            state,
21685            roles: ResolvedRoles {
21686                implementers: Vec::new(),
21687                judges: Vec::new(),
21688                reviewers: Vec::new(),
21689                fixer: None,
21690                conductor: conductor(),
21691                implementer_roster: Vec::new(),
21692                judge_roster: Vec::new(),
21693                reviewer_roster: Vec::new(),
21694            },
21695            sem: Arc::new(Semaphore::new(1)),
21696            pause: Pause::new(),
21697            interrupt: Pause::new(),
21698        };
21699
21700        let started_marker = repo.join("started.marker");
21701        let release_marker = repo.join("release.marker");
21702        let observe = async {
21703            loop {
21704                if started_marker.exists()
21705                    && let Ok(s) = crate::run::RunState::load(&run_id)
21706                    && let Some(a) = s.active.get("gate")
21707                {
21708                    std::fs::write(&release_marker, b"go").expect("release marker");
21709                    break a.clone();
21710                }
21711                tokio::time::sleep(Duration::from_millis(50)).await;
21712            }
21713        };
21714        let captured = {
21715            let gate = runner.gate();
21716            tokio::pin!(gate);
21717            let captured = tokio::select! {
21718                observed = observe => observed,
21719                result = &mut gate => panic!(
21720                    "gate exited before its in-flight entry was observed: {result:?}"
21721                ),
21722            };
21723            gate.await.expect("gate");
21724            captured
21725        };
21726
21727        assert_eq!(captured.task.as_deref(), Some("gate"));
21728        assert_eq!(captured.node, "gate");
21729        assert_eq!(captured.index, Some(1));
21730        assert_eq!(captured.total, Some(1));
21731        assert!(
21732            captured
21733                .command
21734                .as_deref()
21735                .is_some_and(|c| c.contains("started.marker")),
21736            "{captured:?}"
21737        );
21738
21739        assert!(
21740            runner.state.active.is_empty(),
21741            "the entry must be cleared once the command actually finished: {:?}",
21742            runner.state.active
21743        );
21744        assert!(runner.state.gate_ran);
21745        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
21746    }
21747
21748    /// The hand-off over a blocking finding a reviewer rejected on leaves a
21749    /// record for `land`; one with only a Minor, or no reject, leaves none.
21750    #[tokio::test]
21751    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
21752        use crate::verdict::{Finding, ReviewVote, Severity};
21753        crate::run::pin_test_home();
21754        let tmp = tempfile::tempdir().expect("tempdir");
21755        let repo = tmp.path().join("repo");
21756        std::fs::create_dir_all(&repo).unwrap();
21757        init_repo(&repo);
21758
21759        for (severity, vote, expect) in [
21760            (Severity::Major, ReviewVote::Reject, true),
21761            (Severity::Minor, ReviewVote::Reject, false),
21762            (Severity::Major, ReviewVote::Approve, false),
21763        ] {
21764            let mut round = review_round(false, 1, 1, 1, false, true);
21765            round.reviews = vec![ReviewRecord {
21766                reviewer: 1,
21767                agent: "alpha".to_owned(),
21768                summary: String::new(),
21769                findings: vec![Finding {
21770                    id: "R1-1-1".to_owned(),
21771                    severity,
21772                    file: None,
21773                    line: None,
21774                    title: "t".to_owned(),
21775                    detail: String::new(),
21776                }],
21777                vote: Some(vote),
21778                failed: None,
21779                duration_ms: 0,
21780                attempts: 0,
21781            }];
21782            let mut state = RunState::new(
21783                repo.clone(),
21784                "main".to_owned(),
21785                "deadbeef".to_owned(),
21786                "task".to_owned(),
21787                Config::default(),
21788            );
21789            state.reviews = vec![round];
21790            let mut runner = Runner {
21791                state,
21792                roles: ResolvedRoles {
21793                    implementers: Vec::new(),
21794                    judges: Vec::new(),
21795                    reviewers: Vec::new(),
21796                    fixer: None,
21797                    conductor: conductor(),
21798                    implementer_roster: Vec::new(),
21799                    judge_roster: Vec::new(),
21800                    reviewer_roster: Vec::new(),
21801                },
21802                sem: Arc::new(Semaphore::new(1)),
21803                pause: Pause::new(),
21804                interrupt: Pause::new(),
21805            };
21806            let shell = runner.state.config.shell();
21807            runner
21808                .stop_reviewing("round budget spent", &shell, &repo)
21809                .await
21810                .expect("stop_reviewing");
21811            assert_eq!(runner.state.status, RunStatus::Gating);
21812            assert_eq!(
21813                runner.state.contested_handoff.is_some(),
21814                expect,
21815                "{severity:?} + {vote:?}"
21816            );
21817        }
21818    }
21819
21820    /// The shape the incident this whole fix responds to actually had: the
21821    /// round budget spent, the last round's own e2e blocked on the shared
21822    /// build cache (held here by a live pid — this test process — exactly
21823    /// `cache`'s own unit tests' pattern for "another owner, still alive"
21824    /// without forking a process). `stop_reviewing` must retry it — not
21825    /// silently leave the round looking untouched (the catch-up-only half of
21826    /// the bug), and not read the contention as a red `e2e` and block the
21827    /// run on it (the other half). Called directly, the same way
21828    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
21829    /// above exercises `gate`, so this never needs a real cargo build to
21830    /// reach: the lease is never released, so `with_cache_lease` never gets
21831    /// past acquiring it into anything that would need a real workspace.
21832    #[tokio::test]
21833    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
21834        crate::run::pin_test_home();
21835        let home = crate::run::home();
21836
21837        let tmp = tempfile::tempdir().expect("tempdir");
21838        let repo = tmp.path().join("repo");
21839        std::fs::create_dir_all(&repo).unwrap();
21840        init_repo(&repo);
21841        let head = crate::git::rev_parse(&repo, "HEAD")
21842            .await
21843            .expect("rev-parse");
21844        // Unique to this test, so holding its lease cannot collide with
21845        // another test sharing the same process-wide `home`.
21846        let cache_dir = tmp.path().join("target");
21847
21848        let mut config = Config::default();
21849        config.verify.e2e = vec![format!(
21850            "CARGO_TARGET_DIR='{}' test -f README.md",
21851            cache_dir.display()
21852        )];
21853        config.graph.review_rounds = 1;
21854        // Bounded so a regression that does start waiting fails the test in
21855        // seconds, not hangs it.
21856        config.graph.timeout_verify = Some(2);
21857        config.graph.timeout_resource_wait = 2;
21858
21859        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21860        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21861            .expect("no io error acquiring directly")
21862        {
21863            crate::cache::AcquireOutcome::Acquired(g) => g,
21864            crate::cache::AcquireOutcome::Busy(b) => {
21865                panic!("expected the direct acquire to win the lease first: {b:?}")
21866            }
21867        };
21868
21869        let mut state = RunState::new(
21870            repo.clone(),
21871            "main".to_owned(),
21872            head.clone(),
21873            "task".to_owned(),
21874            config,
21875        );
21876        state.candidates = vec![Candidate {
21877            index: 0,
21878            label: 'A',
21879            agent: "alpha".to_owned(),
21880            branch: "does-not-exist".to_owned(),
21881            worktree: repo.clone(),
21882            summary: String::new(),
21883            stat: String::new(),
21884            files: 0,
21885            commits: 0,
21886            empty: false,
21887            failed: None,
21888            verified_noop: None,
21889            duration_ms: 0,
21890            folded: false,
21891        }];
21892        state.tally = Some(Tally {
21893            first_choice: BTreeMap::from([('A', 1)]),
21894            borda: BTreeMap::new(),
21895            winner: 'A',
21896            rankings: 1,
21897            unanimous_initial: true,
21898            deliberated: false,
21899            changed_votes: 0,
21900            unanimous_final: true,
21901            tie_break: None,
21902            judges: 0,
21903            present: 0,
21904            quorum: 0,
21905            met_quorum: true,
21906            uncontested: Some("only candidate A produced a change".to_owned()),
21907        });
21908        // The round budget's last round, deferred: `needs_catchup_run`'s
21909        // other trigger. `stop_reviewing`'s retry machinery must treat this
21910        // exactly like a resource-blocked attempt once it actually runs.
21911        state.reviews = vec![ReviewRound {
21912            round: 1,
21913            head: head.clone(),
21914            verified_head: None,
21915            verified_at: None,
21916            reviews: Vec::new(),
21917            e2e: Vec::new(),
21918            fix: None,
21919            blocking: 1,
21920            answered: 1,
21921            expected: 1,
21922            clean: false,
21923            verify_retried: false,
21924            e2e_deferred: true,
21925            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
21926            progressed: false,
21927            vote_split: false,
21928            reconsideration: Vec::new(),
21929            verdict: None,
21930        }];
21931
21932        let mut runner = Runner {
21933            state,
21934            roles: ResolvedRoles {
21935                implementers: Vec::new(),
21936                judges: Vec::new(),
21937                reviewers: Vec::new(),
21938                fixer: None,
21939                conductor: conductor(),
21940                implementer_roster: Vec::new(),
21941                judge_roster: Vec::new(),
21942                reviewer_roster: Vec::new(),
21943            },
21944            sem: Arc::new(Semaphore::new(1)),
21945            pause: Pause::new(),
21946            interrupt: Pause::new(),
21947        };
21948
21949        let shell = runner.state.config.shell();
21950        runner
21951            .stop_reviewing("round budget spent", &shell, &repo)
21952            .await
21953            .expect("stop_reviewing");
21954
21955        let last = runner.state.reviews.last().expect("round record");
21956        assert_eq!(
21957            last.e2e_status(),
21958            E2eStatus::ResourceBlocked,
21959            "the shared cache is still held; the attempt must read as blocked, not deferred or \
21960             failed: {last:?}"
21961        );
21962        assert_eq!(
21963            last.verified_head.as_deref(),
21964            Some(head.as_str()),
21965            "which commit this attempt targeted is known even though nothing finished checking \
21966             it"
21967        );
21968        let first_attempt_at = last
21969            .verified_at
21970            .expect("when this attempt ran is known too");
21971        assert_ne!(
21972            runner.state.status,
21973            RunStatus::Blocked,
21974            "contention is evidence about the machine, not the patch — it must not settle the \
21975             run as blocked: {:?}",
21976            runner.state.status
21977        );
21978        assert!(
21979            !runner
21980                .state
21981                .events
21982                .iter()
21983                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
21984            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
21985            runner.state.events
21986        );
21987
21988        // The cache is still held: a later reentry must retry the same
21989        // round's verification again — not leave it looking exactly as
21990        // untouched as the first blocked attempt, which is indistinguishable
21991        // from never having tried again at all.
21992        runner
21993            .stop_reviewing("round budget spent", &shell, &repo)
21994            .await
21995            .expect("stop_reviewing retry");
21996        assert_eq!(
21997            runner.state.reviews.len(),
21998            1,
21999            "no new round was started: {:?}",
22000            runner.state.reviews
22001        );
22002        let last = runner.state.reviews.last().expect("round record");
22003        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22004        assert!(
22005            last.verified_at.expect("still known") > first_attempt_at,
22006            "a second reentry must be a fresh attempt, not a stale copy of the first"
22007        );
22008        assert_ne!(runner.state.status, RunStatus::Blocked);
22009
22010        held.release();
22011    }
22012
22013    #[cfg(unix)]
22014    #[tokio::test]
22015    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22016        ask_test_home();
22017        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22018            let tmp = tempfile::tempdir().unwrap();
22019            let repo = tmp.path().join("repo");
22020            std::fs::create_dir(&repo).unwrap();
22021            init_repo(&repo);
22022            let run_git = |args: &[&str]| {
22023                let out = std::process::Command::new("git")
22024                    .args(args)
22025                    .current_dir(&repo)
22026                    .output()
22027                    .unwrap();
22028                assert!(
22029                    out.status.success(),
22030                    "{args:?}: {}",
22031                    String::from_utf8_lossy(&out.stderr)
22032                );
22033            };
22034            let origin = tmp.path().join("origin.git");
22035            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22036            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22037            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22038            run_git(&["add", "spec.rs"]);
22039            run_git(&["commit", "-m", "initial spec"]);
22040            run_git(&["push", "origin", "main"]);
22041            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22042            run_git(&["checkout", "-b", "fix/review"]);
22043            std::fs::write(
22044                repo.join("check.rs"),
22045                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22046            )
22047            .unwrap();
22048            run_git(&["add", "check.rs"]);
22049            run_git(&["commit", "-m", "use spec"]);
22050            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22051            run_git(&["checkout", "main"]);
22052            std::fs::write(
22053                repo.join("spec.rs"),
22054                "struct AgentSpec { max_turn_secs: u64 }\n",
22055            )
22056            .unwrap();
22057            run_git(&["add", "spec.rs"]);
22058            run_git(&["commit", "-m", "extend spec"]);
22059            run_git(&["push", "origin", "main"]);
22060            run_git(&["checkout", "fix/review"]);
22061
22062            let mut runner = runner_at(RunStatus::Reviewing);
22063            runner.state.repo = repo.clone();
22064            runner.state.base_commit = base;
22065            runner.state.pr_head = Some("fix/review".into());
22066            runner.state.config.graph.review_rounds = max_rounds;
22067            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22068            runner.state.config.graph.sessions = false;
22069            runner.state.config.disk.min_free_bytes = 0;
22070            runner.state.config.verify.e2e =
22071                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22072            runner.state.candidates = vec![Candidate {
22073                index: 0,
22074                label: 'A',
22075                agent: "fixture".into(),
22076                branch: "fix/review".into(),
22077                worktree: repo.clone(),
22078                summary: String::new(),
22079                stat: String::new(),
22080                files: 1,
22081                commits: 1,
22082                empty: false,
22083                failed: None,
22084                verified_noop: None,
22085                duration_ms: 0,
22086                folded: false,
22087            }];
22088            runner.state.tally = Some(Tally {
22089                first_choice: BTreeMap::new(),
22090                borda: BTreeMap::new(),
22091                winner: 'A',
22092                rankings: 0,
22093                unanimous_initial: true,
22094                deliberated: false,
22095                changed_votes: 0,
22096                unanimous_final: true,
22097                tie_break: None,
22098                judges: 0,
22099                present: 0,
22100                quorum: 0,
22101                met_quorum: true,
22102                uncontested: Some("review-only".into()),
22103            });
22104            let mut last = review_round(false, 0, 1, 1, false, false);
22105            last.head = reviewed.clone();
22106            last.e2e_deferred = true;
22107            last.e2e[0].resource_blocked = true;
22108            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22109            if max_rounds == 1 {
22110                last.e2e.clear();
22111            }
22112            runner.state.reviews = vec![last];
22113            let calls = tmp.path().join("fix-calls");
22114            let mut fixer = spec("repair");
22115            fixer
22116                .env
22117                .insert("FIX_CALLS".into(), calls.display().to_string());
22118            fixer.command = vec!["sh".into(), "-c".into(), r#"
22119                echo fix >> "$FIX_CALLS"
22120                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22121                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22122                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22123                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22124            "#.into()];
22125            let mut reviewer = spec("reviewer");
22126            reviewer.command = vec![
22127                "sh".into(),
22128                "-c".into(),
22129                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22130                    .into(),
22131            ];
22132            runner.roles.fixer = Some(vec![fixer]);
22133            runner.roles.reviewers = vec![reviewer];
22134
22135            runner.sync_to_base().await.unwrap();
22136            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22137            assert_ne!(rebased, reviewed);
22138            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22139            if reentry {
22140                // Simulate a crash after catch-up evidence was saved but before
22141                // dispatching the fixer. No dedicated pending-repair field exists.
22142                let shell = runner.state.config.shell();
22143                runner
22144                    .stop_unresolved_review("deferred verification", &shell, &repo)
22145                    .await
22146                    .unwrap();
22147                assert!(runner.catchup_repairable());
22148                assert!(!calls.exists());
22149                runner.state = RunState::load(&runner.state.id).unwrap();
22150                assert!(runner.catchup_repairable());
22151            }
22152            runner.review_loop().await.unwrap();
22153            let first = &runner.state.reviews[0];
22154            assert_eq!(first.head, reviewed);
22155            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22156            assert!(
22157                first.verify_retried,
22158                "a reproduced build failure gets exactly one retry: {:?}",
22159                first.e2e
22160            );
22161            assert!(first.e2e[0].output_tail.contains("E0063"));
22162            assert!(!runner.catchup_repairable());
22163            if max_rounds == 2 {
22164                assert_eq!(
22165                    runner.state.status,
22166                    RunStatus::Gating,
22167                    "{}",
22168                    crate::report::run(&runner.state)
22169                );
22170                assert_eq!(runner.state.reviews.len(), 2);
22171                assert!(first.fix.as_ref().unwrap().committed);
22172                assert!(runner.state.reviews[1].clean);
22173                assert_eq!(
22174                    runner
22175                        .state
22176                        .reviews
22177                        .iter()
22178                        .filter(|r| r.fix.is_some())
22179                        .count(),
22180                    1
22181                );
22182                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22183                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22184            } else {
22185                assert_eq!(runner.state.status, RunStatus::Blocked);
22186                assert!(first.fix.is_none());
22187                assert!(!calls.exists());
22188                let recovery = crate::recovery::assess(
22189                    "prior",
22190                    Some(&runner.state),
22191                    &runner.landing_base(),
22192                    crate::recovery::Relation::Diverged,
22193                );
22194                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22195                let reasons = recovery.reasons.join("\n");
22196                assert!(
22197                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22198                    "{reasons}"
22199                );
22200                assert!(
22201                    reasons.contains("base sync to")
22202                        && reasons.contains("additional review is required"),
22203                    "{reasons}"
22204                );
22205            }
22206        }
22207    }
22208
22209    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22210    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22211    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22212    /// own top-of-function fast path (`review_conclusion`) correctly reads
22213    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22214    /// own `for` range is empty once the round budget is spent, so
22215    /// `review_loop` must retry the check itself rather than silently doing
22216    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22217    /// above exercises directly, but through `review_loop`'s own entry point
22218    /// this time, proving the wiring between the two rather than just the
22219    /// retry logic in isolation.
22220    #[tokio::test]
22221    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22222        crate::run::pin_test_home();
22223        let home = crate::run::home();
22224
22225        let tmp = tempfile::tempdir().expect("tempdir");
22226        let repo = tmp.path().join("repo");
22227        std::fs::create_dir_all(&repo).unwrap();
22228        init_repo(&repo);
22229        let head = crate::git::rev_parse(&repo, "HEAD")
22230            .await
22231            .expect("rev-parse");
22232        let cache_dir = tmp.path().join("target");
22233
22234        let mut config = Config::default();
22235        config.verify.e2e = vec![format!(
22236            "CARGO_TARGET_DIR='{}' test -f README.md",
22237            cache_dir.display()
22238        )];
22239        config.graph.review_rounds = 1;
22240        config.graph.timeout_verify = Some(2);
22241        config.graph.timeout_resource_wait = 2;
22242
22243        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22244        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22245            .expect("no io error acquiring directly")
22246        {
22247            crate::cache::AcquireOutcome::Acquired(g) => g,
22248            crate::cache::AcquireOutcome::Busy(b) => {
22249                panic!("expected the direct acquire to win the lease first: {b:?}")
22250            }
22251        };
22252
22253        let mut state = RunState::new(
22254            repo.clone(),
22255            "main".to_owned(),
22256            head.clone(),
22257            "task".to_owned(),
22258            config,
22259        );
22260        state.candidates = vec![Candidate {
22261            index: 0,
22262            label: 'A',
22263            agent: "alpha".to_owned(),
22264            branch: "does-not-exist".to_owned(),
22265            worktree: repo.clone(),
22266            summary: String::new(),
22267            stat: String::new(),
22268            files: 0,
22269            commits: 0,
22270            empty: false,
22271            failed: None,
22272            verified_noop: None,
22273            duration_ms: 0,
22274            folded: false,
22275        }];
22276        state.tally = Some(Tally {
22277            first_choice: BTreeMap::from([('A', 1)]),
22278            borda: BTreeMap::new(),
22279            winner: 'A',
22280            rankings: 1,
22281            unanimous_initial: true,
22282            deliberated: false,
22283            changed_votes: 0,
22284            unanimous_final: true,
22285            tie_break: None,
22286            judges: 0,
22287            present: 0,
22288            quorum: 0,
22289            met_quorum: true,
22290            uncontested: Some("only candidate A produced a change".to_owned()),
22291        });
22292        // The exact shape a prior process's `stop_reviewing` would have left
22293        // on disk: the round budget's last round, a real attempt already
22294        // made and already resource-blocked.
22295        state.reviews = vec![ReviewRound {
22296            round: 1,
22297            head: head.clone(),
22298            verified_head: Some(head.clone()),
22299            verified_at: Some(jiff::Timestamp::now()),
22300            reviews: Vec::new(),
22301            e2e: vec![CommandOutcome {
22302                command: format!(
22303                    "CARGO_TARGET_DIR='{}' test -f README.md",
22304                    cache_dir.display()
22305                ),
22306                code: None,
22307                output_tail: "waiting for the shared build cache".to_owned(),
22308                duration_ms: 0,
22309                resource_blocked: true,
22310                ..Default::default()
22311            }],
22312            fix: None,
22313            blocking: 1,
22314            answered: 1,
22315            expected: 1,
22316            clean: false,
22317            verify_retried: false,
22318            e2e_deferred: false,
22319            e2e_defer_reason: None,
22320            progressed: false,
22321            vote_split: false,
22322            reconsideration: Vec::new(),
22323            verdict: None,
22324        }];
22325
22326        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22327        let mut runner = Runner {
22328            state,
22329            roles: ResolvedRoles {
22330                implementers: Vec::new(),
22331                judges: Vec::new(),
22332                reviewers: Vec::new(),
22333                fixer: None,
22334                conductor: conductor(),
22335                implementer_roster: Vec::new(),
22336                judge_roster: Vec::new(),
22337                reviewer_roster: Vec::new(),
22338            },
22339            sem: Arc::new(Semaphore::new(1)),
22340            pause: Pause::new(),
22341            interrupt: Pause::new(),
22342        };
22343
22344        // The lease is still held throughout, so this reentry's own retry is
22345        // also contended — proving `review_loop` actually tried again (not
22346        // that it happened to succeed) is what the timestamp comparison
22347        // below is for.
22348        runner.review_loop().await.expect("review_loop");
22349
22350        assert_eq!(
22351            runner.state.reviews.len(),
22352            1,
22353            "no new round was started on top of the unresolved one: {:?}",
22354            runner.state.reviews
22355        );
22356        let last = &runner.state.reviews[0];
22357        assert_eq!(
22358            last.e2e_status(),
22359            E2eStatus::ResourceBlocked,
22360            "still contended: {last:?}"
22361        );
22362        assert!(
22363            last.verified_at.expect("still known") > first_attempt_at,
22364            "review_loop must have actually retried the check, not left it exactly as found"
22365        );
22366        assert_ne!(
22367            runner.state.status,
22368            RunStatus::Blocked,
22369            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22370            runner.state.status
22371        );
22372
22373        held.release();
22374    }
22375
22376    #[tokio::test]
22377    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22378        crate::run::pin_test_home();
22379        for status in [RunStatus::Blocked, RunStatus::Gating] {
22380            let mut runner = runner_at(status);
22381            runner.state.config.graph.land = true;
22382            runner.state.gate_ran = true;
22383            runner.state.merge = Some(MergeOutcome {
22384                mode: MergeMode::Pr,
22385                ok: false,
22386                detail: "the fixer produced no commit".into(),
22387                empty: false,
22388            });
22389            let url = "https://example.invalid/o/r/pull/1";
22390            runner.state.pr = Some(crate::run::PrRecord {
22391                url: url.into(),
22392                number: 1,
22393                state: "open".into(),
22394                checks: "red".into(),
22395                round: 1,
22396                rounds: 1,
22397                red_at_merge: Vec::new(),
22398            });
22399            runner.state.save().unwrap();
22400            // The nonexistent repository makes observation fail before a forge
22401            // command can run. We still must reach land, rather than silently
22402            // return from the graph with its old gate and merge records.
22403            runner.execute_graph().await.unwrap();
22404            assert_eq!(runner.state.status, RunStatus::Blocked);
22405            assert!(runner.state.land_sync_pending);
22406            assert!(runner.state.events.iter().any(|event|
22407                event.node == "land" && event.message == format!("watching {url}")));
22408            assert_eq!(
22409                runner.state.merge.as_ref().unwrap().detail,
22410                "the fixer produced no commit"
22411            );
22412        }
22413    }
22414
22415    #[tokio::test]
22416    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22417        crate::run::pin_test_home();
22418        let tmp = tempfile::tempdir().expect("tempdir");
22419        let repo = tmp.path().join("repo");
22420        std::fs::create_dir_all(&repo).unwrap();
22421        init_repo(&repo);
22422
22423        let mut config = Config::default();
22424        config.merge.mode = MergeMode::Pr;
22425        config.graph.land = true;
22426        config.graph.land_approval = false;
22427
22428        let mut state = RunState::new(
22429            repo.clone(),
22430            "main".to_owned(),
22431            "deadbeef".to_owned(),
22432            "task".to_owned(),
22433            config,
22434        );
22435        state.candidates = vec![Candidate {
22436            index: 0,
22437            label: 'A',
22438            agent: "alpha".to_owned(),
22439            branch: "does-not-exist".to_owned(),
22440            worktree: repo.clone(),
22441            summary: String::new(),
22442            stat: String::new(),
22443            files: 0,
22444            commits: 0,
22445            empty: false,
22446            failed: None,
22447            verified_noop: None,
22448            duration_ms: 0,
22449            folded: false,
22450        }];
22451        state.tally = Some(Tally {
22452            first_choice: BTreeMap::from([('A', 1)]),
22453            borda: BTreeMap::new(),
22454            winner: 'A',
22455            rankings: 1,
22456            unanimous_initial: true,
22457            deliberated: false,
22458            changed_votes: 0,
22459            unanimous_final: true,
22460            tie_break: None,
22461            judges: 0,
22462            present: 0,
22463            quorum: 0,
22464            met_quorum: true,
22465            uncontested: Some("only candidate A produced a change".to_owned()),
22466        });
22467        state.reviews = vec![ReviewRound {
22468            round: 1,
22469            head: "deadbeef".to_owned(),
22470            verified_head: None,
22471            verified_at: None,
22472            reviews: Vec::new(),
22473            e2e: Vec::new(),
22474            fix: None,
22475            blocking: 0,
22476            answered: 0,
22477            expected: 0,
22478            clean: true,
22479            verify_retried: false,
22480            e2e_deferred: false,
22481            e2e_defer_reason: None,
22482            progressed: false,
22483            vote_split: false,
22484            reconsideration: Vec::new(),
22485            verdict: None,
22486        }];
22487        state.gate = vec![CommandOutcome {
22488            command: "test".to_owned(),
22489            code: Some(0),
22490            output_tail: String::new(),
22491            duration_ms: 0,
22492            resource_blocked: false,
22493            ..Default::default()
22494        }];
22495        state.gate_ran = true;
22496        // A first pass through `merge` already pushed and opened this pull
22497        // request; `status` is `Landing` because a previous call into `land`
22498        // parked or was interrupted before it reached a terminal outcome.
22499        state.status = RunStatus::Landing;
22500        state.merge = Some(MergeOutcome {
22501            mode: MergeMode::Pr,
22502            ok: true,
22503            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22504            empty: false,
22505        });
22506
22507        // The Landing-resume shortcut calls `run_land` directly rather than
22508        // through `merge`, which is exactly the call site that used to skip
22509        // `settle_questions` - see the fixture below.
22510        ask_test_home();
22511        // A real resume loads a persisted run; driver ownership is checked
22512        // against that record before the Landing shortcut is entered.
22513        state.save().expect("save landing run");
22514        let store = ask::Questions::open();
22515        let q = ask_open_question(&store, &state.id);
22516
22517        let mut runner = Runner {
22518            state,
22519            roles: ResolvedRoles {
22520                implementers: Vec::new(),
22521                judges: Vec::new(),
22522                reviewers: Vec::new(),
22523                fixer: None,
22524                conductor: conductor(),
22525                implementer_roster: Vec::new(),
22526                judge_roster: Vec::new(),
22527                reviewer_roster: Vec::new(),
22528            },
22529            sem: Arc::new(Semaphore::new(1)),
22530            pause: Pause::new(),
22531            interrupt: Pause::new(),
22532        };
22533
22534        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22535        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22536        // exactly because `review_loop` would otherwise clobber the marker
22537        // first.
22538        runner.execute().await.expect("execute");
22539
22540        assert_eq!(
22541            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22542            Some("https://example.invalid/x/y/pull/1"),
22543            "reentry must not push again or open a second pull request over the \
22544             one `land` is already watching"
22545        );
22546        assert_ne!(
22547            runner.state.status,
22548            RunStatus::Landing,
22549            "land could not actually reach the fake pull request, so it must \
22550             have given up rather than left the run silently parked forever"
22551        );
22552        // `land` could not reach the fake pull request, so it gave up into
22553        // `Blocked` - still resumable, so the question must not have been
22554        // swept just because this branch now also calls `settle_questions`.
22555        assert_eq!(runner.state.status, RunStatus::Blocked);
22556        assert!(
22557            store.get(&q.id).unwrap().status.open(),
22558            "Blocked is still alive; settle_questions must have been a no-op here"
22559        );
22560    }
22561
22562    fn state_with_round(round: ReviewRound) -> RunState {
22563        let mut s = RunState::new(
22564            PathBuf::from("/repo"),
22565            "main".to_owned(),
22566            "abc1234".to_owned(),
22567            "add retries".to_owned(),
22568            Config::default(),
22569        );
22570        s.reviews = vec![round];
22571        s
22572    }
22573
22574    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22575        crate::verdict::Finding {
22576            id: id.to_owned(),
22577            severity,
22578            file: None,
22579            line: None,
22580            title: title.to_owned(),
22581            detail: String::new(),
22582        }
22583    }
22584
22585    #[test]
22586    fn pr_body_names_open_findings_and_declined_ones() {
22587        let round = ReviewRound {
22588            round: 2,
22589            head: "deadbee".to_owned(),
22590            verified_head: None,
22591            verified_at: None,
22592            reviews: vec![ReviewRecord {
22593                attempts: 0,
22594                reviewer: 1,
22595                agent: "alpha".to_owned(),
22596                summary: String::new(),
22597                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22598                vote: None,
22599                failed: None,
22600                duration_ms: 0,
22601            }],
22602            e2e: vec![CommandOutcome {
22603                command: "cargo test".to_owned(),
22604                code: Some(0),
22605                output_tail: String::new(),
22606                duration_ms: 0,
22607                resource_blocked: false,
22608                ..Default::default()
22609            }],
22610            verify_retried: false,
22611            e2e_deferred: false,
22612            e2e_defer_reason: None,
22613            fix: Some(FixRecord {
22614                agent: "alpha".to_owned(),
22615                addressed: Vec::new(),
22616                rejected: vec![crate::verdict::Rejection {
22617                    id: "R1-1-1".to_owned(),
22618                    why: "not reachable from any caller".to_owned(),
22619                }],
22620                notes: String::new(),
22621                committed: true,
22622                failed: None,
22623                duration_ms: 0,
22624                continuation: None,
22625            }),
22626            blocking: 0,
22627            answered: 1,
22628            expected: 1,
22629            clean: false,
22630            progressed: true,
22631            vote_split: false,
22632            reconsideration: Vec::new(),
22633            verdict: None,
22634        };
22635        let state = state_with_round(round);
22636        let body = pr_message(&state, 'A').body;
22637
22638        assert!(body.contains("add retries"), "the task must still be there");
22639        assert!(body.contains("R2-1-1"), "{body}");
22640        assert!(!body.contains("unused import"), "{body}");
22641        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22642        assert!(
22643            !body.contains("not reachable from any caller"),
22644            "the reason it was declined: {body}"
22645        );
22646    }
22647
22648    #[test]
22649    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22650        let round = ReviewRound {
22651            round: 1,
22652            head: "deadbee".to_owned(),
22653            verified_head: None,
22654            verified_at: None,
22655            reviews: vec![ReviewRecord {
22656                attempts: 0,
22657                reviewer: 1,
22658                agent: "alpha".to_owned(),
22659                summary: String::new(),
22660                findings: Vec::new(),
22661                vote: None,
22662                failed: None,
22663                duration_ms: 0,
22664            }],
22665            e2e: Vec::new(),
22666            verify_retried: false,
22667            e2e_deferred: false,
22668            e2e_defer_reason: None,
22669            fix: None,
22670            blocking: 0,
22671            answered: 1,
22672            expected: 1,
22673            clean: true,
22674            progressed: false,
22675            vote_split: false,
22676            reconsideration: Vec::new(),
22677            verdict: None,
22678        };
22679        let state = state_with_round(round);
22680        let body = pr_message(&state, 'A').body;
22681        assert!(!body.contains("Open review findings"), "{body}");
22682        assert!(!body.contains("Declined"), "{body}");
22683    }
22684
22685    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22686        let mut state = RunState::new(
22687            PathBuf::from("/repo"),
22688            "main".to_owned(),
22689            "abc1234".to_owned(),
22690            instruction.to_owned(),
22691            Config::default(),
22692        );
22693        // These fixtures test execution flow, independent of host disk capacity.
22694        state.config.disk.min_free_bytes = 0;
22695        state.candidates.push(Candidate {
22696            index: 0,
22697            label: 'A',
22698            agent: "alpha".to_owned(),
22699            branch: "magi/x/A".to_owned(),
22700            worktree: PathBuf::from("/wt"),
22701            summary: summary.to_owned(),
22702            stat: String::new(),
22703            files: 1,
22704            commits: 1,
22705            empty: false,
22706            failed: None,
22707            verified_noop: None,
22708            folded: false,
22709            duration_ms: 0,
22710        });
22711        state
22712    }
22713
22714    fn review_state(subjects: &[&str]) -> RunState {
22715        let mut state = state_with_summary(
22716            "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",
22717            "",
22718        );
22719        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
22720        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
22721        state
22722    }
22723
22724    /// A branch rebased onto a main that moved past the recorded
22725    /// `base_commit` is titled from its own first commit, never main's.
22726    #[tokio::test]
22727    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
22728        ask_test_home();
22729        let tmp = tempfile::tempdir().unwrap();
22730        let repo = tmp.path().join("repo");
22731        std::fs::create_dir_all(&repo).unwrap();
22732        init_repo(&repo);
22733        let origin = tmp.path().join("origin.git");
22734        let g = |dir: &Path, args: &[&str]| {
22735            let out = std::process::Command::new("git")
22736                .args(args)
22737                .current_dir(dir)
22738                .quiet()
22739                .output()
22740                .expect("spawn git");
22741            assert!(
22742                out.status.success(),
22743                "git {args:?}: {}",
22744                String::from_utf8_lossy(&out.stderr)
22745            );
22746        };
22747        g(
22748            tmp.path(),
22749            &[
22750                "clone",
22751                "--bare",
22752                "-q",
22753                repo.to_str().unwrap(),
22754                origin.to_str().unwrap(),
22755            ],
22756        );
22757        g(
22758            &repo,
22759            &["remote", "add", "origin", origin.to_str().unwrap()],
22760        );
22761        let c1 = git::rev_parse(&repo, "main").await.unwrap();
22762
22763        // Main moves on; the branch is built on top of the new main.
22764        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
22765        g(&repo, &["add", "-A"]);
22766        g(
22767            &repo,
22768            &["commit", "-q", "-m", "chore(deps): update a crate"],
22769        );
22770        g(&repo, &["push", "-q", "origin", "main"]);
22771        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
22772        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22773        g(&repo, &["add", "-A"]);
22774        g(
22775            &repo,
22776            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
22777        );
22778        g(&repo, &["checkout", "-q", "main"]);
22779
22780        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
22781        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
22782        // Without a readable tracking ref the recorded base's merge base is used.
22783        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
22784        assert_eq!(fallback, c1);
22785
22786        let mut state = review_state(&[
22787            "chore(deps): update a crate",
22788            "fix(daemon): apply a chosen action",
22789        ]);
22790        state.repo = repo.clone();
22791        state.base_branch = "main".to_owned();
22792        state.base_commit = c1;
22793        refresh_reviewed_commits(&mut state, "feat/own").await;
22794        assert_eq!(
22795            state.reviewed_commits,
22796            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
22797        );
22798        assert_eq!(
22799            review_title(&state).as_deref(),
22800            Some("fix(daemon): apply a chosen action")
22801        );
22802        assert_eq!(
22803            leaked_subjects(&state, "feat/own").await,
22804            Some(vec!["chore(deps): update a crate".to_owned()])
22805        );
22806        // A stale tracking ref is still used when the fetch fails, but the
22807        // leak list is withheld.
22808        state.config.merge.remote = "nowhere".to_owned();
22809        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
22810    }
22811
22812    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
22813    /// with `origin/main` one commit behind it, and a summarizing agent that
22814    /// prints whatever `reply` holds.
22815    struct SummaryFixture {
22816        _tmp: tempfile::TempDir,
22817        repo: PathBuf,
22818        reply: PathBuf,
22819        runner: Runner,
22820    }
22821
22822    fn summary_fixture() -> SummaryFixture {
22823        ask_test_home();
22824        let tmp = tempfile::tempdir().unwrap();
22825        let repo = tmp.path().join("repo");
22826        std::fs::create_dir_all(&repo).unwrap();
22827        init_repo(&repo);
22828        let origin = tmp.path().join("origin.git");
22829        let g = |args: &[&str]| {
22830            let out = std::process::Command::new("git")
22831                .args(args)
22832                .current_dir(&repo)
22833                .quiet()
22834                .output()
22835                .expect("spawn git");
22836            assert!(
22837                out.status.success(),
22838                "git {args:?}: {}",
22839                String::from_utf8_lossy(&out.stderr)
22840            );
22841        };
22842        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
22843        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
22844        g(&["push", "-q", "origin", "main"]);
22845        g(&["checkout", "-q", "-b", "feat/own"]);
22846        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22847        g(&["add", "-A"]);
22848        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
22849        let reply = tmp.path().join("reply.txt");
22850        std::fs::write(
22851            &reply,
22852            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
22853        )
22854        .unwrap();
22855        let mut runner = runner_at(RunStatus::Gating);
22856        let mut state = review_state(&["feat(own): add the own file"]);
22857        state.repo = repo.clone();
22858        state.base_branch = "main".to_owned();
22859        state.candidates[0].branch = "feat/own".to_owned();
22860        state.candidates[0].worktree = repo.clone();
22861        let mut author = spec("alpha");
22862        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
22863        author
22864            .env
22865            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
22866        state.config.agents = vec![author];
22867        runner.state = state;
22868        SummaryFixture {
22869            _tmp: tmp,
22870            repo,
22871            reply,
22872            runner,
22873        }
22874    }
22875
22876    async fn posted(f: &mut SummaryFixture) -> PrMessage {
22877        let winner = f.runner.state.candidates[0].clone();
22878        f.runner
22879            .guarded_pr_message(&winner, None, true)
22880            .await
22881            .unwrap()
22882            .expect("an English description never parks")
22883    }
22884
22885    fn clean_round_with_minor_findings() -> ReviewRound {
22886        let mut round = passing_round(2, None);
22887        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
22888        round.reviews = vec![ReviewRecord {
22889            attempts: 0,
22890            reviewer: 1,
22891            agent: "alpha".into(),
22892            summary: "内部レビュー".into(),
22893            findings: vec![
22894                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
22895                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
22896            ],
22897            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
22898            failed: None,
22899            duration_ms: 0,
22900        }];
22901        round
22902    }
22903
22904    #[tokio::test]
22905    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
22906        for review_only in [false, true] {
22907            let mut f = summary_fixture();
22908            if !review_only {
22909                f.runner.state.candidates[0].agent = "alpha".into();
22910            }
22911            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
22912            assert!(f.runner.state.reviews[0].clean);
22913            assert!(f.runner.state.reviews[0].fix.is_none());
22914            assert!(f.runner.state.open_findings().is_empty());
22915            assert_eq!(
22916                crate::pr_outcome::required_finding_ids(&f.runner.state),
22917                ["R2-1-1", "R2-1-2"]
22918            );
22919            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22920            let evidence = crate::pr_outcome::summary_evidence(
22921                &f.runner.state,
22922                crate::pr_outcome::FinalHead::At(&head),
22923            );
22924            assert!(
22925                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
22926            );
22927            // The ordinary reply omits both IDs: no cached description is adopted.
22928            let omitted = posted(&mut f).await;
22929            assert!(omitted.body.contains("No description"));
22930            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
22931            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
22932            assert!(f.runner.state.change_summary.is_none());
22933            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();
22934            let described = posted(&mut f).await;
22935            assert!(described.body.contains("improve documentation for callers"));
22936            assert!(described.body.contains("remaining edge case"));
22937            assert!(described.body.contains("## Open review findings"));
22938            assert!(!described.body.contains("未修正"));
22939        }
22940    }
22941
22942    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
22943        let mut f = summary_fixture();
22944        if !review_only {
22945            f.runner.state.candidates[0].agent = "alpha".into();
22946        }
22947        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22948        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
22949        fixed
22950            .fix
22951            .as_mut()
22952            .unwrap()
22953            .rejected
22954            .push(crate::verdict::Rejection {
22955                id: "R1-1-1".into(),
22956                why: "呼び出されないコードのため辞退".into(),
22957            });
22958        let mut clean = clean_round_with_minor_findings();
22959        clean.verified_head = Some(head.clone());
22960        f.runner.state.reviews = vec![fixed, clean];
22961        ok_gate(&mut f.runner.state, Some(&head));
22962        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
22963        f.runner.state.config.agents.push(scripted("beta", reply));
22964        f.runner.state.config.roles.language_judge =
22965            Some(crate::config::AgentChoice::One("beta".into()));
22966        f
22967    }
22968
22969    #[tokio::test]
22970    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
22971        for review_only in [false, true] {
22972            let mut f = rewrite_fixture_with_findings(review_only,
22973                "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;
22974            let m = posted(&mut f).await;
22975            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22976            let expected =
22977                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
22978            assert!(m.body.contains(&expected));
22979            assert!(m.body.contains("## Review rounds"));
22980            assert!(
22981                m.body
22982                    .contains("Gate (`verify.gate`): passed on the final commit")
22983            );
22984            assert!(
22985                m.body
22986                    .contains("Tests (`verify.e2e`): passed on the final commit")
22987            );
22988            let c = f.runner.state.change_summary.as_ref().unwrap();
22989            assert!(
22990                m.body
22991                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
22992            );
22993            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22994            assert!(crate::pr_outcome::covers_required_findings(
22995                &f.runner.state,
22996                &m.body
22997            ));
22998            assert!(m.body.contains("documentation remains incomplete"));
22999            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23000            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23001            assert!(f.runner.state.github_text.is_none());
23002        }
23003    }
23004
23005    #[tokio::test]
23006    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23007        for review_only in [false, true] {
23008            for reply in [
23009                "TITLE: fix: public description\nA short English description.",
23010                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23011            ] {
23012                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23013                let winner = f.runner.state.candidates[0].clone();
23014                let posted = f
23015                    .runner
23016                    .guarded_pr_message(&winner, None, true)
23017                    .await
23018                    .unwrap();
23019                assert!(posted.is_none());
23020                assert!(f.runner.state.parked);
23021                let withheld = f.runner.state.github_text.as_ref().unwrap();
23022                assert!(
23023                    withheld.rewrite.is_none(),
23024                    "an incomplete rewrite must not be selectable"
23025                );
23026                let q = ask::Questions::open()
23027                    .get(withheld.question.as_ref().unwrap())
23028                    .unwrap();
23029                assert!(
23030                    !q.choices
23031                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23032                );
23033                assert!(
23034                    q.detail.contains("R1-1-1")
23035                        && q.detail.contains("R2-1-1")
23036                        && q.detail.contains("R2-1-2")
23037                );
23038            }
23039        }
23040    }
23041
23042    #[tokio::test]
23043    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23044        for review_only in [false, true] {
23045            let mut f = summary_fixture();
23046            if !review_only {
23047                f.runner.state.candidates[0].agent = "alpha".into();
23048            }
23049            f.runner.state.instruction = "内部タスクの説明".into();
23050            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23051            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23052            f.runner.state.reviews = vec![
23053                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23054                round_with_notes(2, Some("二回目の内部修正報告です。")),
23055                passing_round(3, Some(&head)),
23056            ];
23057            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23058            ok_gate(&mut f.runner.state, Some(&head));
23059            let captured = f.repo.join("public-prompt.txt");
23060            let author = &mut f.runner.state.config.agents[0];
23061            author.command = vec![
23062                "sh".into(),
23063                "-c".into(),
23064                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23065            ];
23066            author.env.insert(
23067                "PROMPT_FILE".into(),
23068                captured.to_string_lossy().into_owned(),
23069            );
23070            let m = posted(&mut f).await;
23071            assert!(m.body.contains("Adds `own.txt`"));
23072            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23073            assert!(m.body.contains("R1-1-1"));
23074            assert!(
23075                m.body
23076                    .contains("Gate (`verify.gate`): passed on the final commit")
23077            );
23078            assert!(
23079                m.body
23080                    .contains("Tests (`verify.e2e`): passed on the final commit")
23081            );
23082            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23083            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23084            let prompt = std::fs::read_to_string(captured).unwrap();
23085            assert!(prompt.contains(&format!(
23086                "git diff {} {head}",
23087                f.runner.state.change_summary.as_ref().unwrap().base
23088            )));
23089            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23090            assert_eq!(
23091                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23092                "二回目の内部修正報告です。"
23093            );
23094        }
23095    }
23096
23097    #[tokio::test]
23098    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23099        for review_only in [false, true] {
23100            let mut f = summary_fixture();
23101            if !review_only {
23102                f.runner.state.candidates[0].agent = "alpha".into();
23103            }
23104            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23105            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23106            std::fs::write(&f.reply, "no usable description").unwrap();
23107            let failed = posted(&mut f).await;
23108            assert!(
23109                failed
23110                    .body
23111                    .contains("No description of what this change does could be generated")
23112            );
23113            assert!(failed.body.is_ascii());
23114            assert!(f.runner.state.github_text.is_none());
23115            assert!(f.runner.state.change_summary.is_none());
23116            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23117            let evidence = crate::pr_outcome::summary_evidence(
23118                &f.runner.state,
23119                crate::pr_outcome::FinalHead::At(&head),
23120            );
23121            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23122            assert!(
23123                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23124                    .exists()
23125            );
23126            f.runner.state =
23127                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23128            std::fs::write(
23129                &f.reply,
23130                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23131            )
23132            .unwrap();
23133            let retried = posted(&mut f).await;
23134            assert!(retried.body.contains("Adds the committed own file."));
23135            assert_eq!(
23136                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23137                "日本語の修正報告"
23138            );
23139        }
23140    }
23141
23142    #[tokio::test]
23143    async fn same_head_verification_and_findings_invalidate_public_prose() {
23144        let mut f = summary_fixture();
23145        posted(&mut f).await;
23146        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23147        let original = f
23148            .runner
23149            .state
23150            .change_summary
23151            .as_ref()
23152            .unwrap()
23153            .evidence
23154            .clone();
23155        ok_gate(&mut f.runner.state, Some(&head));
23156        std::fs::write(
23157            &f.reply,
23158            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23159        )
23160        .unwrap();
23161        let verified = posted(&mut f).await;
23162        assert!(verified.body.contains("now verified"));
23163        assert_ne!(
23164            f.runner.state.change_summary.as_ref().unwrap().evidence,
23165            original
23166        );
23167        let mut round = round_with_notes(1, Some("内部報告"));
23168        round.reviews.push(ReviewRecord {
23169            attempts: 0,
23170            reviewer: 1,
23171            agent: "alpha".into(),
23172            summary: "内部レビュー".into(),
23173            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23174            vote: None,
23175            failed: None,
23176            duration_ms: 0,
23177        });
23178        round
23179            .fix
23180            .as_mut()
23181            .unwrap()
23182            .rejected
23183            .push(crate::verdict::Rejection {
23184                id: "R1-1-1".into(),
23185                why: "呼び出し元から到達できない".into(),
23186            });
23187        f.runner.state.reviews = vec![round];
23188        // A description omitting the required ID is unusable, even with a title.
23189        let omitted = posted(&mut f).await;
23190        assert!(omitted.body.contains("No description"));
23191        assert!(omitted.body.contains("R1-1-1"));
23192        assert!(!omitted.body.contains("到達"));
23193        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();
23194        let described = posted(&mut f).await;
23195        assert!(described.body.contains("unreachable from callers"));
23196        assert!(described.body.contains("R1-1-1"));
23197        assert!(!described.body.contains("到達"));
23198        let evidence = f
23199            .runner
23200            .state
23201            .change_summary
23202            .as_ref()
23203            .unwrap()
23204            .evidence
23205            .clone();
23206        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23207        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23208        assert!(posted(&mut f).await.body.contains("rationale updated"));
23209        assert_ne!(
23210            f.runner.state.change_summary.as_ref().unwrap().evidence,
23211            evidence
23212        );
23213        // Old serialized summaries have no evidence fingerprint and must regenerate.
23214        f.runner
23215            .state
23216            .change_summary
23217            .as_mut()
23218            .unwrap()
23219            .evidence
23220            .clear();
23221        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23222        assert!(posted(&mut f).await.body.contains("current specification"));
23223    }
23224
23225    #[tokio::test]
23226    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23227        let mut f = summary_fixture();
23228        let m = posted(&mut f).await;
23229        assert_eq!(m.title, "feat(own): add the own file");
23230        assert!(
23231            m.body
23232                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23233            "{}",
23234            m.body
23235        );
23236        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23237        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23238        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23239        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23240        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23241        let kept = f.runner.state.change_summary.as_ref().unwrap();
23242        assert_eq!(
23243            (kept.head.as_str(), kept.base.as_str()),
23244            (head.as_str(), base.as_str())
23245        );
23246        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23247    }
23248
23249    #[tokio::test]
23250    async fn review_only_summary_receives_the_configured_github_language() {
23251        let mut f = summary_fixture();
23252        f.runner.state.config.graph.github_language = "ja".into();
23253        let captured = f.repo.join("summary-prompt.txt");
23254        let author = &mut f.runner.state.config.agents[0];
23255        author.command = vec![
23256            "sh".into(),
23257            "-c".into(),
23258            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23259        ];
23260        author.env.insert(
23261            "PROMPT_FILE".into(),
23262            captured.to_string_lossy().into_owned(),
23263        );
23264        std::fs::write(
23265            &f.reply,
23266            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23267        )
23268        .unwrap();
23269        let m = posted(&mut f).await;
23270        let prompt = std::fs::read_to_string(captured).unwrap();
23271        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23272        assert!(!prompt.contains("in English"));
23273        assert_eq!(m.title, "feat(own): ファイルを追加");
23274        assert!(m.body.contains("own.txt を追加します。"));
23275    }
23276
23277    #[tokio::test]
23278    async fn review_fixes_come_after_the_whole_change_summary() {
23279        let mut f = summary_fixture();
23280        f.runner.state.reviews = vec![
23281            round_with_notes(1, Some("handled the PATH case")),
23282            round_with_notes(2, None),
23283        ];
23284        let m = posted(&mut f).await;
23285        let summary = m.body.find("## Summary").expect("summary");
23286        let fixes = m.body.find("## Review rounds").expect("review rounds");
23287        assert!(summary < fixes, "{}", m.body);
23288        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23289        assert!(m.body.contains("## Final verification"), "{}", m.body);
23290    }
23291
23292    #[tokio::test]
23293    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23294        let mut f = summary_fixture();
23295        let first = posted(&mut f).await;
23296        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23297        // The same head reuses the record: a different reply is not read.
23298        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23299        let again = posted(&mut f).await;
23300        assert_eq!((again.title, again.body), (first.title, first.body));
23301
23302        let g = |args: &[&str]| {
23303            let out = std::process::Command::new("git")
23304                .args(args)
23305                .current_dir(&f.repo)
23306                .quiet()
23307                .output()
23308                .expect("spawn git");
23309            assert!(out.status.success(), "git {args:?}");
23310        };
23311        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23312        g(&["add", "-A"]);
23313        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23314        let second = posted(&mut f).await;
23315        let kept = f.runner.state.change_summary.clone().unwrap();
23316        assert_ne!(kept.head, first_head);
23317        assert!(second.body.contains("Not read yet."), "{}", second.body);
23318        assert!(!second.body.contains("so the first summary is read"));
23319        assert_eq!(second.title, "feat(own): other");
23320    }
23321
23322    #[tokio::test]
23323    async fn an_unavailable_summary_is_stated_and_never_invented() {
23324        let mut f = summary_fixture();
23325        std::fs::write(&f.reply, "no title line here").unwrap();
23326        let m = posted(&mut f).await;
23327        assert!(
23328            m.body
23329                .contains("No description of what this change does could be generated"),
23330            "{}",
23331            m.body
23332        );
23333        assert!(m.body.contains("internal reports remain in local records"));
23334        assert!(f.runner.state.change_summary.is_none());
23335        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23336        // A preview asks nobody and claims nothing.
23337        let winner = f.runner.state.candidates[0].clone();
23338        let preview = f
23339            .runner
23340            .guarded_pr_message(&winner, None, false)
23341            .await
23342            .unwrap()
23343            .unwrap();
23344        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23345    }
23346
23347    #[test]
23348    fn pr_message_review_single_commit_uses_its_subject() {
23349        let state = review_state(&["feat(nats): per-role user"]);
23350        let m = pr_message(&state, 'A');
23351        assert_eq!(m.title, "feat(nats): per-role user");
23352        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23353        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23354    }
23355
23356    #[test]
23357    fn pr_message_review_multi_commit_takes_the_oldest() {
23358        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23359        let m = pr_message(&state, 'A');
23360        assert_eq!(m.title, "feat: the change");
23361        for s in ["feat: the change", "fix: typo", "fix: again"] {
23362            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23363        }
23364    }
23365
23366    #[test]
23367    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23368        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23369            let mut state = review_state(&[first, "fix: later fixup"]);
23370            state.candidates[0].branch = "機能/ログイン".to_owned();
23371            let m = pr_message(&state, 'A');
23372            assert!(
23373                m.title.starts_with("chore: land candidate A of run"),
23374                "{}",
23375                m.title
23376            );
23377        }
23378    }
23379
23380    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23381        BranchFacts {
23382            commits: commits
23383                .iter()
23384                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23385                .collect(),
23386            stat: stat.to_owned(),
23387        }
23388    }
23389
23390    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23391        let mut r = review_round(true, 0, 1, 1, true, true);
23392        r.round = round;
23393        r.fix = notes.map(|n| FixRecord {
23394            agent: "fixer".to_owned(),
23395            addressed: Vec::new(),
23396            rejected: Vec::new(),
23397            notes: n.to_owned(),
23398            committed: true,
23399            failed: None,
23400            duration_ms: 0,
23401            continuation: None,
23402        });
23403        r
23404    }
23405
23406    #[test]
23407    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23408        let state = review_state(&["ignored"]);
23409        let f = facts(
23410            &[
23411                (
23412                    "fix(login): resolve PATH on macOS",
23413                    "Login shells skip rc files.",
23414                ),
23415                ("fix: address review", ""),
23416            ],
23417            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23418        );
23419        let m = pr_message_with(&state, 'A', Some(&f));
23420        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23421        assert!(
23422            m.body
23423                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23424            "{}",
23425            m.body
23426        );
23427        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23428        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23429        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23430        for banned in [
23431            "Review the work already",
23432            "no task statement",
23433            "Original task",
23434        ] {
23435            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23436        }
23437        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23438    }
23439
23440    #[test]
23441    fn pr_message_review_truncates_a_huge_first_commit_body() {
23442        let state = review_state(&["ignored"]);
23443        let f = facts(
23444            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23445            "s",
23446        );
23447        let m = pr_message_with(&state, 'A', Some(&f));
23448        assert!(m.body.len() < 30_000, "{}", m.body.len());
23449        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23450        assert!(
23451            m.body.contains("- ... 1 more commit(s)"),
23452            "{}",
23453            m.body.len()
23454        );
23455        assert!(m.body.ends_with("magi:candidate-a\n"));
23456    }
23457
23458    #[test]
23459    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23460        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23461        assert_eq!(m.title, "feat: x");
23462        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23463        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23464        assert!(!m.body.contains("no task statement"), "{}", m.body);
23465    }
23466
23467    #[test]
23468    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23469        let mut state = review_state(&["日本語の件名"]);
23470        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23471        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23472        state.candidates[0].branch = "機能/ログイン".to_owned();
23473        assert!(
23474            pr_message(&state, 'A')
23475                .title
23476                .starts_with("chore: land candidate A")
23477        );
23478    }
23479
23480    #[test]
23481    fn pr_message_review_fixes_survive_a_clean_final_round() {
23482        let mut state = review_state(&["feat: x"]);
23483        state.reviews = vec![
23484            round_with_notes(1, Some("handled the PATH case")),
23485            round_with_notes(2, None),
23486        ];
23487        let body = pr_message(&state, 'A').body;
23488        assert!(
23489            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23490            "{body}"
23491        );
23492        assert!(body.contains("### Round 1"), "{body}");
23493
23494        state.reviews = vec![
23495            round_with_notes(1, Some("first fix")),
23496            round_with_notes(2, Some("")),
23497            round_with_notes(3, Some("second fix")),
23498            round_with_notes(4, None),
23499        ];
23500        let body = pr_message(&state, 'A').body;
23501        assert!(
23502            body.contains("### Round 1") && !body.contains("first fix"),
23503            "{body}"
23504        );
23505        assert!(
23506            body.contains("### Round 3") && !body.contains("second fix"),
23507            "{body}"
23508        );
23509        assert!(body.contains("### Round 2"), "{body}");
23510    }
23511
23512    const FINAL: &str = "abcdef1234567890";
23513
23514    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23515        let mut r = round_with_notes(round, None);
23516        r.verified_head = verified.map(str::to_owned);
23517        r
23518    }
23519
23520    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23521        state.gate = vec![CommandOutcome {
23522            command: "gate".to_owned(),
23523            code: Some(0),
23524            output_tail: String::new(),
23525            duration_ms: 0,
23526            resource_blocked: false,
23527            ..Default::default()
23528        }];
23529        state.gate_ran = true;
23530        state.gate_head = head.map(str::to_owned);
23531    }
23532
23533    fn body_at(state: &RunState) -> String {
23534        pr_message_raw(
23535            state,
23536            'A',
23537            None,
23538            crate::pr_outcome::FinalHead::At(FINAL),
23539            ChangeNote::NotAsked,
23540        )
23541        .body
23542    }
23543
23544    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23545
23546    #[test]
23547    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23548        let mut state = review_state(&["feat: x"]);
23549        state.reviews = vec![
23550            round_with_notes(1, Some(SANDBOXED)),
23551            passing_round(2, Some(FINAL)),
23552        ];
23553        ok_gate(&mut state, Some(FINAL));
23554        let body = body_at(&state);
23555        assert!(!body.contains("Handled the PATH case."), "{body}");
23556        assert!(!body.contains("could not commit"), "{body}");
23557        assert!(!body.contains("could not run"), "{body}");
23558        assert!(
23559            body.contains("The fix is committed on the branch"),
23560            "{body}"
23561        );
23562        assert!(!body.contains("sandbox"), "{body}");
23563        assert!(
23564            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23565            "{body}"
23566        );
23567        assert!(
23568            body.contains("Gate (`verify.gate`): passed on the final commit"),
23569            "{body}"
23570        );
23571        // The raw report is untouched in the record.
23572        assert!(
23573            state.reviews[0]
23574                .fix
23575                .as_ref()
23576                .unwrap()
23577                .notes
23578                .contains("could not commit")
23579        );
23580    }
23581
23582    #[test]
23583    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23584        let mut state = review_state(&["feat: x"]);
23585        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23586        r1.fix.as_mut().unwrap().committed = false;
23587        let mut r2 = passing_round(2, Some(FINAL));
23588        r2.e2e[0].code = Some(1);
23589        state.reviews = vec![r1, r2];
23590        let body = body_at(&state);
23591        assert!(!body.contains("could not commit"), "{body}");
23592        assert!(!body.contains("could not run"), "{body}");
23593        assert!(body.contains("This round produced no commit"), "{body}");
23594        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23595        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23596        assert!(!body.contains("passed"), "{body}");
23597    }
23598
23599    #[test]
23600    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23601        let mut state = review_state(&["feat: x"]);
23602        state.reviews = vec![
23603            round_with_notes(1, Some(SANDBOXED)),
23604            passing_round(2, Some("0123456789abcdef")),
23605        ];
23606        ok_gate(&mut state, Some("0123456789abcdef"));
23607        let body = body_at(&state);
23608        assert!(!body.contains("HTTP tests could not run"), "{body}");
23609        // The commit claim is still settled by the structured record.
23610        assert!(!body.contains("could not commit"), "{body}");
23611        assert!(
23612            body.contains("passed on an earlier commit (`0123456`)"),
23613            "{body}"
23614        );
23615        assert!(!body.contains("passed on the final commit"), "{body}");
23616
23617        // A gate recorded before `gate_head` existed is "not recorded".
23618        ok_gate(&mut state, None);
23619        let body = body_at(&state);
23620        assert!(
23621            body.contains("passed on a commit that was not recorded"),
23622            "{body}"
23623        );
23624    }
23625
23626    #[test]
23627    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23628        let state = state_with_summary(
23629            "add retries to the client",
23630            "TITLE: feat: retries\n\nDid it.",
23631        );
23632        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23633        assert_eq!(m.title, "feat: retries");
23634        assert!(
23635            m.body.contains("<summary>Original task</summary>"),
23636            "{}",
23637            m.body
23638        );
23639        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23640        assert!(
23641            m.body
23642                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23643            "{}",
23644            m.body
23645        );
23646    }
23647
23648    #[test]
23649    fn pr_message_review_bounds_a_long_english_subject() {
23650        let long = format!("feat: {}", "word ".repeat(100));
23651        let m = pr_message(&review_state(&[&long]), 'A');
23652        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23653        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23654    }
23655
23656    #[test]
23657    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23658        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23659        let m = pr_message(&state, 'A');
23660        assert_eq!(m.title, "add retries");
23661        assert!(m.body.contains("<summary>Original task</summary>"));
23662        assert!(!m.body.contains("Commits under review"));
23663        assert_eq!(landing_subject_source(&state), state.instruction);
23664    }
23665
23666    #[test]
23667    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23668        let state = review_state(&["feat: the change", "fix: typo"]);
23669        let source = landing_subject_source(&state);
23670        assert_eq!(land::merge_subject("", &source), "feat: the change");
23671        assert_eq!(
23672            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23673            "feat: the change"
23674        );
23675        // An operator's rename still wins.
23676        assert_eq!(
23677            land::merge_subject("feat: renamed by hand", &source),
23678            "feat: renamed by hand"
23679        );
23680        let blank = review_state(&["日本語"]);
23681        assert!(
23682            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23683        );
23684    }
23685
23686    #[test]
23687    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23688        let state = review_state(&["feat: the change"]);
23689        let source = landing_subject_source(&state);
23690        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23691        assert_eq!(
23692            land::merge_subject(landing_title(&state, old), &source),
23693            "feat: the change"
23694        );
23695        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23696        let task = state_with_summary("add retries", "");
23697        assert_eq!(landing_title(&task, old), old);
23698    }
23699
23700    #[test]
23701    fn pr_message_describes_the_change_not_the_task() {
23702        let state = state_with_summary(
23703            "今回やってほしいこと: results projector を直す",
23704            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23705        );
23706        let m = pr_message(&state, 'A');
23707        assert_eq!(m.title, "fix(web): batch the runs list reads");
23708        assert!(
23709            m.body.starts_with("## Summary\n\n- reads run.json once"),
23710            "{}",
23711            m.body
23712        );
23713        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23714        let task_at = m.body.find("今回やってほしいこと").unwrap();
23715        let details_at = m.body.find("<details>").unwrap();
23716        assert!(
23717            details_at < task_at,
23718            "the task lives inside <details>: {}",
23719            m.body
23720        );
23721        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
23722        assert!(m.body.contains("magi:candidate-a"));
23723    }
23724
23725    #[test]
23726    fn pr_message_falls_back_to_the_task_without_a_title_line() {
23727        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
23728        let m = pr_message(&state, 'A');
23729        assert_eq!(m.title, "add retries");
23730        assert!(
23731            m.body.contains("## Summary\n\n- did some things"),
23732            "{}",
23733            m.body
23734        );
23735
23736        let none = RunState::new(
23737            PathBuf::from("/repo"),
23738            "main".to_owned(),
23739            "abc1234".to_owned(),
23740            "add retries".to_owned(),
23741            Config::default(),
23742        );
23743        let m = pr_message(&none, 'A');
23744        assert_eq!(m.title, "add retries");
23745        assert!(!m.body.contains("## Summary"), "{}", m.body);
23746    }
23747
23748    #[test]
23749    fn pr_message_refuses_the_candidate_commit_subject() {
23750        for bad in [
23751            "TITLE: magi: candidate A (uncommitted work)",
23752            "TITLE: chore: stuff (uncommitted work)",
23753            "TITLE:   ",
23754        ] {
23755            let state = state_with_summary("add retries", bad);
23756            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
23757        }
23758    }
23759
23760    #[test]
23761    fn pr_message_bounds_a_very_long_task_and_title() {
23762        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
23763        let state = state_with_summary(&long, "- nothing");
23764        let m = pr_message(&state, 'A');
23765        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23766        assert!(!m.title.contains('\n'));
23767
23768        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
23769        let m = pr_message(&state, 'A');
23770        assert!(m.title.starts_with("feat: "));
23771        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23772        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
23773    }
23774
23775    fn long_title_of(instruction: &str) -> String {
23776        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
23777    }
23778
23779    #[test]
23780    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
23781        let first = "Make the landing path keep a readable title for long tasks";
23782        let line = format!(
23783            "{first}. {}",
23784            "And then keep going with more words ".repeat(20)
23785        );
23786        let t = long_title_of(&line);
23787        assert_eq!(t, first);
23788        assert!(!t.starts_with("chore: land"));
23789    }
23790
23791    #[test]
23792    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
23793        let line = "word ".repeat(200);
23794        let t = long_title_of(&line);
23795        assert!(t.ends_with("word..."), "{t}");
23796        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
23797    }
23798
23799    #[test]
23800    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
23801        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
23802            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
23803        }
23804    }
23805
23806    #[test]
23807    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
23808        let mut state = state_with_summary("再試行を追加する", "- nothing");
23809        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
23810        state.config.graph.github_language = "ja".into();
23811        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
23812    }
23813
23814    #[test]
23815    fn pr_message_title_limit_is_exact() {
23816        let at = "a".repeat(PR_TITLE_MAX);
23817        assert_eq!(long_title_of(&at), at);
23818        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
23819        assert!(over.ends_with("..."), "{over}");
23820        assert_eq!(over.chars().count(), PR_TITLE_MAX);
23821    }
23822
23823    #[test]
23824    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
23825        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
23826        let t = long_title_of(&line);
23827        assert!(t.ends_with("..."), "{t}");
23828        assert!(t.is_ascii(), "{t}");
23829    }
23830
23831    #[test]
23832    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
23833        let line = format!(
23834            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
23835            "plus more filler words ".repeat(20)
23836        );
23837        let t = long_title_of(&line);
23838        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
23839    }
23840
23841    #[test]
23842    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
23843        let line = format!("\n\n# {}", "title words ".repeat(40));
23844        let state = state_with_summary(&line, "- nothing");
23845        let m = pr_message(&state, 'A');
23846        assert!(m.title.starts_with("title words"), "{}", m.title);
23847        assert_eq!(
23848            land::merge_subject(&m.title, &landing_subject_source(&state)),
23849            m.title
23850        );
23851        // An operator's rename wins untouched.
23852        assert_eq!(
23853            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
23854            "feat: renamed by hand"
23855        );
23856    }
23857
23858    #[tokio::test]
23859    async fn github_text_rewrite_is_bounded_and_falls_back() {
23860        crate::run::pin_test_home();
23861        for (reply, accepted) in [
23862            (
23863                "TITLE: fix: retries\nAdd retries for failed requests.",
23864                true,
23865            ),
23866            (
23867                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
23868                false,
23869            ),
23870            (
23871                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
23872                true,
23873            ),
23874            (
23875                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
23876                true,
23877            ),
23878            (
23879                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
23880                true,
23881            ),
23882            (
23883                "TITLE: fix: retries\n日本語の説明です。 token=secret",
23884                false,
23885            ),
23886            ("TITLE: fix: retries\n", false),
23887        ] {
23888            let dir = tempfile::tempdir().unwrap();
23889            let mut runner = runner_at(RunStatus::Gating);
23890            runner.state = state_with_summary(
23891                "add retries",
23892                "TITLE: fix: retries\n日本語の説明を書きます。",
23893            );
23894            runner.state.repo = dir.path().to_owned();
23895            runner.state.candidates[0].worktree = dir.path().to_owned();
23896            let mut author = spec("alpha");
23897            author.command = vec![
23898                "sh".into(),
23899                "-c".into(),
23900                "printf '%s' \"$REWRITE_REPLY\"".into(),
23901            ];
23902            author.env.insert("REWRITE_REPLY".into(), reply.into());
23903            runner.state.config.agents = vec![author];
23904            seed_public_summary(&mut runner);
23905            let winner = runner.state.candidates[0].clone();
23906            let first = runner
23907                .guarded_pr_message(&winner, None, true)
23908                .await
23909                .unwrap();
23910            let message = if accepted {
23911                first.expect("a passing rewrite never asks")
23912            } else {
23913                // Withheld: the run parks on a question and posts nothing yet.
23914                assert!(first.is_none());
23915                assert!(runner.state.parked);
23916                let store = ask::Questions::open();
23917                let asked: Vec<_> = store
23918                    .list()
23919                    .into_iter()
23920                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23921                    .collect();
23922                assert_eq!(asked.len(), 1);
23923                assert!(!asked[0].detail.contains("secret"));
23924                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
23925                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
23926                assert_eq!(
23927                    asked[0]
23928                        .choices
23929                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
23930                    rewrite.is_some()
23931                );
23932                // Silence: the question lapses and the neutral text is used,
23933                // without a second rewrite call or a second question.
23934                store
23935                    .update(&asked[0].id, |q| {
23936                        q.abandon("test");
23937                        Ok(())
23938                    })
23939                    .unwrap();
23940                let again = runner
23941                    .guarded_pr_message(&winner, None, true)
23942                    .await
23943                    .unwrap()
23944                    .expect("an abandoned question falls back");
23945                let n = store
23946                    .list()
23947                    .into_iter()
23948                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23949                    .count();
23950                assert_eq!(n, 1, "asked once per rejected text");
23951                again
23952            };
23953            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
23954            assert!(!message.body.contains("secret"));
23955            assert!(!message.body.contains("prefix"));
23956            assert!(!message.title.contains("secret"));
23957            assert_eq!(
23958                message.body.contains("Add retries for failed requests."),
23959                accepted
23960            );
23961            assert_eq!(
23962                runner.state.seats["github-text-rewrite"].turns, 1,
23963                "only one rewrite invocation"
23964            );
23965            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
23966            if accepted {
23967                assert!(runner.state.github_text.is_none());
23968                assert!(!runner.state.parked);
23969                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
23970                assert!(message.body.contains("## Final verification"));
23971                assert!(message.body.contains("Evidence: final diff"));
23972                assert!(
23973                    message
23974                        .body
23975                        .contains(&format!("magi:run/{}", runner.state.id))
23976                );
23977            }
23978            if !accepted {
23979                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
23980                assert!(
23981                    message
23982                        .body
23983                        .contains(&format!("magi:run/{}", runner.state.id))
23984                );
23985            }
23986        }
23987    }
23988
23989    fn scripted(id: &str, reply: &str) -> AgentSpec {
23990        let mut a = spec(id);
23991        a.command = vec![
23992            "sh".into(),
23993            "-c".into(),
23994            "printf '%s' \"$REWRITE_REPLY\"".into(),
23995        ];
23996        a.env.insert("REWRITE_REPLY".into(), reply.into());
23997        a
23998    }
23999
24000    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24001    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24002
24003    /// Gate tests inject generated public output, not internal reports.
24004    fn seed_public_summary(runner: &mut Runner) {
24005        let repo = &runner.state.repo;
24006        let g = |args: &[&str]| {
24007            let out = std::process::Command::new("git")
24008                .args(args)
24009                .current_dir(repo)
24010                .quiet()
24011                .output()
24012                .unwrap();
24013            assert!(out.status.success(), "git {args:?}");
24014            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24015        };
24016        g(&["init", "-q", "-b", "main"]);
24017        g(&[
24018            "-c",
24019            "user.name=Test",
24020            "-c",
24021            "user.email=test@example.invalid",
24022            "commit",
24023            "-q",
24024            "--allow-empty",
24025            "-m",
24026            "feat: fixture",
24027        ]);
24028        let head = g(&["rev-parse", "HEAD"]);
24029        g(&["update-ref", "refs/remotes/origin/main", &head]);
24030        let evidence = crate::pr_outcome::summary_evidence(
24031            &runner.state,
24032            crate::pr_outcome::FinalHead::At(&head),
24033        );
24034        let generated = &runner.state.candidates[0].summary;
24035        runner.state.change_summary = Some(crate::run::ChangeSummary {
24036            base: head.clone(),
24037            head,
24038            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24039            title: summary_title(generated).unwrap(),
24040            body: summary_without_title(generated),
24041        });
24042    }
24043
24044    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24045        let mut runner = runner_at(RunStatus::Gating);
24046        runner.state = state_with_summary("add retries", JA_SUMMARY);
24047        if review_only {
24048            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24049        }
24050        runner.state.repo = dir.to_owned();
24051        runner.state.candidates[0].worktree = dir.to_owned();
24052        runner.state.config.agents = agents;
24053        seed_public_summary(&mut runner);
24054        runner
24055    }
24056
24057    fn gate_questions(runner: &Runner) -> usize {
24058        ask::Questions::open()
24059            .list()
24060            .into_iter()
24061            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24062            .count()
24063    }
24064
24065    #[tokio::test]
24066    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24067        crate::run::pin_test_home();
24068        let dir = tempfile::tempdir().unwrap();
24069        let mut runner = rewrite_runner(
24070            dir.path(),
24071            true,
24072            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24073        );
24074        runner.state.config.roles.language_judge =
24075            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24076        let winner = runner.state.candidates[0].clone();
24077        let msg = runner
24078            .guarded_pr_message(&winner, None, true)
24079            .await
24080            .unwrap()
24081            .expect("an English rewrite posts without asking");
24082        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24083        assert!(msg.body.contains("<details>kept</details>"));
24084        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24085        assert_eq!(gate_questions(&runner), 0);
24086        assert!(runner.state.github_text.is_none());
24087        assert!(!runner.state.seats.contains_key("impl-A"));
24088        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24089    }
24090
24091    #[tokio::test]
24092    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24093        crate::run::pin_test_home();
24094        let dir = tempfile::tempdir().unwrap();
24095        let mut runner = rewrite_runner(
24096            dir.path(),
24097            false,
24098            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24099        );
24100        runner.state.config.roles.language_judge =
24101            Some(crate::config::AgentChoice::One("beta".into()));
24102        runner.state.seats.insert(
24103            "impl-A".into(),
24104            SeatState::new("impl-A", "alpha", runner.state.seed),
24105        );
24106        let winner = runner.state.candidates[0].clone();
24107        let msg = runner
24108            .guarded_pr_message(&winner, None, true)
24109            .await
24110            .unwrap()
24111            .expect("rewritten");
24112        assert!(msg.body.contains("<details>kept</details>"));
24113        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24114        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24115        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24116    }
24117
24118    #[tokio::test]
24119    async fn rewrite_reuses_a_resumable_implementer_session() {
24120        crate::run::pin_test_home();
24121        let dir = tempfile::tempdir().unwrap();
24122        let mut runner = rewrite_runner(
24123            dir.path(),
24124            false,
24125            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24126        );
24127        runner.state.config.roles.language_judge =
24128            Some(crate::config::AgentChoice::One("beta".into()));
24129        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24130        seat.turns = 1;
24131        runner.state.seats.insert("impl-A".into(), seat);
24132        let winner = runner.state.candidates[0].clone();
24133        runner
24134            .guarded_pr_message(&winner, None, true)
24135            .await
24136            .unwrap()
24137            .expect("rewritten");
24138        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24139        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24140    }
24141
24142    #[tokio::test]
24143    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24144        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24145        // session, was out of quota, and nothing else was asked.
24146        crate::run::pin_test_home();
24147        let dir = tempfile::tempdir().unwrap();
24148        let mut exhausted = spec("alpha");
24149        exhausted.command = vec!["false".into()];
24150        let mut runner = rewrite_runner(
24151            dir.path(),
24152            false,
24153            vec![exhausted, scripted("beta", EN_REWRITE)],
24154        );
24155        // The implementer's own agent is in the role too: it is not asked twice.
24156        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24157            "alpha".into(),
24158            "beta".into(),
24159        ]));
24160        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24161        seat.turns = 1;
24162        runner.state.seats.insert("impl-A".into(), seat);
24163        let winner = runner.state.candidates[0].clone();
24164        let msg = runner
24165            .guarded_pr_message(&winner, None, true)
24166            .await
24167            .unwrap()
24168            .expect("the role rewrites after the implementer fails");
24169        assert!(msg.body.contains("`src/net.rs`"));
24170        assert_eq!(
24171            runner.state.seats["impl-A"].turns, 2,
24172            "the implementer was tried once"
24173        );
24174        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24175        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24176    }
24177
24178    #[tokio::test]
24179    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24180        crate::run::pin_test_home();
24181        let dir = tempfile::tempdir().unwrap();
24182        let mut broken = spec("bad");
24183        broken.command = vec!["false".into()];
24184        let mut runner = rewrite_runner(
24185            dir.path(),
24186            true,
24187            vec![
24188                broken,
24189                scripted("noformat", "Add retries."),
24190                scripted("good", EN_REWRITE),
24191            ],
24192        );
24193        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24194            "bad".into(),
24195            "noformat".into(),
24196            "good".into(),
24197        ]));
24198        let winner = runner.state.candidates[0].clone();
24199        let msg = runner
24200            .guarded_pr_message(&winner, None, true)
24201            .await
24202            .unwrap()
24203            .expect("the third agent rewrites");
24204        assert!(msg.body.contains("`src/net.rs`"));
24205        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24206        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24207    }
24208
24209    #[tokio::test]
24210    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24211        crate::run::pin_test_home();
24212        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24213        for (agents, role, saved) in [
24214            (
24215                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24216                Some("beta"),
24217                true,
24218            ),
24219            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24220            (Vec::new(), None, false),
24221        ] {
24222            let dir = tempfile::tempdir().unwrap();
24223            let mut runner = rewrite_runner(dir.path(), true, agents);
24224            runner.state.config.roles.language_judge =
24225                role.map(|r| crate::config::AgentChoice::One(r.into()));
24226            let winner = runner.state.candidates[0].clone();
24227            let first = runner
24228                .guarded_pr_message(&winner, None, true)
24229                .await
24230                .unwrap();
24231            assert!(first.is_none(), "withheld text parks the run");
24232            assert!(runner.state.parked);
24233            assert_eq!(gate_questions(&runner), 1);
24234            let g = runner.state.github_text.as_ref().unwrap();
24235            assert_eq!(g.rewrite.is_some(), saved);
24236            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24237        }
24238    }
24239
24240    #[tokio::test]
24241    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24242        crate::run::pin_test_home();
24243        let dir = tempfile::tempdir().unwrap();
24244        let mut runner = runner_at(RunStatus::Gating);
24245        runner.state =
24246            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24247        runner.state.repo = dir.path().to_owned();
24248        runner.state.candidates[0].worktree = dir.path().to_owned();
24249        let mut author = spec("alpha");
24250        author.command = vec![
24251            "sh".into(),
24252            "-c".into(),
24253            "printf '%s' \"$REWRITE_REPLY\"".into(),
24254        ];
24255        author.env.insert(
24256            "REWRITE_REPLY".into(),
24257            format!(
24258                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24259                "English sentence. ".repeat(600)
24260            ),
24261        );
24262        runner.state.config.agents = vec![author];
24263        seed_public_summary(&mut runner);
24264        let winner = runner.state.candidates[0].clone();
24265        assert!(
24266            runner
24267                .guarded_pr_message(&winner, None, true)
24268                .await
24269                .unwrap()
24270                .is_none()
24271        );
24272        let record = runner.state.github_text.clone().unwrap();
24273        let rewrite = record.rewrite.clone().unwrap();
24274        assert_eq!(rewrite.failed, ["body-language"]);
24275        assert!(
24276            rewrite
24277                .body
24278                .ends_with(&format!("magi:run/{}", runner.state.id))
24279        );
24280        let store = ask::Questions::open();
24281        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24282        assert!(
24283            q.choices
24284                .contains(&crate::github_text::USE_REWRITE.to_owned())
24285        );
24286        for label in [
24287            "ORIGINAL",
24288            "FALLBACK",
24289            "REWRITE",
24290            "Rules still failed: body-language",
24291            "truncated",
24292        ] {
24293            assert!(q.detail.contains(label), "{label}");
24294        }
24295        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24296            &runner.state,
24297            &crate::github_text::artifact_name(&record.fingerprint),
24298        ))
24299        .unwrap();
24300        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24301        // Restart from serialized state, then retry after a bad owner title.
24302        runner.state =
24303            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24304        store
24305            .update(&q.id, |q| {
24306                q.say("まだ日本語")?;
24307                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24308            })
24309            .unwrap();
24310        assert!(
24311            runner
24312                .guarded_pr_message(&winner, None, true)
24313                .await
24314                .unwrap()
24315                .is_none()
24316        );
24317        let retry = runner.state.github_text.as_ref().unwrap();
24318        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24319        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24320        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24321        assert!(
24322            q.posting_comparison
24323                .as_ref()
24324                .unwrap()
24325                .matches_detail(&q.detail)
24326        );
24327        store
24328            .update(&q.id, |q| {
24329                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24330            })
24331            .unwrap();
24332        let message = runner
24333            .guarded_pr_message(&winner, None, true)
24334            .await
24335            .unwrap()
24336            .unwrap();
24337        assert_eq!(message.title, rewrite.title);
24338        assert_eq!(message.body, rewrite.body);
24339        assert_eq!(
24340            runner.state.github_text.as_ref().unwrap().choice,
24341            Some(GithubTextChoice::Rewrite)
24342        );
24343        let again = runner
24344            .guarded_pr_message(&winner, None, true)
24345            .await
24346            .unwrap()
24347            .unwrap();
24348        assert_eq!(again.title, message.title);
24349        assert_eq!(again.body, message.body);
24350        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24351        assert!(
24352            !runner
24353                .state
24354                .events
24355                .iter()
24356                .any(|e| e.message.contains(&rewrite.title)
24357                    || e.message.contains("English sentence."))
24358        );
24359    }
24360
24361    #[tokio::test]
24362    async fn historical_posting_reply_never_expires_into_fallback() {
24363        crate::run::pin_test_home();
24364        let dir = tempfile::tempdir().unwrap();
24365        let mut runner = runner_at(RunStatus::Gating);
24366        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24367        runner.state.repo = dir.path().to_owned();
24368        runner.state.candidates[0].worktree = dir.path().to_owned();
24369        seed_public_summary(&mut runner);
24370        let winner = runner.state.candidates[0].clone();
24371        assert!(
24372            runner
24373                .guarded_pr_message(&winner, None, true)
24374                .await
24375                .unwrap()
24376                .is_none()
24377        );
24378        let id = runner
24379            .state
24380            .github_text
24381            .as_ref()
24382            .unwrap()
24383            .question
24384            .clone()
24385            .unwrap();
24386        let store = ask::Questions::open();
24387        let mut q = store.get(&id).unwrap();
24388        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24389        q.answer(ask::Answer::Choice(
24390            crate::github_text::POST_ORIGINAL.into(),
24391        ))
24392        .unwrap();
24393        q.answer_delivered = true;
24394        store.put(&mut q).unwrap();
24395        let source = std::fs::read(store.path_of(&id)).unwrap();
24396        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24397        std::fs::create_dir_all(&migration).unwrap();
24398        std::fs::write(
24399            migration.join("state.json"),
24400            serde_json::to_vec(&serde_json::json!({
24401                "schema": 1, "sources": [id], "pending": [id]
24402            }))
24403            .unwrap(),
24404        )
24405        .unwrap();
24406        for _ in 0..2 {
24407            assert!(
24408                runner
24409                    .guarded_pr_message(&winner, None, true)
24410                    .await
24411                    .unwrap()
24412                    .is_none()
24413            );
24414            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24415            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24416        }
24417        let home = crate::run::home();
24418        crate::task_chat::sweep(
24419            &crate::queue::Queue::at(home.join("queue")),
24420            &crate::talk::Talks::at(home.join("talks")),
24421            &store,
24422            &home,
24423        );
24424        let outbox = crate::task_inquiry::Outbox::at(&home);
24425        outbox
24426            .update_decision(&id, |d| {
24427                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24428                d.source_answer_at = q.answered_at;
24429                Ok(true)
24430            })
24431            .unwrap();
24432        outbox
24433            .settle(
24434                &id,
24435                "owner-chat",
24436                "Owner confirms no publication remains necessary",
24437                None,
24438            )
24439            .unwrap();
24440        assert!(
24441            runner
24442                .guarded_pr_message(&winner, None, true)
24443                .await
24444                .unwrap()
24445                .is_none()
24446        );
24447        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24448        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24449    }
24450
24451    #[tokio::test]
24452    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24453        crate::run::pin_test_home();
24454        let dir = tempfile::tempdir().unwrap();
24455        let mut runner = runner_at(RunStatus::Gating);
24456        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24457        runner.state.repo = dir.path().to_owned();
24458        runner.state.candidates[0].worktree = dir.path().to_owned();
24459        seed_public_summary(&mut runner);
24460        let winner = runner.state.candidates[0].clone();
24461        assert!(
24462            runner
24463                .guarded_pr_message(&winner, None, true)
24464                .await
24465                .unwrap()
24466                .is_none()
24467        );
24468        let record = runner.state.github_text.as_ref().unwrap();
24469        assert!(record.rewrite.is_none());
24470        // Records written before the additive field deserialize with no rewrite.
24471        let mut old = serde_json::to_value(record).unwrap();
24472        old.as_object_mut().unwrap().remove("rewrite");
24473        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24474        assert!(old.rewrite.is_none());
24475        let id = record.question.clone().unwrap();
24476        ask::Questions::open()
24477            .update(&id, |q| {
24478                q.choices.push(crate::github_text::USE_REWRITE.into());
24479                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24480            })
24481            .unwrap();
24482        let message = runner
24483            .guarded_pr_message(&winner, None, true)
24484            .await
24485            .unwrap()
24486            .unwrap();
24487        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24488        assert_eq!(
24489            runner.state.github_text.as_ref().unwrap().choice,
24490            Some(GithubTextChoice::Fallback)
24491        );
24492    }
24493
24494    #[tokio::test]
24495    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24496        crate::run::pin_test_home();
24497        let dir = tempfile::tempdir().unwrap();
24498        let mut runner = runner_at(RunStatus::Gating);
24499        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24500        runner.state.repo = dir.path().to_owned();
24501        runner.state.candidates[0].worktree = dir.path().to_owned();
24502        seed_public_summary(&mut runner);
24503        let winner = runner.state.candidates[0].clone();
24504        assert!(
24505            runner
24506                .guarded_pr_message(&winner, None, true)
24507                .await
24508                .unwrap()
24509                .is_none()
24510        );
24511        let store = ask::Questions::open();
24512        let find = |run: &str| {
24513            store
24514                .list()
24515                .into_iter()
24516                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24517                .unwrap()
24518        };
24519        let run = runner.state.id.clone();
24520        let q = find(&run);
24521        let fp = runner
24522            .state
24523            .github_text
24524            .as_ref()
24525            .unwrap()
24526            .fingerprint
24527            .clone();
24528        let name = crate::github_text::artifact_name(&fp);
24529        let path = crate::run::artifact_path(&runner.state, &name);
24530        assert!(q.detail.contains(&path.display().to_string()));
24531        assert!(q.detail.contains("title-language: title"));
24532        let saved = std::fs::read_to_string(&path).expect("artifact written");
24533        assert!(saved.contains("日本語のタイトル"));
24534        assert!(q.cwd.is_none());
24535        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24536        // A bad replacement is refused and asked about once more.
24537        let say = |id: &str, text: &str, choice: &str| {
24538            store
24539                .update(id, |q| {
24540                    q.thread.push(ask::Turn {
24541                        who: ask::Who::Operator,
24542                        body: text.to_owned(),
24543                        at: jiff::Timestamp::now(),
24544                        note: None,
24545                    });
24546                    q.answer(ask::Answer::Choice(choice.to_owned()))
24547                })
24548                .unwrap();
24549        };
24550        say(&q.id, "まだ日本語", "use my text");
24551        assert!(
24552            runner
24553                .guarded_pr_message(&winner, None, true)
24554                .await
24555                .unwrap()
24556                .is_none()
24557        );
24558        let second = find(&run);
24559        assert_ne!(second.id, q.id);
24560        assert!(second.detail.contains("did not pass"));
24561        // The retry still compares the original text; the rejected
24562        // replacement is named by category only.
24563        assert!(second.detail.contains("日本語のタイトル"));
24564        assert!(!second.detail.contains("まだ日本語"));
24565        assert!(second.detail.contains(&path.display().to_string()));
24566        say(&second.id, "fix: retry failed requests", "use my text");
24567        let message = runner
24568            .guarded_pr_message(&winner, None, true)
24569            .await
24570            .unwrap()
24571            .expect("a vetted replacement is posted");
24572        assert_eq!(message.title, "fix: retry failed requests");
24573        assert_eq!(
24574            runner
24575                .state
24576                .github_text
24577                .as_ref()
24578                .unwrap()
24579                .chosen_title
24580                .as_deref(),
24581            Some("fix: retry failed requests")
24582        );
24583        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24584        // Resumed again: the saved decision is applied, nothing is re-asked.
24585        let again = runner
24586            .guarded_pr_message(&winner, None, true)
24587            .await
24588            .unwrap()
24589            .unwrap();
24590        assert_eq!(again.title, message.title);
24591        assert_eq!(
24592            store
24593                .list()
24594                .into_iter()
24595                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24596                .count(),
24597            2
24598        );
24599    }
24600
24601    #[test]
24602    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24603        // What magi itself writes stays English under any configured language,
24604        // so a future localisation of these headings fails here. (The agents'
24605        // own text is also checked by the posting gate.)
24606        let mut state = state_with_summary(
24607            "add retries",
24608            "TITLE: fix(web): batch reads\n- reads run.json once",
24609        );
24610        state.config.graph.language = "ja".to_owned();
24611        let m = pr_message(&state, 'A');
24612        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24613        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24614
24615        // The task is the operator's own text: it goes in untouched, and the
24616        // fallback title (no summary) may be in its language too.
24617        let task = "今回やってほしいこと: results projector を直す";
24618        let mut state = state_with_summary(task, "- no title line");
24619        state.config.graph.language = "ja".to_owned();
24620        let m = pr_message(&state, 'A');
24621        assert_eq!(
24622            m.title,
24623            format!("chore: land candidate A of run {}", state.id)
24624        );
24625        assert!(
24626            m.body.contains(&format!(
24627                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24628            )),
24629            "{}",
24630            m.body
24631        );
24632    }
24633
24634    #[test]
24635    fn pr_message_scrubs_home_paths_and_addresses() {
24636        let state = state_with_summary(
24637            "fix it in /Users/someone/src/x",
24638            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24639        );
24640        let m = pr_message(&state, 'A');
24641        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24642            assert!(!m.body.contains(leak), "{}", m.body);
24643        }
24644        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24645    }
24646
24647    #[test]
24648    fn pr_message_survives_a_task_that_closes_details() {
24649        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24650        let m = pr_message(&state, 'A');
24651        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24652    }
24653
24654    #[test]
24655    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24656        let cmd = manual_merge_command(
24657            MergeStyle::Squash,
24658            Path::new("/repo"),
24659            "b",
24660            "fix: \"quoted\" $(x) `y`\n\nbody",
24661        );
24662        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24663    }
24664
24665    #[test]
24666    fn manual_merge_command_matches_the_configured_style() {
24667        let repo = Path::new("/repo");
24668        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24669
24670        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24671        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24672
24673        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24674        assert_eq!(
24675            squash,
24676            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24677             \"Merge magi run 0832 (candidate A)\""
24678        );
24679
24680        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24681        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24682    }
24683
24684    #[test]
24685    fn a_nudge_gets_a_quarter_of_the_budget() {
24686        // The judge and implement budgets magi ships with.
24687        assert_eq!(retry_budget(secs(1200), true), secs(300));
24688        assert_eq!(retry_budget(secs(3600), true), secs(900));
24689    }
24690
24691    #[test]
24692    fn a_resent_prompt_keeps_the_whole_budget() {
24693        // The seat kept no context, so the retry is the original job again and
24694        // shortening it would only guarantee a second failure.
24695        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24696        assert_eq!(retry_budget(secs(60), false), secs(60));
24697    }
24698
24699    #[test]
24700    fn the_floor_never_exceeds_the_original_budget() {
24701        // A short configured timeout must not be *raised* by the floor: the
24702        // operator asked for a bound, and a retry may not outlast the attempt
24703        // it is retrying.
24704        assert_eq!(retry_budget(secs(60), true), secs(60));
24705        assert_eq!(retry_budget(secs(480), true), secs(120));
24706        assert_eq!(retry_budget(secs(0), true), secs(0));
24707    }
24708
24709    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24710        agent::CommandEvidence {
24711            id: "item1".to_owned(),
24712            description: "cargo test".to_owned(),
24713            exit_code,
24714            result_summary: String::new(),
24715            source: "codex".to_owned(),
24716        }
24717    }
24718
24719    #[test]
24720    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
24721        // No evidence is not the same fact as unconfirmed evidence: a
24722        // backend with no adapter, or a reply that ran no commands at all,
24723        // must not be misread as carrying a dangling job.
24724        assert!(!has_unconfirmed_command(&[]));
24725    }
24726
24727    #[test]
24728    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
24729        // Deliberately not a check on the exit code's *value*: a fixer
24730        // legitimately runs something that fails mid-iteration before it
24731        // succeeds, and that must never by itself reopen a valid report.
24732        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
24733        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
24734        assert!(!has_unconfirmed_command(&[
24735            evidence(Some(0)),
24736            evidence(Some(101))
24737        ]));
24738    }
24739
24740    #[test]
24741    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
24742        assert!(has_unconfirmed_command(&[
24743            evidence(Some(0)),
24744            evidence(None)
24745        ]));
24746    }
24747
24748    #[test]
24749    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
24750        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24751        assert_eq!(
24752            verified_noop_claim(true, &[], text).as_deref(),
24753            Some("already fixed by b32cfc4, on main.")
24754        );
24755    }
24756
24757    #[test]
24758    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
24759        // A timeout or a bad exit code reads as the ordinary loss it is,
24760        // whatever the reply's own prose claims.
24761        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24762        assert!(verified_noop_claim(false, &[], text).is_none());
24763    }
24764
24765    #[test]
24766    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
24767        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24768        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
24769        // A confirmed command alongside the marker is fine.
24770        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
24771    }
24772
24773    #[test]
24774    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
24775        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
24776    }
24777
24778    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
24779    /// pair, in order, labelled A, B, C, ...
24780    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
24781        runner.state.candidates = shape
24782            .iter()
24783            .enumerate()
24784            .map(|(i, &(empty, verified))| Candidate {
24785                index: i,
24786                label: (b'A' + i as u8) as char,
24787                agent: "sonnet".to_owned(),
24788                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
24789                worktree: PathBuf::from(format!("/wt/{i}")),
24790                summary: String::new(),
24791                stat: String::new(),
24792                files: 0,
24793                commits: 0,
24794                empty,
24795                failed: None,
24796                verified_noop: verified.map(str::to_owned),
24797                duration_ms: 0,
24798                folded: false,
24799            })
24800            .collect();
24801    }
24802
24803    #[test]
24804    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
24805        ask_test_home();
24806        let mut runner = runner_at(RunStatus::Implementing);
24807        set_candidates(
24808            &mut runner,
24809            &[
24810                (true, Some("already on main at b32cfc4")),
24811                (true, Some("same fix, see the existing test")),
24812            ],
24813        );
24814
24815        runner
24816            .after_implement()
24817            .expect("a verified no-op is not an error");
24818
24819        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
24820    }
24821
24822    #[test]
24823    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
24824        ask_test_home();
24825        let mut runner = runner_at(RunStatus::Implementing);
24826        // Candidate A declares a verified no-op; candidate B simply wrote
24827        // nothing and said nothing about why. One candidate's claim is not
24828        // the whole run's agreement.
24829        set_candidates(
24830            &mut runner,
24831            &[(true, Some("already on main at b32cfc4")), (true, None)],
24832        );
24833
24834        let err = runner
24835            .after_implement()
24836            .expect_err("an unverified empty candidate must still fail the run");
24837
24838        assert!(
24839            err.to_string().contains("no candidate produced a change"),
24840            "{err}"
24841        );
24842        assert_eq!(runner.state.status, RunStatus::Failed);
24843    }
24844
24845    #[test]
24846    fn after_implement_still_fails_an_ordinary_all_empty_run() {
24847        ask_test_home();
24848        let mut runner = runner_at(RunStatus::Implementing);
24849        set_candidates(&mut runner, &[(true, None), (true, None)]);
24850
24851        let err = runner
24852            .after_implement()
24853            .expect_err("no candidate declared anything; this is an ordinary failure");
24854
24855        assert!(
24856            err.to_string().contains("no candidate produced a change"),
24857            "{err}"
24858        );
24859        assert_eq!(runner.state.status, RunStatus::Failed);
24860    }
24861}
24862
24863/// A graft rollback whose restore could not be confirmed (see
24864/// [`Runner::graft`]).
24865#[derive(Debug)]
24866struct GraftRestoreFailed(String);
24867
24868impl std::fmt::Display for GraftRestoreFailed {
24869    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24870        write!(
24871            f,
24872            "could not restore the winner to its pre-graft commit: {}",
24873            self.0
24874        )
24875    }
24876}
24877
24878impl std::error::Error for GraftRestoreFailed {}
24879
24880/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
24881/// not the agent: they never draw on an agent's own timeout, and running out of
24882/// them never reads as an agent failure.
24883#[cfg(test)]
24884mod resource_wait_tests {
24885    use super::*;
24886    use std::collections::BTreeMap;
24887
24888    fn sh(id: &str, script: &str) -> AgentSpec {
24889        AgentSpec {
24890            id: id.to_owned(),
24891            kind: crate::config::AgentKind::Command,
24892            model: None,
24893            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
24894            extra_args: Vec::new(),
24895            env: BTreeMap::new(),
24896            prompt_delivery: None,
24897            max_turn_secs: None,
24898        }
24899    }
24900
24901    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
24902        SeatJob {
24903            seat: SeatState::new("impl-A", &spec.id, 1),
24904            spec,
24905            cwd: dir.to_path_buf(),
24906            prompt: "do it".to_owned(),
24907            timeout,
24908            allow_write: true,
24909            sessions: false,
24910            artifacts: dir.join("art"),
24911            stem: "impl-A".to_owned(),
24912            handover: None,
24913        }
24914    }
24915
24916    fn state(resource_wait_secs: u64) -> RunState {
24917        let mut config = Config::default();
24918        config.graph.timeout_resource_wait = resource_wait_secs;
24919        RunState::new(
24920            PathBuf::from("/repo"),
24921            "main".to_owned(),
24922            "abc1234".to_owned(),
24923            "task".to_owned(),
24924            config,
24925        )
24926    }
24927
24928    fn hold(cache: &Path) -> crate::cache::Guard {
24929        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
24930        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
24931            crate::cache::AcquireOutcome::Acquired(g) => g,
24932            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
24933        }
24934    }
24935
24936    async fn run(
24937        jobs: Vec<SeatJob>,
24938        sem: Arc<Semaphore>,
24939        cache: Option<&Path>,
24940        st: &mut RunState,
24941    ) -> Vec<(usize, SeatState, AgentOutcome)> {
24942        let prompts = Prompts::default();
24943        let ctx = WaveCtx {
24944            run: "r",
24945            node: "implement",
24946            prompts: &prompts,
24947            cache,
24948            round: None,
24949            carry_seats: false,
24950            pauses: None,
24951        };
24952        wave(jobs, sem, &ctx, st, 0).await
24953    }
24954
24955    #[tokio::test]
24956    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
24957        crate::run::pin_test_home();
24958        let home = crate::run::home();
24959        let tmp = tempfile::tempdir().unwrap();
24960        let repo = tmp.path().join("repo");
24961        let checkout = tmp.path().join("checkout");
24962        std::fs::create_dir(&repo).unwrap();
24963        git::git(&repo, &["init"]).await.unwrap();
24964        git::git(
24965            &repo,
24966            &[
24967                "-c",
24968                "user.name=Fixture",
24969                "-c",
24970                "user.email=fixture@example.invalid",
24971                "commit",
24972                "--allow-empty",
24973                "-m",
24974                "initial",
24975            ],
24976        )
24977        .await
24978        .unwrap();
24979        git::worktree_add_detached(&repo, &checkout, "HEAD")
24980            .await
24981            .unwrap();
24982        let target = crate::build_target::resolve(&home, &checkout).unwrap();
24983        let target_lease = hold(&target);
24984        let shared = tmp.path().join("unrelated");
24985        let _shared_lease = hold(&shared);
24986        let mut st = state(0);
24987        st.repo = repo.clone();
24988        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
24989        st.config.verify.e2e = vec![format!(
24990            "CARGO_TARGET_DIR='{}' cargo test",
24991            git::path_arg(&shared)
24992        )];
24993        let config = tmp.path().join("config.toml");
24994        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
24995        let prompts = Prompts::default();
24996        let run_id = st.id.clone();
24997        let ctx = WaveCtx {
24998            run: &run_id,
24999            node: "implement",
25000            prompts: &prompts,
25001            cache: None,
25002            round: None,
25003            carry_seats: false,
25004            pauses: None,
25005        };
25006        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
25007        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
25008        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25009        assert_eq!(results[0].1.turns, 0);
25010        let saved = RunState::load_under(&run_id, &home).unwrap();
25011        let block = saved.resource_block.unwrap();
25012        assert!(matches!(
25013            block.cause,
25014            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
25015                if actual == &target
25016        ));
25017        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
25018        let mut task = crate::queue::Task::new(
25019            "build".into(),
25020            "build".into(),
25021            repo,
25022            crate::queue::Source::Human,
25023        );
25024        task.runs.push(run_id);
25025        task.hold_machine(Some(format!(
25026            "{}{}",
25027            crate::cache::RESOURCE_HOLD,
25028            block.description()
25029        )));
25030        queue.put(&mut task).unwrap();
25031        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
25032        let triage =
25033            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
25034        let pending = triage();
25035        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
25036        assert_eq!(
25037            queue.get(&task.id).unwrap().status,
25038            crate::queue::TaskStatus::Held
25039        );
25040        drop(target_lease);
25041        assert_eq!(triage().resumed, vec![task.id.clone()]);
25042        assert_eq!(
25043            queue.get(&task.id).unwrap().status,
25044            crate::queue::TaskStatus::Queued
25045        );
25046        assert!(crate::cache::in_use(&home, &shared));
25047    }
25048
25049    #[tokio::test]
25050    async fn verification_cache_wait_preserves_the_command_budget() {
25051        crate::run::pin_test_home();
25052        let tmp = tempfile::tempdir().unwrap();
25053        let cache = tmp.path().join("target");
25054        let guard = hold(&cache);
25055        let release = tokio::spawn(async move {
25056            tokio::time::sleep(Duration::from_millis(100)).await;
25057            guard.release();
25058        });
25059        let mut st = state(10);
25060        let budget = Duration::from_millis(50);
25061        let wait = repository_wait(&st, None);
25062        let (outcomes, _) = with_cache_lease(
25063            &mut st,
25064            Some(&cache),
25065            "gate",
25066            "gate",
25067            tmp.path(),
25068            "abc1234",
25069            budget,
25070            "test gate",
25071            &wait,
25072            |_, available| async move {
25073                assert_eq!(
25074                    available, budget,
25075                    "contention must not shorten verification"
25076                );
25077                (Vec::new(), false, Vec::new())
25078            },
25079        )
25080        .await
25081        .unwrap();
25082        release.await.unwrap();
25083        assert!(outcomes.is_empty(), "{outcomes:?}");
25084        assert!(
25085            st.events
25086                .iter()
25087                .any(|event| event.message.contains("waiting for"))
25088        );
25089        assert!(st.resource_wait.is_none());
25090        // The verification body no longer owns the lease after returning.
25091        hold(&cache).release();
25092    }
25093
25094    #[tokio::test]
25095    async fn verification_cache_wait_expires_without_starting_commands() {
25096        crate::run::pin_test_home();
25097        let tmp = tempfile::tempdir().unwrap();
25098        let cache = tmp.path().join("target");
25099        let _held = hold(&cache);
25100        let mut st = state(0);
25101        let wait = repository_wait(&st, None);
25102        let (outcomes, _) = with_cache_lease(
25103            &mut st,
25104            Some(&cache),
25105            "gate",
25106            "gate",
25107            tmp.path(),
25108            "abc1234",
25109            Duration::from_secs(60),
25110            "test gate",
25111            &wait,
25112            |_, _| async { panic!("commands must not start without the cache lease") },
25113        )
25114        .await
25115        .unwrap();
25116        assert_eq!(outcomes.len(), 1);
25117        assert!(outcomes[0].resource_blocked);
25118        assert!(st.resource_wait.is_none());
25119        assert!(matches!(
25120            st.resource_block.unwrap().cause,
25121            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25122        ));
25123    }
25124
25125    #[tokio::test]
25126    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25127        crate::run::pin_test_home();
25128        let tmp = tempfile::tempdir().unwrap();
25129        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25130        let cache = tmp.path().join("cache");
25131        let mut state = state(21600);
25132        let wait = repository_wait(&state, None);
25133        let (outcomes, _) = with_cache_lease(
25134            &mut state,
25135            Some(&cache),
25136            "gate",
25137            "gate",
25138            tmp.path(),
25139            "head",
25140            Duration::from_secs(60),
25141            "gate",
25142            &wait,
25143            |_, _| async { panic!("freshness failure must not start verification") },
25144        )
25145        .await
25146        .unwrap();
25147        assert_eq!(outcomes.len(), 1);
25148        assert!(outcomes[0].resource_blocked);
25149        let block = state.resource_block.unwrap();
25150        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25151        assert!(!block.description().contains("timed out"));
25152    }
25153
25154    #[tokio::test]
25155    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25156        crate::run::pin_test_home();
25157        let tmp = tempfile::tempdir().unwrap();
25158        let cache = tmp.path().join("cache");
25159        let _held = hold(&cache);
25160        let mut state = state(21600);
25161        let pause = Pause::new();
25162        let interrupt = Pause::new();
25163        let cause = ParkCause::Operator;
25164        pause.park_for(cause.clone());
25165        let prompts = Prompts::default();
25166        let ctx = WaveCtx {
25167            run: "test",
25168            node: "fix",
25169            prompts: &prompts,
25170            cache: Some(&cache),
25171            round: None,
25172            carry_seats: false,
25173            pauses: Some((&pause, &interrupt)),
25174        };
25175        let result = wave(
25176            vec![job(
25177                sh("writer", "exit 99"),
25178                tmp.path(),
25179                Duration::from_secs(1),
25180            )],
25181            Arc::new(Semaphore::new(1)),
25182            &ctx,
25183            &mut state,
25184            0,
25185        )
25186        .await;
25187        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
25188        assert_eq!(result[0].1.turns, 0);
25189        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25190        assert_eq!(
25191            state.resource_block.unwrap().cause,
25192            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
25193        );
25194        assert!(state.active.is_empty());
25195    }
25196
25197    #[tokio::test]
25198    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
25199        crate::run::pin_test_home();
25200        let tmp = tempfile::tempdir().unwrap();
25201        let cache = tmp.path().join("target-a");
25202        let guard = hold(&cache);
25203        // Held for longer than the agent's whole 1s budget.
25204        tokio::spawn(async move {
25205            tokio::time::sleep(Duration::from_millis(1500)).await;
25206            guard.release();
25207        });
25208        let mut st = state(60);
25209        let results = run(
25210            vec![job(
25211                sh("alpha", "echo ok"),
25212                tmp.path(),
25213                Duration::from_secs(1),
25214            )],
25215            Arc::new(Semaphore::new(1)),
25216            Some(&cache),
25217            &mut st,
25218        )
25219        .await;
25220        assert!(
25221            matches!(results[0].2, AgentOutcome::Ok(_)),
25222            "the wait must not be charged to the agent"
25223        );
25224        assert!(st.resource_block.is_none());
25225        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25226        assert!(st.resource_wait.is_none() && st.active.is_empty());
25227    }
25228
25229    #[tokio::test]
25230    #[cfg(unix)]
25231    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
25232        use std::os::fd::AsRawFd as _;
25233        crate::run::pin_test_home();
25234        let tmp = tempfile::tempdir().unwrap();
25235        crate::git::git(tmp.path(), &["init"]).await.unwrap();
25236        let common = tmp.path().join(".git");
25237        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
25238        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
25239        assert_eq!(
25240            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
25241            0
25242        );
25243        let mut st = state(1);
25244        st.config.coordination = crate::config::test_coordination();
25245        let mut reader = job(
25246            sh("reader", "echo must-not-run"),
25247            tmp.path(),
25248            Duration::from_secs(30),
25249        );
25250        reader.allow_write = false;
25251        let results = run(
25252            vec![reader.clone()],
25253            Arc::new(Semaphore::new(1)),
25254            None,
25255            &mut st,
25256        )
25257        .await;
25258        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25259        assert_eq!(results[0].1.turns, 0);
25260        assert!(FailClass::of(&results[0].2).is_none());
25261        assert_eq!(
25262            st.resource_block.as_ref().unwrap().kind,
25263            "repository coordination"
25264        );
25265        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25266        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25267        drop(external);
25268        let editor = crate::repo_lock::SeatLease::for_checkout(
25269            tmp.path(),
25270            true,
25271            crate::config::test_coordination().as_ref(),
25272        )
25273        .await
25274        .unwrap();
25275        let pause = Pause::new();
25276        let interrupt = Pause::new();
25277        let prompts = Prompts::default();
25278        let ctx = WaveCtx {
25279            run: "r",
25280            node: "review",
25281            prompts: &prompts,
25282            cache: None,
25283            round: None,
25284            carry_seats: false,
25285            pauses: Some((&pause, &interrupt)),
25286        };
25287        let (results, ()) = tokio::join!(
25288            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25289            async {
25290                tokio::time::sleep(Duration::from_millis(50)).await;
25291                pause.park();
25292            }
25293        );
25294        assert!(
25295            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25296        );
25297        assert_eq!(results[0].1.turns, 0);
25298        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25299        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25300        drop(editor);
25301    }
25302
25303    #[tokio::test]
25304    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25305        crate::run::pin_test_home();
25306        let tmp = tempfile::tempdir().unwrap();
25307        let cache = tmp.path().join("target-b");
25308        let _held = hold(&cache);
25309        let mut st = state(1);
25310        let results = run(
25311            vec![job(
25312                sh("alpha", "echo ok"),
25313                tmp.path(),
25314                Duration::from_secs(1),
25315            )],
25316            Arc::new(Semaphore::new(1)),
25317            Some(&cache),
25318            &mut st,
25319        )
25320        .await;
25321        let (_, seat, out) = &results[0];
25322        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25323        assert!(wave_blocked(&results));
25324        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25325        assert_eq!(seat.turns, 0, "nothing was asked");
25326        assert!(
25327            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25328            "no agent was spawned"
25329        );
25330        assert!(FailClass::of(out).is_none(), "not a failure class");
25331        let block = st.resource_block.as_ref().expect("recorded for the resume");
25332        assert_eq!(block.kind, "shared build cache");
25333        assert!(matches!(
25334            block.cause,
25335            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25336        ));
25337        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25338        assert!(st.active.is_empty());
25339    }
25340
25341    #[tokio::test]
25342    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25343        crate::run::pin_test_home();
25344        let tmp = tempfile::tempdir().unwrap();
25345        let mut st = state(1);
25346        let results = run(
25347            vec![job(
25348                sh("alpha", "echo ok"),
25349                tmp.path(),
25350                Duration::from_secs(1),
25351            )],
25352            Arc::new(Semaphore::new(0)),
25353            None,
25354            &mut st,
25355        )
25356        .await;
25357        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25358        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25359        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25360    }
25361
25362    #[tokio::test]
25363    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25364        crate::run::pin_test_home();
25365        let tmp = tempfile::tempdir().unwrap();
25366        let mut st = state(60);
25367        let results = run(
25368            vec![job(
25369                sh("alpha", "sleep 30"),
25370                tmp.path(),
25371                Duration::from_secs(1),
25372            )],
25373            Arc::new(Semaphore::new(1)),
25374            None,
25375            &mut st,
25376        )
25377        .await;
25378        let out = &results[0].2;
25379        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25380        let class = FailClass::of(out).expect("a failure");
25381        assert_eq!(class, FailClass::Timeout);
25382        assert!(should_hand_over(None, &class), "existing handover policy");
25383        assert!(st.resource_block.is_none());
25384    }
25385}