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        anyhow::ensure!(
1461            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1462            "{}",
1463            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1464        );
1465        state.ensure_base_episode();
1466        state.record_base_sync_stop(&head);
1467        anyhow::ensure!(
1468            state
1469                .base_sync_recovery
1470                .stop
1471                .as_ref()
1472                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1473            "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"
1474        );
1475        let fetched =
1476            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1477        anyhow::ensure!(
1478            fetched.ok(),
1479            "cannot authorize base recovery without a fetched base"
1480        );
1481        let approved_tip = git::rev_parse(
1482            &state.repo,
1483            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1484        )
1485        .await?;
1486        if let Some(control) = control.as_deref_mut() {
1487            let queue = crate::queue::Queue::at(home.join("queue"));
1488            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1489            if let Some(prior) = state
1490                .base_sync_recovery
1491                .authorizations
1492                .iter()
1493                .find(|a| a.request.as_deref() == Some(&control.key()))
1494            {
1495                anyhow::ensure!(
1496                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1497                    "recovery request was consumed or invalidated; it cannot queue again"
1498                );
1499                return control.enqueue(&queue);
1500            }
1501        }
1502        if resumption {
1503            anyhow::ensure!(
1504                crate::daemon::compatible_run_instruction(&state, &queued),
1505                "resumption instruction does not match the retained run"
1506            );
1507            let approval = queued
1508                .resumption
1509                .as_ref()
1510                .context("no operator resumption")?;
1511            anyhow::ensure!(
1512                approval.instruction == queued.instruction,
1513                "resumption approval does not match the current task instruction"
1514            );
1515            state.authorize_base_sync_resumption(task, approval)?;
1516        } else {
1517            state.authorize_base_sync(task)?;
1518        }
1519        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1520        state
1521            .base_sync_recovery
1522            .authorizations
1523            .last_mut()
1524            .unwrap()
1525            .scope = Some(crate::base_sync_recovery::Scope {
1526            tip: approved_tip,
1527            instruction: queued.instruction.clone(),
1528            episode,
1529        });
1530        if let Some(control) = control.as_deref_mut() {
1531            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1532            authorization.request = Some(control.key());
1533            authorization.generation = control.generation();
1534            authorization.decision = control.decision();
1535            authorization.question = control
1536                .request
1537                .decision
1538                .as_ref()
1539                .map(|_| control.request.request.clone());
1540        }
1541        state.event(
1542            "base-recovery",
1543            "owner authorized a bounded base synchronization interval; fresh verification required",
1544        );
1545        state.save_under(home)?;
1546        if let Some(control) = control {
1547            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1548        }
1549        Ok(())
1550    }
1551
1552    /// Reopen an existing run.
1553    pub fn resume(id: &str) -> Result<Self> {
1554        let state = RunState::load(id)?;
1555        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1556        if state.startup.as_ref().is_some_and(|s| !s.complete)
1557            || (state.status == RunStatus::Prep
1558                && state.instruction.trim().is_empty()
1559                && state.candidates.is_empty()
1560                && state.prep_complete == Some(false))
1561        {
1562            bail!(
1563                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1564            );
1565        }
1566        crate::pr_head::ensure_owner(&state)?;
1567        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1568            bail!(
1569                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1570            );
1571        }
1572        if let Some(to) = &state.released_to {
1573            bail!(
1574                "run {} cannot be resumed: its worktree was released to run {}",
1575                state.short(),
1576                crate::run::short_of(to)
1577            );
1578        }
1579        let roles = state.config.resolve_roles()?;
1580        if let Some(id) = &state.config.graph.selected_implementer
1581            && state.candidates.iter().any(|c| c.agent != *id)
1582        {
1583            bail!(
1584                "replacement implementer pin does not match the saved candidates; task must stay held"
1585            );
1586        }
1587        let max_parallel = state.config.graph.max_parallel.max(1);
1588        Ok(Self {
1589            state,
1590            roles,
1591            sem: Arc::new(Semaphore::new(max_parallel)),
1592            pause: Pause::new(),
1593            interrupt: Pause::new(),
1594        })
1595    }
1596
1597    /// Walk the graph to a terminal state, skipping nodes already recorded.
1598    ///
1599    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1600    /// the phone - ends here, so this is the one place a run that ended
1601    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1602    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1603    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1604        // Allocate before polling: boxing inside an async wrapper would still
1605        // retain its construction frame while the nested graph is polled.
1606        Box::pin(self.execute_inner(None))
1607    }
1608
1609    pub(crate) async fn execute_sync_only(
1610        &mut self,
1611        request: crate::base_sync_only::Request,
1612    ) -> Result<()> {
1613        Box::pin(self.execute_inner(Some(request))).await
1614    }
1615
1616    async fn execute_inner(
1617        &mut self,
1618        sync_only: Option<crate::base_sync_only::Request>,
1619    ) -> Result<()> {
1620        anyhow::ensure!(
1621            self.state.startup.as_ref().is_none_or(|s| s.complete),
1622            "startup incomplete; inspect retained evidence before explicit recovery"
1623        );
1624        if let Some(selection) = &self.state.pr_recovery
1625            && (selection.source_proof.is_some() || selection.source_run.is_some())
1626        {
1627            Box::pin(selection.verify_source(&self.state.repo)).await?;
1628        }
1629        // Queue claims cover daemon work; this also serializes manual drivers
1630        // consuming a repair answer, including the new review and decision.
1631        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1632            || self.state.land_approval.is_some()
1633            || self.state.merge_decision.is_some()
1634            || !self.state.merge_repairs.is_empty()
1635            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1636        {
1637            let claim = FixClaim::acquire(&self.state.dir())?;
1638            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1639            let disk = RunState::load(&self.state.id)?;
1640            let checkpoint = |s: &RunState| {
1641                (
1642                    s.merge_repairs.len(),
1643                    s.merge_repairs
1644                        .last()
1645                        .map(|r| (r.question.clone(), r.phase)),
1646                    s.land_approval
1647                        .as_ref()
1648                        .map(|a| (a.question.clone(), a.head.clone())),
1649                )
1650            };
1651            if checkpoint(&disk) != checkpoint(&self.state) {
1652                bail!(
1653                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1654                );
1655            }
1656            Some(claim)
1657        } else {
1658            None
1659        };
1660        let base_only = sync_only.is_some();
1661        let mut execution = self.claim_driver(sync_only).await?;
1662        let runner = &mut *execution.runner;
1663        let wait = runner.repository_wait();
1664        // Keep the graph's large future off the callers' stack, including
1665        // standalone task attempts running on a default-sized test thread.
1666        let result = if base_only {
1667            wait.scope(Box::pin(async {
1668                let repo = runner.state.repo.clone();
1669                let result = async {
1670                    let _coordination = runner.coordinate(&repo).await?;
1671                    anyhow::ensure!(
1672                        !runner.pause.parked() && !runner.interrupt.parked(),
1673                        "paused before base synchronization"
1674                    );
1675                    crate::base_sync_only::sync(&mut runner.state).await
1676                }
1677                .await;
1678                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1679                pass.result = match result {
1680                    Ok(outcome) => outcome,
1681                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1682                };
1683                let summary = pass.summary();
1684                runner.state.event("base-sync-only", summary);
1685                runner.state.save()
1686            }))
1687            .await
1688        } else {
1689            wait.scope(Box::pin(runner.execute_graph())).await
1690        };
1691        let result = match result {
1692            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1693                record_repository_block(&mut runner.state, &e);
1694                runner.park_here()?;
1695                Ok(())
1696            }
1697            other => other,
1698        };
1699        execution.driver.finish(&mut runner.state).await?;
1700        let ended = if result.is_err() {
1701            Some({
1702                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1703                if let Err(error) = &result {
1704                    notice.message = format!(
1705                        "Run {} stopped with an error: {}",
1706                        runner.state.id,
1707                        error.to_string().lines().next().unwrap_or("unknown error")
1708                    );
1709                }
1710                notice
1711            })
1712        } else {
1713            crate::notices::run_ended(&runner.state)
1714        };
1715        if let Some(notice) = ended {
1716            crate::notices::raise(notice);
1717        }
1718        result
1719    }
1720
1721    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1722        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1723    }
1724
1725    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1726        let wait = self.repository_wait();
1727        coordinate_operation(&mut self.state, cwd, &wait).await
1728    }
1729
1730    /// Validate ownership and persist the driver claim in one critical section.
1731    async fn claim_driver(
1732        &mut self,
1733        sync_only: Option<crate::base_sync_only::Request>,
1734    ) -> Result<DriverExecution<'_>> {
1735        let owner = match crate::pr_head::owner_lock_wait(
1736            &crate::run::home(),
1737            &self.state.id,
1738            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1739        )
1740        .await
1741        {
1742            Ok(owner) => owner,
1743            Err(error) => {
1744                let detail = format!("worktree maintenance or ownership update: {error:#}");
1745                // Admission did not own run.json: retain this resource outcome
1746                // in memory for queue settlement without overwriting a concurrent
1747                // retirement or publication transaction.
1748                self.state.resource_block = Some(crate::run::ResourceBlock {
1749                    cause: crate::run::ResourceBlockCause::Other,
1750                    node: "start".into(),
1751                    kind: "worktree maintenance".into(),
1752                    detail: detail.clone(),
1753                    at: Timestamp::now(),
1754                });
1755                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1756            }
1757        };
1758        let disk = RunState::load(&self.state.id)?;
1759        crate::pr_head::ensure_owner(&disk)?;
1760        let claimed =
1761            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1762        // Only proven-live ownership refuses here. Unknown records (legacy runs
1763        // with no claim marker or process identity) fall through to the
1764        // exclusive execution lease taken just below, which is what actually
1765        // keeps a second driver out.
1766        anyhow::ensure!(
1767            disk.liveness(claimed) != crate::run::Liveness::Live,
1768            "run already has a live driver; wait for its execution to end"
1769        );
1770        if let Some(to) = &disk.released_to {
1771            bail!(
1772                "run {} cannot continue: its worktree was released to run {}",
1773                self.state.short(),
1774                crate::run::short_of(to)
1775            );
1776        }
1777        anyhow::ensure!(
1778            serde_json::to_value(&disk.base_sync_recovery)?
1779                == serde_json::to_value(&self.state.base_sync_recovery)?,
1780            "base recovery changed since this run was loaded; reload the saved run"
1781        );
1782        anyhow::ensure!(
1783            disk.sync_only_passes == self.state.sync_only_passes,
1784            "base-only synchronization changed since this run was loaded; reload the saved run"
1785        );
1786        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1787        let mut execution = DriverExecution {
1788            runner: self,
1789            driver,
1790        };
1791        // Declare after the execution guard: on any claim error this short
1792        // lock must drop before that guard reloads and releases ownership.
1793        let _owner = owner;
1794        if let Some(request) = sync_only {
1795            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1796            anyhow::ensure!(
1797                request.run == disk.id,
1798                "sync-base-only request targets a different run"
1799            );
1800            let state = &mut execution.runner.state;
1801            let task_entry = state.next_pass_task_entry;
1802            *state = disk;
1803            state.next_pass_task_entry = task_entry;
1804            if state.pending_sync_only().is_some() {
1805                let pass_index = state.passes.len();
1806                let pass = state.sync_only_passes.last_mut().unwrap();
1807                anyhow::ensure!(
1808                    pass.request == request,
1809                    "interrupted base-only synchronization belongs to a different request"
1810                );
1811                pass.pass_index = pass_index;
1812            } else {
1813                let pass = crate::base_sync_only::Pass::new(request, state);
1814                state.sync_only_passes.push(pass);
1815            }
1816            if state.status == RunStatus::Failed {
1817                state.status = RunStatus::Blocked;
1818            }
1819        } else {
1820            anyhow::ensure!(
1821                disk.pending_sync_only().is_none(),
1822                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1823            );
1824            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1825                .await?;
1826        }
1827        let state = &mut execution.runner.state;
1828        // Moving again, so it is no longer parked. Set before the walk rather
1829        // than in `resume`, so every way of re-entering the graph clears it
1830        // and a card cannot claim a run is waiting to be resumed while the
1831        // agents are already working.
1832        state.parked = false;
1833        state.resource_wait = None;
1834        state.resource_block = None;
1835        // Any seat this state still lists as answering belongs to whatever
1836        // process last drove this run — this one included, if it crashed
1837        // mid-wave. Cleared and flushed immediately, before anything else
1838        // runs, so a resume can never show a seat as live when nothing is
1839        // asking it anything yet; the node that actually dispatches the next
1840        // wave repopulates it.
1841        state.clear_active();
1842        // Recorded in the same spot, and flushed together with the clear
1843        // above: this is the pid a reader checks (`RunState::liveness`) when
1844        // no daemon claim exists to answer "is a process still driving this
1845        // run" — a plain `magi run` / `magi review` typed into a terminal
1846        // claims nothing there. Always overwritten, never only-if-absent, so
1847        // a resumed run's stale pid from a previous, possibly-dead process
1848        // can never survive into this one's own report. Unlike
1849        // `clear_active`, this changes on every single `execute()` call, so
1850        // the save below is now unconditional rather than only-if-cleared.
1851        //
1852        // `driver_started_at` is recorded in the same breath, from this same
1853        // pid, so `liveness` can tell a live pid that is genuinely still us
1854        // apart from one the OS has since handed to an unrelated process —
1855        // see that field's own doc for why the pid alone is not enough.
1856        let pid = std::process::id();
1857        state.driver_pid = Some(pid);
1858        state.driver_started_at = crate::proc::process_started_at(pid);
1859        state.driver_exited = false;
1860        state.driver_claimed = Some(true);
1861        state.begin_pass();
1862        execution.driver.bind(state);
1863        state.save()?;
1864        execution.driver.record(state)?;
1865        Ok(execution)
1866    }
1867
1868    /// No conflict checkpoint proves dispatch was never reached. End that
1869    /// consumed generation so an owner can explicitly authorize a fresh one.
1870    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1871        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1872        if let Err(error) = &result
1873            && !error.is::<crate::repo_lock::ResourceBlocked>()
1874            && self
1875                .state
1876                .repair_grants
1877                .last()
1878                .is_some_and(|g| g.conflict.is_none())
1879        {
1880            self.state.repair_grants.last_mut().unwrap().phase =
1881                crate::repair_budget::Phase::Complete;
1882            self.state.status = RunStatus::Blocked;
1883            self.state.save()?;
1884            bail!(
1885                "{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",
1886                self.state.passes.last().map_or(0, |p| p.index)
1887            );
1888        }
1889        result
1890    }
1891
1892    /// A grant owns only these repair attempts. Confirmation reviews cannot
1893    /// create another fixer allowance, and every operation is restart-checkpointed.
1894    async fn execute_granted_repair(&mut self) -> Result<()> {
1895        use crate::repair_budget::{Kind, Phase};
1896        let index = self.state.repair_grants.len() - 1;
1897        let winner = self
1898            .state
1899            .winner()
1900            .cloned()
1901            .context("repair winner missing")?;
1902        loop {
1903            let grant = self.state.repair_grants[index].clone();
1904            match grant.phase {
1905                Phase::Pending => {
1906                    if grant.spent >= grant.receipt.request.rounds {
1907                        self.state.repair_grants[index].phase = Phase::Complete;
1908                        self.state.status = RunStatus::Blocked;
1909                        self.state.save()?;
1910                        return Ok(());
1911                    }
1912                    // Reserve before dispatch. A crash can consume an attempt,
1913                    // but can never duplicate it or reset saved fixer history.
1914                    self.state.repair_grants[index].spent += 1;
1915                    self.state.repair_grants[index].phase = Phase::Fixing;
1916                    self.state.save()?;
1917                    match grant.receipt.request.kind {
1918                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1919                        Kind::Gate => {
1920                            let failed = self.state.gate.clone();
1921                            let _ = self.gate_fix_round(&winner, &failed).await?;
1922                        }
1923                        Kind::Review => {
1924                            let mut record = self
1925                                .state
1926                                .reviews
1927                                .last()
1928                                .cloned()
1929                                .context("review failure missing")?;
1930                            let round = record.round;
1931                            let step = self.run_fix_round(&winner, &mut record).await?;
1932                            self.state.reviews[round - 1] = record;
1933                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1934                                self.state.repair_grants[index].phase = Phase::Complete;
1935                                self.state.status = RunStatus::Blocked;
1936                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1937                                self.state.save()?;
1938                                return Ok(());
1939                            }
1940                            if matches!(step, FixStep::Resource) {
1941                                self.stop_for_resource()?;
1942                                return Ok(());
1943                            }
1944                            self.state.save()?;
1945                        }
1946                    }
1947                    if self.resource_halt()? {
1948                        return Ok(());
1949                    }
1950                }
1951                Phase::Fixing => {
1952                    if grant.receipt.request.kind == Kind::BaseConflict {
1953                        self.repair_base_conflict(false).await?;
1954                    }
1955                    // Interrupted fixers may have left source changes or an
1956                    // unpushed commit. Preserve them before fresh assessment.
1957                    let _coordination = self.coordinate(&winner.worktree).await?;
1958                    let rescued = git::rescue_commit(
1959                        &winner.worktree,
1960                        "magi: preserve interrupted granted repair",
1961                    )
1962                    .await?;
1963                    self.state.note_withheld("repair-grant", &rescued.withheld);
1964                    // Fresh checks must supersede even a same-head failure.
1965                    // Archive rather than erase failure evidence or counters.
1966                    self.state
1967                        .verification_history
1968                        .push(crate::run::VerificationEvidence {
1969                            superseded_by: None,
1970                            archived_at: Some(Timestamp::now()),
1971                            fixes_spent: Some(self.state.gate_fixes.len()),
1972                            gate_head: self.state.gate_head.take(),
1973                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1974                            gate: std::mem::take(&mut self.state.gate),
1975                            e2e: self.state.head_e2e.take(),
1976                        });
1977                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1978                        self.state
1979                            .verification_history
1980                            .push(crate::run::VerificationEvidence {
1981                                superseded_by: None,
1982                                archived_at: Some(Timestamp::now()),
1983                                fixes_spent: Some(self.state.gate_fixes.len()),
1984                                gate_head: None,
1985                                gate_ran: false,
1986                                gate: Vec::new(),
1987                                e2e: Some(e2e),
1988                            });
1989                    }
1990                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1991                    self.state.repair_grants[index].head =
1992                        git::rev_parse(&winner.worktree, "HEAD").await?;
1993                    self.state.repair_grants[index].phase = Phase::Reviewing;
1994                    if grant.receipt.request.kind == Kind::BaseConflict {
1995                        self.state.base_sync_recovery.stop = None;
1996                        if let Some(sync) = &mut self.state.base_sync {
1997                            sync.tip = grant
1998                                .receipt
1999                                .request
2000                                .tip
2001                                .clone()
2002                                .context("repair base tip missing")?;
2003                            sync.conflict = None;
2004                            sync.behind = 0;
2005                        }
2006                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2007                    }
2008                    self.state.save()?;
2009                }
2010                Phase::Reviewing => {
2011                    self.review_loop_pass().await?;
2012                    if self.resource_halt()? {
2013                        return Ok(());
2014                    }
2015                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2016                    let clean = self.state.reviews.len() > grant.review_start
2017                        && self.state.reviews.last().is_some_and(|r| {
2018                            r.head == head
2019                                && r.clean
2020                                && r.expected > 0
2021                                && r.answered == r.expected
2022                                && matches!(
2023                                    r.e2e_status(),
2024                                    E2eStatus::Passed | E2eStatus::NotConfigured
2025                                )
2026                        });
2027                    if !clean {
2028                        // A confirmation review carries no additional fix budget.
2029                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2030                            == Kind::Review
2031                            && grant.spent < grant.receipt.request.rounds
2032                            && self.state.reviews.last().is_some_and(|r| {
2033                                r.fix.is_none()
2034                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2035                            }) {
2036                            Phase::Pending
2037                        } else {
2038                            Phase::Complete
2039                        };
2040                        self.state.status = RunStatus::Blocked;
2041                        self.state.event(
2042                            "repair-grant",
2043                            "fresh review did not clear the repaired head; no publication",
2044                        );
2045                        self.state.save()?;
2046                        if self.state.repair_grants[index].phase == Phase::Pending {
2047                            continue;
2048                        }
2049                        return Ok(());
2050                    }
2051                    self.state.repair_grants[index].phase = Phase::Gating;
2052                    self.state.save()?;
2053                }
2054                Phase::Gating => {
2055                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2056                    self.state.reconcile_verification_head(&head);
2057                    let wait = self.repository_wait();
2058                    if self
2059                        .state
2060                        .reviews
2061                        .last()
2062                        .is_none_or(|r| r.head != head || !r.clean)
2063                    {
2064                        self.state.status = RunStatus::Blocked;
2065                        self.state.repair_grants[index].phase = Phase::Complete;
2066                        self.state.event(
2067                            "repair-grant",
2068                            "head changed since fresh review; repair held",
2069                        );
2070                        self.state.save()?;
2071                        return Ok(());
2072                    }
2073                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2074                        return Ok(());
2075                    }
2076                    let outcomes = self.run_gate(&winner).await?;
2077                    if verify_inconclusive(&outcomes) {
2078                        return Ok(());
2079                    }
2080                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2081                    if after != head {
2082                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2083                        self.state.repair_grants[index].head = after;
2084                        self.state.repair_grants[index].phase = Phase::Reviewing;
2085                        self.state.status = RunStatus::Blocked;
2086                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2087                        self.state.save()?;
2088                        return Ok(());
2089                    }
2090                    let passed = outcomes.iter().all(CommandOutcome::ok);
2091                    // Follow-up grants owe the same guarded checkout delivery
2092                    // as the conflict repair that introduced the new head.
2093                    if passed
2094                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2095                    {
2096                        return Ok(());
2097                    }
2098                    self.state.repair_grants[index].succeeded = passed;
2099                    self.state.gate = outcomes;
2100                    self.state.gate_ran = true;
2101                    self.state.status = if passed {
2102                        RunStatus::Gating
2103                    } else {
2104                        RunStatus::Blocked
2105                    };
2106                    self.state.repair_grants[index].phase = if !passed
2107                        && grant.receipt.request.kind == Kind::Gate
2108                        && grant.spent < grant.receipt.request.rounds
2109                    {
2110                        Phase::Pending
2111                    } else {
2112                        Phase::Complete
2113                    };
2114                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2115                        // Persist publication debt with the successful checkpoint.
2116                        self.state.pr_publication_pending = true;
2117                    } else if passed {
2118                        self.state.status = RunStatus::Ready;
2119                    }
2120                    self.state.save()?;
2121                    if !passed {
2122                        continue;
2123                    }
2124                    // Existing PR ownership and push lease stay in place. The
2125                    // normal publisher owes the new reviewed/gated SHA, and
2126                    // land's fresh owner approval remains mandatory.
2127                    if self.state.config.merge.mode != MergeMode::Pr {
2128                        self.state.status = RunStatus::Ready;
2129                        self.state.event(
2130                            "repair-grant",
2131                            "repair verified locally; grant carries no merge authorization",
2132                        );
2133                        self.state.save()?;
2134                        return Ok(());
2135                    }
2136                    return self.merge().await;
2137                }
2138                Phase::Complete => return Ok(()),
2139            }
2140        }
2141    }
2142
2143    async fn execute_graph(&mut self) -> Result<()> {
2144        // Even a terminal run may reenter through an explicit recovery action.
2145        // Restore before prep shortcuts, saved conversations or graph nodes use
2146        // a disposable path; GC may already have removed its original objects.
2147        let archive_home = crate::run::home().canonicalize()?;
2148        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2149            let repo = self.state.repo.clone();
2150            let _coordination = self.coordinate(&repo).await?;
2151            ensure_setup_config(&mut self.state, &repo).await?;
2152            crate::retention::restore_execution_seats(
2153                &archive_home,
2154                &self.state,
2155                _coordination.as_ref(),
2156            )
2157            .await?;
2158        }
2159        self.state.configure_recovery_resume()?;
2160        if self
2161            .state
2162            .repair_grants
2163            .last()
2164            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2165        {
2166            return self.execute_granted_repair().await;
2167        }
2168        if self
2169            .state
2170            .repair_grants
2171            .last()
2172            .is_some_and(|g| !g.succeeded)
2173        {
2174            self.state.status = RunStatus::Blocked;
2175            self.state.save()?;
2176            return Ok(());
2177        }
2178        // Preservation may invalidate an old empty classification. Resolve it
2179        // before any resume shortcut can reuse a verdict or publish a branch.
2180        self.persist_candidates().await?;
2181        // A saved base stop outranks stage markers, including legacy Voting.
2182        // Recovery never reenters implementation, deliberation or voting.
2183        if self.state.base_sync_blocked() {
2184            self.sync_to_base().await?;
2185            if !self.state.base_sync_blocked()
2186                && self.state.status != RunStatus::AlreadyInBase
2187                && !self.resource_halt()?
2188            {
2189                self.finish_after_tally().await?;
2190            }
2191            return Ok(());
2192        }
2193        if self
2194            .state
2195            .merge_decision
2196            .as_ref()
2197            .is_some_and(|decision| !decision.closed)
2198            && self.state.status != RunStatus::Landing
2199        {
2200            if crate::merge_decision::resumable_hold(&self.state) {
2201                self.state.merge = Some(MergeOutcome {
2202                    mode: MergeMode::Pr,
2203                    ok: false,
2204                    detail: self
2205                        .state
2206                        .merge_decision
2207                        .as_ref()
2208                        .unwrap()
2209                        .target
2210                        .pr
2211                        .clone(),
2212                    empty: false,
2213                });
2214                self.run_land().await?;
2215                self.settle_questions();
2216                return Ok(());
2217            }
2218            bail!(
2219                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2220            );
2221        }
2222        if self.state.config.graph.selected_implementer.is_some()
2223            && self.state.status == RunStatus::Blocked
2224            && self.state.tally.is_none()
2225            && self.state.candidate_preservation.is_empty()
2226            && self.state.interrupted_implementations.is_empty()
2227        {
2228            bail!(
2229                "selected implementation is held; explicitly release the owning task to retry it"
2230            );
2231        }
2232
2233        if self.state.merge_repairs.last().is_some_and(|r| {
2234            matches!(
2235                r.phase,
2236                crate::run::MergeRepairPhase::Requested
2237                    | crate::run::MergeRepairPhase::Fixing
2238                    | crate::run::MergeRepairPhase::Reviewing
2239            )
2240        }) {
2241            if self.repair_merge_review().await? {
2242                self.run_land().await?;
2243            }
2244            self.settle_questions();
2245            return Ok(());
2246        }
2247        // Publication already passed review and gate. Resume only that node:
2248        // syncing to a newer base here could change the verified commit.
2249        if self.state.pr_publication_pending {
2250            self.merge().await?;
2251            if self.resource_halt()? {
2252                return Ok(());
2253            }
2254            self.state.save()?;
2255            self.settle_questions();
2256            return Ok(());
2257        }
2258        // A run that already lost its quorum never resumes into the verdict
2259        // machinery: `deliberate` and `vote` would otherwise clobber the
2260        // stalled marker back to Voting and the run would keep going past a
2261        // verdict that is no longer trustworthy. Everything already recorded is
2262        // kept, so the run stays resumable (or foldable) for a human to pick up.
2263        //
2264        // On --resume the run gets one chance to repair itself: the seats a
2265        // rate limit took out are re-asked. If their quota has since reset and
2266        // the quorum is restored, the run picks up and finishes; otherwise it
2267        // stays stale and still-resumable for a later retry. If it does not
2268        // recover, the returned status stays `Stalled` and nothing was
2269        // clobbered (the recovery only mutates entries for the lost seats).
2270        if self.state.status == RunStatus::Stalled {
2271            if self.recover_stall().await? {
2272                self.finish_after_tally().await?;
2273            } else {
2274                // Still below quorum: persist the marker and stay resumable.
2275                self.state.save()?;
2276            }
2277            return Ok(());
2278        }
2279        // A run parked inside `land` - watching CI, mid fix-round, or
2280        // waiting on the owner's merge approval - resumes directly into it,
2281        // never back through `prep`. Everything before `merge` already
2282        // concluded; that is the only way `status` reaches `Landing` in the
2283        // first place. Re-walking `review_loop` first would also be actively
2284        // wrong: its own status recomputation (see its doc) treats any
2285        // clean round as reason to set `status` to `Gating`, which would
2286        // clobber this marker before `merge` ever ran, and this run would
2287        // never find its way back into `land` at all.
2288        if self.state.status == RunStatus::Landing
2289            || crate::handover::landing_checkpoint(&self.state)
2290        {
2291            self.state.land_sync_pending = true;
2292            self.state.save()?;
2293            self.run_land().await?;
2294            // `run_land` may have settled the run right here - CI came back
2295            // green and the PR merged, say - without ever passing back
2296            // through `merge`'s own trailing call. Whatever it left `status`
2297            // as is what this has to read.
2298            self.settle_questions();
2299            return Ok(());
2300        }
2301        // A run parked at `merge` on the owner's word about a withheld PR text
2302        // resumes straight into `merge`. Re-walking the tail would sync to the
2303        // base again (possibly rebasing, possibly spending the fixer) after the
2304        // gate had passed, and then push a tree nobody reviewed or gated.
2305        if self.state.github_text.is_some()
2306            && self.state.merge.is_none()
2307            && self.state.status == RunStatus::Gating
2308        {
2309            self.merge().await?;
2310            if self.resource_halt()? {
2311                return Ok(());
2312            }
2313            self.state.save()?;
2314            return Ok(());
2315        }
2316        // A resource stop left the reserved synchronization unfinished. Reconcile
2317        // its exact HEAD and base before starting any earlier graph stage.
2318        if self.state.pending_base_operation().is_some() {
2319            return self.finish_after_tally().await;
2320        }
2321        if let Err(e) = self.prep().await {
2322            if e.is::<crate::repo_lock::ResourceBlocked>() {
2323                return Err(e);
2324            }
2325            self.state.status = RunStatus::Blocked;
2326            self.state
2327                .prep_failure
2328                .get_or_insert_with(|| format!("{e:#}"));
2329            self.state
2330                .event("prep", format!("preparation stopped: {e:#}"));
2331            self.state.save()?;
2332            return Err(e);
2333        }
2334        if self.park_here()? {
2335            return Ok(());
2336        }
2337        self.advise().await?;
2338        if self.park_here()? {
2339            return Ok(());
2340        }
2341        self.implement().await?;
2342        if self.park_here()? {
2343            return Ok(());
2344        }
2345        // `after_implement` already saved the state and settled any open
2346        // questions when it set this; nothing later in the graph has
2347        // anything to judge.
2348        if self.state.status == RunStatus::VerifiedNoop {
2349            return Ok(());
2350        }
2351        self.judge().await?;
2352        if self.park_here()? {
2353            return Ok(());
2354        }
2355        self.deliberate().await?;
2356        if self.park_here()? {
2357            return Ok(());
2358        }
2359        self.vote().await?;
2360        if self.park_here()? {
2361            return Ok(());
2362        }
2363        self.tally()?;
2364        // A verdict that lost its quorum is not trustworthy: do not review,
2365        // gate, or merge on it. Everything already done is kept, so the run
2366        // stays resumable (or foldable); the human can replace the agent that
2367        // ran out of quota and pick it up.
2368        if self.state.status == RunStatus::Stalled {
2369            // Persist the stalled marker now — the normal end-of-execute save
2370            // below is below this early return, and without it a resumed run
2371            // would reload a pre-tally status and keep going.
2372            self.state.save()?;
2373            return Ok(());
2374        }
2375        self.finish_after_tally().await?;
2376        Ok(())
2377    }
2378
2379    /// A wave could not start its agents because a shared resource stayed busy
2380    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2381    /// resumable. Unstarted seats have no result; completed peers retain
2382    /// their saved candidate state.
2383    fn stop_for_resource(&mut self) -> Result<()> {
2384        // Resource acquisition observes cancellation inside a node. Complete
2385        // the same durable park as every other node boundary before returning.
2386        if self.pause.parked() || self.interrupt.parked() {
2387            self.park_here()?;
2388            return Ok(());
2389        }
2390        if self.state.resource_block.is_some() {
2391            self.state.status = RunStatus::Blocked;
2392        }
2393        self.state.save()
2394    }
2395
2396    /// Stop walking the graph if a node ended on a resource block.
2397    fn resource_halt(&mut self) -> Result<bool> {
2398        if self.state.resource_block.is_none() {
2399            return Ok(false);
2400        }
2401        self.stop_for_resource()?;
2402        Ok(true)
2403    }
2404
2405    /// Park here if asked to, recording it in the run's own timeline.
2406    ///
2407    /// Returns whether the caller should stop walking the graph. The state is
2408    /// saved either way by the node that just finished; this adds the event so
2409    /// the operator's card says why a run that is neither finished nor moving
2410    /// is sitting where it is.
2411    fn park_here(&mut self) -> Result<bool> {
2412        let parking = self.pause.parked() || self.interrupt.parked();
2413        if !parking && self.state.resource_block.is_some() {
2414            self.stop_for_resource()?;
2415            return Ok(true);
2416        }
2417        // Either handle asking is enough - see `Pause`'s own doc for why
2418        // they are never the same one. `interrupt` is checked second so a
2419        // reason it carries is preferred in the message below over a plain
2420        // shutdown park racing it at the same boundary.
2421        if !self.pause.parked() && !self.interrupt.parked() {
2422            return Ok(false);
2423        }
2424        if self.state.parked {
2425            return Ok(true);
2426        }
2427        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2428        if let Some(block) = &mut self.state.resource_block
2429            && matches!(
2430                block.cause,
2431                crate::run::ResourceBlockCause::Cancelled { .. }
2432            )
2433        {
2434            block.cause = crate::run::ResourceBlockCause::Cancelled {
2435                park: cause.clone(),
2436            };
2437        }
2438        let why = match cause.as_ref().map(ParkCause::label) {
2439            Some(reason) => format!(
2440                "parked after `{}` ({reason}) — resume to carry on from here",
2441                self.state.status.as_str()
2442            ),
2443            None => format!(
2444                "parked after `{}` — resume to carry on from here",
2445                self.state.status.as_str()
2446            ),
2447        };
2448        self.state.event("park", why);
2449        self.state
2450            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2451        self.state.parked = true;
2452        self.state.save()?;
2453        Ok(true)
2454    }
2455
2456    /// Only a new explicit operator approval may retry failed preparation.
2457    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2458        if self.state.prep_failure.is_none() {
2459            return Ok(());
2460        }
2461        let failed_at = self
2462            .state
2463            .events
2464            .iter()
2465            .rev()
2466            .find(|event| event.node == "prep")
2467            .map_or(self.state.updated_at, |event| event.at);
2468        anyhow::ensure!(
2469            approval_at > failed_at,
2470            "preparation retry requires a new explicit release after the failure"
2471        );
2472        self.state.prep_failure = None;
2473        self.state.prep_complete = Some(false);
2474        self.state
2475            .event("prep-retry", "operator approved retry of preparation");
2476        Ok(())
2477    }
2478
2479    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2480    pub fn on_pause(&mut self, pause: Pause) {
2481        self.pause = pause;
2482    }
2483
2484    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2485    /// scheduler asking this one run - and no other - to park so a task
2486    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2487    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2488    /// handle.
2489    pub fn watch_interrupt(&mut self, pause: Pause) {
2490        self.interrupt = pause;
2491    }
2492
2493    /// Abandon this run's own open questions, once `status` has actually
2494    /// settled rather than merely paused.
2495    ///
2496    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2497    /// either back up with the candidates, the review round and the seat
2498    /// sessions already on disk, so a question an implementer asked mid-round
2499    /// may still get a real answer read by a real resume. Only the statuses
2500    /// `resumable` excludes are actually final: the run merged, it reached
2501    /// `Ready` with nothing left to do, it failed outright with no
2502    /// established point to continue from, or every candidate agreed, with
2503    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2504    /// every one of those the seat that asked is gone for good, exactly like
2505    /// the run being deleted under `magi run rm` - so the same cleanup
2506    /// applies, worded for what actually happened instead of "the run was
2507    /// deleted".
2508    ///
2509    /// Best-effort and silent on success: called from every place `status`
2510    /// can land on one of those three, including ones a resumed run revisits,
2511    /// so it must cost nothing when there was nothing open to begin with.
2512    fn settle_questions(&mut self) {
2513        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2514            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2515        }
2516    }
2517
2518    /// The tail of the graph after a trustworthy tally: fold losers, review,
2519    /// gate, merge, and persist.
2520    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2521        Box::pin(self.finish_after_tally_inner())
2522    }
2523
2524    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2525        // Before the losers are folded: their branches are what the graft
2526        // reads from.
2527        self.graft().await?;
2528        if self.resource_halt()? {
2529            return Ok(());
2530        }
2531        self.fold_losers().await?;
2532        // Before review starts, and again right before the gate: a run's
2533        // review rounds can themselves take long enough for the base to move
2534        // a second time, and the gate is the one node whose "green" gets
2535        // acted on.
2536        self.sync_to_base().await?;
2537        if self.hold_base_sync().await? || self.resource_halt()? {
2538            return Ok(());
2539        }
2540        if self.state.status == RunStatus::AlreadyInBase {
2541            return Ok(());
2542        }
2543        self.review_loop().await?;
2544        if self.resource_halt()? {
2545            return Ok(());
2546        }
2547        self.sync_to_base().await?;
2548        if self.hold_base_sync().await? || self.resource_halt()? {
2549            return Ok(());
2550        }
2551        if self.state.status == RunStatus::AlreadyInBase {
2552            return Ok(());
2553        }
2554        self.gate().await?;
2555        self.merge().await?;
2556        if self.resource_halt()? {
2557            return Ok(());
2558        }
2559        self.state.save()?;
2560        Ok(())
2561    }
2562
2563    // ---------------------------------------------------------------- prep
2564
2565    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2566    /// run with the step and its output in the event; it is never swallowed.
2567    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2568    /// resume starts over instead of finding candidates and missing seats.
2569    async fn setup_seat_worktree(
2570        &mut self,
2571        repo: &Path,
2572        wt: &Path,
2573        in_prep: bool,
2574        coordination: Option<&crate::repo_lock::SeatLease>,
2575    ) -> Result<()> {
2576        let result = match ensure_setup_config(&mut self.state, repo).await {
2577            Ok(()) => {
2578                worktree_setup::prepare_with(
2579                    &self.state.config,
2580                    repo,
2581                    wt,
2582                    crate::build_target::Coordination::Held(coordination),
2583                )
2584                .await
2585            }
2586            Err(e) => Err(e),
2587        };
2588        if let Err(e) = result {
2589            git::worktree_remove_clean(repo, wt).await.ok();
2590            if in_prep {
2591                self.rollback_prep(repo).await;
2592            }
2593            self.state.status = RunStatus::Blocked;
2594            self.state.event(
2595                "setup",
2596                format!("worktree setup failed in {}: {e:#}", wt.display()),
2597            );
2598            self.state.save()?;
2599            return Err(e);
2600        }
2601        Ok(())
2602    }
2603
2604    /// Undo everything `prep` created, so a resume re-runs it whole.
2605    async fn rollback_prep(&mut self, repo: &Path) {
2606        let root = self.state.worktree_root();
2607        for c in std::mem::take(&mut self.state.candidates) {
2608            if matches!(
2609                git::worktree_remove_clean(repo, &c.worktree).await,
2610                Ok(true)
2611            ) {
2612                git::branch_delete(repo, &c.branch).await.ok();
2613            } else {
2614                self.state.candidates.push(c);
2615            }
2616        }
2617        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2618        for j in 1..=seats {
2619            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2620                .await
2621                .ok();
2622        }
2623        for k in 1..=self.state.config.graph.advisors {
2624            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2625                .await
2626                .ok();
2627        }
2628    }
2629
2630    async fn prep(&mut self) -> Result<()> {
2631        if let Some(reason) = &self.state.prep_failure {
2632            bail!(
2633                "candidate preparation previously failed: {reason}; correct the source before retrying"
2634            );
2635        }
2636        if self
2637            .state
2638            .prep_complete
2639            .unwrap_or(!self.state.candidates.is_empty())
2640        {
2641            return Ok(());
2642        }
2643        let repo = self.state.repo.clone();
2644        // Includes rollback, config, refs, checkout creation and setup. No
2645        // repository mutation may precede the real shared lock acquisition.
2646        let _coordination = self.coordinate(&repo).await?;
2647        let base = self.state.base_commit.clone();
2648        let plan = self.state.sources.plan(&repo, &base).await?;
2649        self.rollback_prep(&repo).await;
2650        if !self.state.candidates.is_empty() {
2651            bail!(
2652                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2653            );
2654        }
2655        self.state.prep_complete = Some(false);
2656        self.state.status = RunStatus::Prep;
2657        self.state.save()?;
2658        let repo = self.state.repo.clone();
2659        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2660        let root = self.state.worktree_root();
2661        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2662
2663        // The hook is the write-time half of the blindness contract; the
2664        // presentation filter in `blind` is the half that cannot be bypassed.
2665        let hooks_dir = self.state.dir().join("hooks");
2666        if self.state.config.blind.commit_msg_hook {
2667            std::fs::create_dir_all(&hooks_dir)
2668                .with_context(|| format!("create {}", hooks_dir.display()))?;
2669            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2670            let path = hooks_dir.join("commit-msg");
2671            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2672            make_executable(&path)?;
2673            // Ref-counted rather than a plain idempotent set: with more than
2674            // one run able to be in flight in the same repository at once
2675            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2676            // true?" check cannot tell "another run of mine still needs
2677            // this" from "nobody does", and the run that happens to finish
2678            // first would disable the hook out from under a sibling still
2679            // relying on it.
2680            git::acquire_worktree_config(&repo).await?;
2681            self.state.enabled_worktree_config = true;
2682        }
2683
2684        // `[worktree] setup` hides its products per worktree, which needs the
2685        // same per-worktree config the hook does. Held until fold, like it.
2686        ensure_setup_config(&mut self.state, &repo).await?;
2687
2688        for (index, (spec, label)) in self
2689            .roles
2690            .implementers
2691            .clone()
2692            .into_iter()
2693            .zip(labels)
2694            .enumerate()
2695        {
2696            let branch = self.state.branch_for(label);
2697            let worktree = root.join(format!("cand-{label}"));
2698            // Persist intent before Git can leave a partially created tree.
2699            // Candidate registration follows setup, so it cannot inventory
2700            // crashes or refusals during creation itself.
2701            self.state.event(
2702                "prep-intent",
2703                serde_json::json!({
2704                    "branch": branch,
2705                    "worktree": worktree,
2706                    "start": start,
2707                    "picks": plan.picks,
2708                })
2709                .to_string(),
2710            );
2711            self.state.save()?;
2712            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2713            if self.state.config.blind.commit_msg_hook {
2714                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2715            }
2716            git::local_exclude(&worktree, "/.magi/").await?;
2717            if let Err(e) = worktree_setup::prepare_with(
2718                &self.state.config,
2719                &repo,
2720                &worktree,
2721                crate::build_target::Coordination::Held(_coordination.as_ref()),
2722            )
2723            .await
2724            {
2725                // Nothing of this prep may survive: a resume must start over,
2726                // not find half the candidates and skip the rest.
2727                git::worktree_remove_clean(&repo, &worktree).await.ok();
2728                git::branch_delete(&repo, &branch).await.ok();
2729                self.rollback_prep(&repo).await;
2730                self.state.status = RunStatus::Blocked;
2731                self.state
2732                    .event("prep", format!("worktree setup failed: {e:#}"));
2733                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2734                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2735                }
2736                self.state.save()?;
2737                return Err(e);
2738            }
2739            self.state.candidates.push(Candidate {
2740                index,
2741                label,
2742                agent: spec.id.clone(),
2743                branch,
2744                worktree,
2745                summary: String::new(),
2746                stat: String::new(),
2747                files: 0,
2748                commits: 0,
2749                empty: false,
2750                failed: None,
2751                verified_noop: None,
2752                duration_ms: 0,
2753                folded: false,
2754            });
2755            self.state.save()?;
2756            for pick in &plan.picks {
2757                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2758                {
2759                    self.state.status = RunStatus::Blocked;
2760                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2761                    self.state
2762                        .event("prep", format!("cannot apply referenced commit: {e}"));
2763                    self.state.save()?;
2764                    return Err(e);
2765                }
2766            }
2767        }
2768
2769        for j in 1..=self.roles.judges.len() {
2770            let wt = root.join(format!("judge-{j}"));
2771            if !wt.exists() {
2772                git::worktree_add_detached(&repo, &wt, &base).await?;
2773                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2774                    .await?;
2775            }
2776        }
2777
2778        // Disposable, detached checkouts for the design-deliberation stage's
2779        // advisor seats — the same shape as the judges' above, at the same
2780        // base commit, since advisors also only ever read. Sized off the
2781        // configured count directly rather than a resolved roster: unlike
2782        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2783        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2784        // `prep` has no `ResolvedRoles` field to read a count from here.
2785        if self.state.config.graph.advise {
2786            for k in 1..=self.state.config.graph.advisors {
2787                let wt = root.join(format!("advisor-{k}"));
2788                if !wt.exists() {
2789                    git::worktree_add_detached(&repo, &wt, &base).await?;
2790                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2791                        .await?;
2792                }
2793            }
2794        }
2795
2796        // A judge cannot tell it is looking at its own patch — the seats keep
2797        // separate conversations — but a panel that shares agents with the
2798        // field is less independent than it looks, and that is worth saying out
2799        // loud once per run rather than leaving it in the config.
2800        let authors: Vec<&str> = self
2801            .roles
2802            .implementers
2803            .iter()
2804            .map(|a| a.id.as_str())
2805            .collect();
2806        let overlap: Vec<String> = self
2807            .roles
2808            .judges
2809            .iter()
2810            .enumerate()
2811            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2812            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2813            .collect();
2814        if !overlap.is_empty() {
2815            let note = format!(
2816                "{} also authored a candidate; blind, but the panel is less \
2817                 independent than {} distinct agents would be",
2818                overlap.join(", "),
2819                self.roles.judges.len()
2820            );
2821            self.state.event("prep", note);
2822        }
2823
2824        self.state.event(
2825            "prep",
2826            format!(
2827                "{} candidates, {} judges, base {} ({})",
2828                self.state.candidates.len(),
2829                self.roles.judges.len(),
2830                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2831                self.state.base_branch
2832            ),
2833        );
2834        self.state.prep_complete = Some(true);
2835        self.state.status = RunStatus::Implementing;
2836        self.state.save()?;
2837        Ok(())
2838    }
2839
2840    // -------------------------------------------------------------- advise
2841
2842    /// The design-deliberation stage: independent, read-only advisor seats
2843    /// each sketch a design before any implementer touches the repository,
2844    /// and (when at least one produced a usable proposal) a synthesis seat
2845    /// blends them into a brief `implement` carries in every candidate's
2846    /// prompt.
2847    ///
2848    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2849    /// advisors` is the proposal count. Everything here is best-effort and
2850    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2851    /// that cannot reach quota, or a synthesis seat that produced nothing
2852    /// usable all leave `implement` exactly as it was before this stage
2853    /// existed — the task instruction alone — rather than failing the whole
2854    /// competition over an enrichment stage. Every outcome is still recorded
2855    /// as an event, so a run that got nothing from this stage says why.
2856    ///
2857    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2858    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2859    /// resumed run whose stage failed would re-run it, and re-spend the
2860    /// agent calls, on every reentry before `implement`.
2861    ///
2862    /// Also skipped once any candidate shows implementation progress — the
2863    /// exact predicate `implement` itself uses to decide a candidate is no
2864    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2865    /// is not enough: a run created by an older binary that predates this
2866    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2867    /// an already-`Implementing`-or-later run under this build would
2868    /// otherwise walk straight back through `prep` (a no-op once candidates
2869    /// exist) into this node and spawn every advisor seat against worktrees
2870    /// `prep` never recreated — after implementation has already started,
2871    /// which is exactly the invariant this stage exists to guarantee.
2872    async fn advise(&mut self) -> Result<()> {
2873        let implement_untouched = self
2874            .state
2875            .candidates
2876            .iter()
2877            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2878        if !self.state.config.graph.advise || self.state.advise_attempted {
2879            return Ok(());
2880        }
2881        if !implement_untouched {
2882            self.state.event(
2883                "advise",
2884                "skipping the design-deliberation stage: at least one \
2885                 candidate already shows implementation progress, so this \
2886                 run is past the point the stage exists to run before"
2887                    .to_owned(),
2888            );
2889            self.state.advise_attempted = true;
2890            self.state.save()?;
2891            return Ok(());
2892        }
2893        let run_id = self.state.id.clone();
2894        let prompts = self.state.config.prompts.clone();
2895        let instruction = self.state.instruction.clone();
2896        let language = self.state.config.graph.language.clone();
2897        let root = self.state.worktree_root();
2898        let n = self.state.config.graph.advisors;
2899        let where_recorded = self.state.dir().join("run.json");
2900
2901        let seats = match self.state.config.advisors() {
2902            Ok(seats) if !seats.is_empty() => seats,
2903            Ok(_) => {
2904                self.state.event(
2905                    "advise",
2906                    format!(
2907                        "[graph] advisors is 0; skipping the design-deliberation \
2908                         stage and continuing without a synthesis brief (see {})",
2909                        where_recorded.display()
2910                    ),
2911                );
2912                self.state.advise_attempted = true;
2913                self.state.save()?;
2914                return Ok(());
2915            }
2916            Err(e) => {
2917                self.state.event(
2918                    "advise",
2919                    format!(
2920                        "could not resolve advisor seats ({e:#}); continuing \
2921                         without a design-deliberation brief (see {})",
2922                        where_recorded.display()
2923                    ),
2924                );
2925                self.state.advise_attempted = true;
2926                self.state.save()?;
2927                return Ok(());
2928            }
2929        };
2930
2931        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2932        let artifacts = agent::artifacts_dir(&self.state.dir());
2933        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2934
2935        let mut jobs = Vec::new();
2936        for (i, spec) in seats.iter().cloned().enumerate() {
2937            let seat_key = format!("advisor-{}", i + 1);
2938            let seat = self.seat(&seat_key, &spec.id);
2939            jobs.push(SeatJob {
2940                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2941                spec,
2942                seat,
2943                cwd: worktrees[i % worktrees.len()].clone(),
2944                timeout,
2945                allow_write: false,
2946                sessions: false,
2947                artifacts: artifacts.clone(),
2948                stem: seat_key,
2949                handover: None,
2950            });
2951        }
2952
2953        self.state.event(
2954            "advise",
2955            format!(
2956                "{} advisor seat(s) sketching a design in parallel",
2957                jobs.len()
2958            ),
2959        );
2960        let mut quota_losses = Vec::new();
2961        let cache = self.state.config.cache_dir();
2962        let ctx = WaveCtx {
2963            carry_seats: false,
2964            pauses: Some((&self.pause, &self.interrupt)),
2965            run: &run_id,
2966            node: "advise",
2967            prompts: &prompts,
2968            cache: cache.as_deref(),
2969            round: None,
2970        };
2971        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2972        let results = ask_json_wave::<Proposal>(
2973            jobs,
2974            Arc::clone(&self.sem),
2975            self.state.config.graph.retries,
2976            &advisor_roster,
2977            &ctx,
2978            &mut quota_losses,
2979            &mut self.state,
2980            &|p: &Proposal| p.validate(),
2981        )
2982        .await;
2983        if self.state.resource_block.is_some() {
2984            return self.stop_for_resource();
2985        }
2986        self.state.quota.extend(quota_losses);
2987
2988        let mut records = Vec::with_capacity(results.len());
2989        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2990            let agent_id = seat.agent.clone();
2991            self.state.seats.insert(seat.key.clone(), seat);
2992            match res {
2993                Ok((proposal, out)) => {
2994                    self.state
2995                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2996                    records.push(advise::AdvisorRecord::proposed(
2997                        i + 1,
2998                        agent_id,
2999                        proposal,
3000                        out.duration_ms,
3001                    ));
3002                }
3003                Err(e) => {
3004                    self.state.event(
3005                        "advise",
3006                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3007                    );
3008                    records.push(advise::AdvisorRecord::failed(
3009                        i + 1,
3010                        agent_id,
3011                        e.to_string(),
3012                    ));
3013                }
3014            }
3015        }
3016
3017        let mut advice = advise::Advice {
3018            records,
3019            synthesis: None,
3020        };
3021        if advice.proposals().is_empty() {
3022            self.state.event(
3023                "advise",
3024                "no advisor produced a usable proposal; continuing without a \
3025                 synthesis brief"
3026                    .to_owned(),
3027            );
3028        } else {
3029            match self
3030                .synthesize_brief(
3031                    &advice,
3032                    &instruction,
3033                    &language,
3034                    &worktrees[0],
3035                    &artifacts,
3036                    &run_id,
3037                    &prompts,
3038                    cache.as_deref(),
3039                )
3040                .await
3041            {
3042                Ok(Some(text)) => {
3043                    self.state.event(
3044                        "advise",
3045                        "synthesized a design brief for the implementer".to_owned(),
3046                    );
3047                    advice.synthesis = Some(text);
3048                }
3049                Ok(None) => {
3050                    self.state.event(
3051                        "advise",
3052                        "the synthesis seat produced nothing usable; continuing \
3053                         without a design brief"
3054                            .to_owned(),
3055                    );
3056                }
3057                Err(e) => {
3058                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3059                        return Err(e);
3060                    }
3061                    self.state.event(
3062                        "advise",
3063                        format!("could not synthesize a design brief: {e:#}"),
3064                    );
3065                }
3066            }
3067        }
3068        advise::apply_reflection(&mut advice);
3069
3070        self.state.advice = Some(advice);
3071        self.state.advise_attempted = true;
3072        self.state.save()?;
3073        Ok(())
3074    }
3075
3076    /// The synthesis seat: reads every advisor's proposal and blends them
3077    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3078    /// out of [`Runner::advise`] only for readability — it is not called
3079    /// anywhere else.
3080    ///
3081    /// Picked the same way [`crate::talk`]'s standing conversation and
3082    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3083    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3084    /// order (a claude seat, else the first runnable agent in roster order)
3085    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3086    /// in [`crate::config`] for why a dedicated field exists here at all.
3087    #[allow(clippy::too_many_arguments)]
3088    async fn synthesize_brief(
3089        &mut self,
3090        advice: &advise::Advice,
3091        instruction: &str,
3092        language: &str,
3093        cwd: &Path,
3094        artifacts: &Path,
3095        run_id: &str,
3096        prompts: &Prompts,
3097        cache: Option<&Path>,
3098    ) -> Result<Option<String>> {
3099        let chain = agent::pick_chain(
3100            &self.state.config.agents,
3101            self.state.config.roles.synthesizer.as_ref(),
3102            &agent::installed,
3103            "synthesizer",
3104        )?;
3105        let proposals = advice.proposals();
3106        let mut prompt = prompt::with_overlay(
3107            prompt::synthesize_brief(instruction, &proposals, language),
3108            prompts.overlay("advise"),
3109        );
3110        if cache.is_some() {
3111            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3112            // below — see `prompt::build_cache_note`'s doc for why telling a
3113            // read-only seat to build through the shared cache is exactly how
3114            // a sandbox's write refusal gets misread as a defect.
3115            prompt.push('\n');
3116            prompt.push_str(&prompt::build_cache_note("advise", false));
3117        }
3118        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3119        // Each id is tried once, in order; a quota hit, error or unusable
3120        // answer moves to the next. The seat is single-turn (`sessions:
3121        // false`) and the prompt is the whole context, so a fallback agent
3122        // needs nothing carried over.
3123        let mut last = None;
3124        for (n, spec) in chain.iter().enumerate() {
3125            if n > 0 {
3126                self.state
3127                    .event("advise", format!("synthesis falling back to {}", spec.id));
3128            }
3129            let mut seat = self.seat("advise-synthesis", &spec.id);
3130            let wait = self.repository_wait();
3131            let outcome = wait
3132                .scope(agent::invoke(
3133                    spec,
3134                    &mut seat,
3135                    &Invocation {
3136                        coordination: self.state.config.coordination.as_ref(),
3137                        fetched_base: None,
3138                        cwd,
3139                        prompt: &prompt,
3140                        timeout,
3141                        allow_write: false,
3142                        sessions: false,
3143                        artifacts,
3144                        stem: &if n == 0 {
3145                            "advise-synthesis".to_owned()
3146                        } else {
3147                            format!("advise-synthesis-{}", spec.id)
3148                        },
3149                        run: run_id,
3150                        node: "advise",
3151                        cache_dir: None,
3152                        attachments: &[],
3153                        writable: &[],
3154                    },
3155                ))
3156                .await;
3157            if outcome.is_ok() {
3158                self.state.seats.insert(seat.key.clone(), seat);
3159            }
3160            let advance = agent::chain_advances(&outcome);
3161            last = Some(outcome);
3162            if !advance {
3163                break;
3164            }
3165        }
3166        // Exhausted: the last attempt's result is what a single failed seat
3167        // would have produced.
3168        let out = last.expect("a chain holds at least one agent")?;
3169        if !out.usable() {
3170            return Ok(None);
3171        }
3172        let text =
3173            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3174        Ok((!text.trim().is_empty()).then_some(text))
3175    }
3176
3177    // ----------------------------------------------------------- implement
3178
3179    async fn implement(&mut self) -> Result<()> {
3180        self.persist_candidates().await?;
3181        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3182        // agent files with `magi task add` name the run that paid for it. The
3183        // prompt overlay is cloned alongside it because the waves borrow it
3184        // while `self` is mutably borrowed by the node's own bookkeeping.
3185        let run_id = self.state.id.clone();
3186        let prompts = self.state.config.prompts.clone();
3187        let todo: Vec<usize> = self
3188            .state
3189            .candidates
3190            .iter()
3191            .enumerate()
3192            .filter(|(_, c)| {
3193                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3194                    && c.failed.is_none()
3195                    && !c.empty
3196            })
3197            .map(|(i, _)| i)
3198            .collect();
3199        if todo.is_empty() {
3200            return self.after_implement();
3201        }
3202        self.state.status = RunStatus::Implementing;
3203
3204        let language = self.state.config.graph.language.clone();
3205        let github_language = self.state.config.graph.github_language.clone();
3206        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3207        let sessions = self.state.config.graph.sessions;
3208        let artifacts = agent::artifacts_dir(&self.state.dir());
3209        // The design-deliberation stage's blended brief, when `advise` found
3210        // one — carried into every implementer's prompt the same way
3211        // regardless of which candidate it is.
3212        let brief = self
3213            .state
3214            .advice
3215            .as_ref()
3216            .and_then(|a| a.synthesis.as_deref())
3217            .map(str::to_owned);
3218        let attachments = self.state.attachments.clone();
3219
3220        let mut jobs = Vec::new();
3221        for &i in &todo {
3222            let (index, label, worktree) = {
3223                let c = &self.state.candidates[i];
3224                (c.index, c.label, c.worktree.clone())
3225            };
3226            let spec = self.roles.implementers[index].clone();
3227            let seat_key = format!("impl-{label}");
3228            let seat = self.seat(&seat_key, &spec.id);
3229            let instruction = seeded_instruction(&self.state);
3230            jobs.push(SeatJob {
3231                spec,
3232                seat,
3233                prompt: prompt::implement_in(
3234                    &instruction,
3235                    &worktree.to_string_lossy(),
3236                    &language,
3237                    &github_language,
3238                    brief.as_deref(),
3239                    &attachments,
3240                ),
3241                cwd: worktree,
3242                timeout,
3243                allow_write: true,
3244                sessions,
3245                artifacts: artifacts.clone(),
3246                stem: format!("impl-{label}"),
3247                handover: None,
3248            });
3249        }
3250
3251        self.state.event(
3252            "implement",
3253            format!("{} candidates in parallel", jobs.len()),
3254        );
3255        // Kept so a seat whose CLI hung up can be asked again from the same
3256        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3257        // can update a seat's own entry once a fallback agent takes it over —
3258        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3259        // whichever agent actually answered, not the one that quota'd out.
3260        let mut sent = jobs.clone();
3261        let cache = self.state.config.cache_dir();
3262        let ctx = WaveCtx {
3263            carry_seats: false,
3264            pauses: Some((&self.pause, &self.interrupt)),
3265            run: &run_id,
3266            node: "implement",
3267            prompts: &prompts,
3268            cache: cache.as_deref(),
3269            round: None,
3270        };
3271        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3272        if !wave_blocked(&results) {
3273            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3274                .await;
3275            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3276                .await?;
3277            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3278                .await;
3279        }
3280        // Do not finalize failed candidates when the entire wave needs machine
3281        // recovery: leaving them pending resumes this node with its work intact.
3282        if !results.is_empty()
3283            && results
3284                .iter()
3285                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3286        {
3287            let losses: Vec<_> = results
3288                .iter()
3289                .map(|(_, seat, out)| {
3290                    let AgentOutcome::Quota(o) = out else {
3291                        unreachable!()
3292                    };
3293                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3294                })
3295                .collect();
3296            self.state.quota.extend(losses.clone());
3297            for (_, seat, _) in results {
3298                self.state.seats.insert(seat.key.clone(), seat);
3299            }
3300            for &i in &todo {
3301                let label = self.state.candidates[i].label;
3302                self.state.interrupted_implementations.insert(label);
3303                self.state
3304                    .candidate_preservation
3305                    .insert(label, "machine outage awaiting persistence".into());
3306            }
3307            // Preserve partial edits too, while keeping every interrupted seat
3308            // pending even when its tree already contains an inherited patch.
3309            block_machine_outage(&mut self.state, "implement", &losses);
3310            self.state.save()?;
3311            self.persist_candidates().await?;
3312            for &i in &todo {
3313                self.state
3314                    .interrupted_implementations
3315                    .insert(self.state.candidates[i].label);
3316            }
3317            return self.stop_for_resource();
3318        }
3319        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3320
3321        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3322            && results
3323                .iter()
3324                .any(|(_, _, out)| FailClass::of(out).is_some());
3325        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3326            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3327                // Executed turns interrupted by disk pressure already carry
3328                // a preservation barrier from wave. Admission-only waits do
3329                // not. Keep the interrupted seat's session for recovery too.
3330                if self
3331                    .state
3332                    .candidate_preservation
3333                    .contains_key(&self.state.candidates[i].label)
3334                {
3335                    self.state.seats.insert(seat.key.clone(), seat);
3336                }
3337                continue;
3338            }
3339            let seat_key = seat.key.clone();
3340            // A quota fallback (`resume_seat_handovers`) may have handed this
3341            // seat to a different agent than the one `prep` recorded on the
3342            // candidate; the stats tables and any later fixer-defaults-to-
3343            // winner's-author lookup must credit whoever actually answered —
3344            // unless every fallback also quota'd out, in which case nobody
3345            // actually answered and crediting the last agent tried would
3346            // erase every earlier agent's own quota loss from the stats
3347            // tables instead of just this one seat's.
3348            let agent = seat.agent.clone();
3349            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3350            self.state.seats.insert(seat.key.clone(), seat);
3351            let label = self.state.candidates[i].label;
3352            self.state.interrupted_implementations.remove(&label);
3353
3354            let (summary, duration, failed, verified_claim) = match out {
3355                AgentOutcome::Ok(o) => {
3356                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3357                    let failed = (!o.usable()).then(|| {
3358                        if o.timed_out {
3359                            "agent timed out".to_owned()
3360                        } else {
3361                            format!(
3362                                "agent exited with {}",
3363                                crate::notices::exit_status(o.exit_code)
3364                            )
3365                        }
3366                    });
3367                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3368                    (text, o.duration_ms, failed, verified_claim)
3369                }
3370                // Left un-resumed by `resume_undelivered` (a dirty tree
3371                // already rescues the work, or there was no session left to
3372                // resume into) — reported like the ordinary failure it is,
3373                // never as if `o.text` (the CLI's raw error JSON) were an
3374                // answer.
3375                AgentOutcome::Dropped(o) => {
3376                    let why = o
3377                        .dropped
3378                        .as_ref()
3379                        .map(|d| d.why.as_str())
3380                        .unwrap_or("the CLI ended the stream without delivering its answer");
3381                    (
3382                        String::new(),
3383                        o.duration_ms,
3384                        Some(format!("the CLI dropped the stream ({why})")),
3385                        None,
3386                    )
3387                }
3388                AgentOutcome::Quota(o) => {
3389                    self.state.quota.push(QuotaLoss::from_report(
3390                        seat_key,
3391                        "implement",
3392                        o.quota.as_ref(),
3393                    ));
3394                    (
3395                        String::new(),
3396                        o.duration_ms,
3397                        Some("rate limited (quota); produced no change".to_owned()),
3398                        None,
3399                    )
3400                }
3401                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3402                    (String::new(), 0, Some(e), None)
3403                }
3404            };
3405
3406            // Save every completed turn before any fallible Git operation. A failed
3407            // rescue must not erase the reply or prevent collection of other seats.
3408            let c = &mut self.state.candidates[i];
3409            if !exhausted_the_fallback_chain {
3410                c.agent = agent;
3411            }
3412            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3413            c.duration_ms = duration;
3414            c.failed = failed;
3415            c.verified_noop = verified_claim;
3416            self.state
3417                .candidate_preservation
3418                .insert(label, "awaiting persistence".to_owned());
3419        }
3420        self.state.save()?;
3421        self.persist_candidates().await?;
3422
3423        if resource_blocked {
3424            return self.stop_for_resource();
3425        }
3426        if selected_failed {
3427            self.state.status = RunStatus::Blocked;
3428            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3429            self.state.save()?;
3430            bail!(
3431                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3432            );
3433        }
3434        self.after_implement()
3435    }
3436
3437    /// Retry only persistence after a completed implementation turn.
3438    async fn persist_candidates(&mut self) -> Result<()> {
3439        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3440        for label in labels {
3441            let i = self
3442                .state
3443                .candidates
3444                .iter()
3445                .position(|c| c.label == label)
3446                .context("pending candidate is missing")?;
3447            let c = self.state.candidates[i].clone();
3448            let interrupted = self.state.interrupted_implementations.contains(&label);
3449            let result = async {
3450                let wait = crate::repo_lock::WaitPolicy::new(
3451                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3452                    || false,
3453                );
3454                let _coordination =
3455                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3456                // Best effort evidence requires no index writes. A successful snapshot
3457                // never authorizes removal of a tree whose rescue failed.
3458                if let Err(e) = git::snapshot_uncommitted(
3459                    &c.worktree,
3460                    &self
3461                        .state
3462                        .dir()
3463                        .join("artifacts")
3464                        .join(format!("candidate-{label}-recovery")),
3465                )
3466                .await
3467                {
3468                    self.state.event(
3469                        "preserve",
3470                        format!("candidate {label} snapshot incomplete: {e:#}"),
3471                    );
3472                }
3473                let rescued = git::rescue_commit(
3474                    &c.worktree,
3475                    &format!("magi: candidate {label} (uncommitted work)"),
3476                )
3477                .await?;
3478                self.state.note_withheld("implement", &rescued.withheld);
3479                let base = &self.state.base_commit;
3480                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3481                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3482                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3483                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3484                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3485                if c.empty && commits > 0 && !patch.trim().is_empty()
3486                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3487                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3488                        || self.state.tally.is_some())
3489                {
3490                    // Keep the old classification and pending marker so every
3491                    // retry stops too. Retain decisions as recovery evidence;
3492                    // only a supported recovery operation may replace them.
3493                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3494                }
3495                let c = &mut self.state.candidates[i];
3496                c.commits = commits;
3497                c.stat = stat;
3498                c.files = files;
3499                let no_changes = commits == 0 || patch.trim().is_empty();
3500                c.empty = no_changes && !interrupted;
3501                if interrupted && no_changes {
3502                    c.failed = None;
3503                    c.verified_noop = None;
3504                }
3505                if !c.empty {
3506                    c.failed = None;
3507                    c.verified_noop = None;
3508                }
3509                self.state.event(
3510                    "preserve",
3511                    format!("candidate {label}: {files} files, {commits} commits"),
3512                );
3513                Ok::<_, anyhow::Error>(())
3514            }
3515            .await;
3516            match result {
3517                Ok(()) => {
3518                    self.state.candidate_preservation.remove(&label);
3519                    if !interrupted || self.state.candidates[i].files > 0 {
3520                        self.state.interrupted_implementations.remove(&label);
3521                    }
3522                }
3523                Err(e) => {
3524                    let reason = format!("candidate {label} preservation failed: {e:#}");
3525                    self.state.event("preserve", &reason);
3526                    self.state.candidate_preservation.insert(label, reason);
3527                }
3528            }
3529            if self.state.candidate_preservation.is_empty()
3530                && self.state.status == RunStatus::Blocked
3531                && self.state.candidates.iter().all(|c| c.failed.is_none())
3532            {
3533                // Persist the recovered phase with the cleared pending marker;
3534                // a crash between saves must not turn this into a selected-seat
3535                // failure hold on the next resume.
3536                self.state.status = RunStatus::Implementing;
3537                self.state.event(
3538                    "preserve",
3539                    "candidate persistence recovered; implementation can continue",
3540                );
3541            }
3542            self.state.save()?;
3543        }
3544        if !self.state.candidate_preservation.is_empty() {
3545            self.state.status = RunStatus::Blocked;
3546            self.state.save()?;
3547            bail!(
3548                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3549            );
3550        }
3551        Ok(())
3552    }
3553
3554    /// Ask again, once, for work a CLI did and then failed to hand over.
3555    ///
3556    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3557    /// status with an empty response and a usage report showing output tokens,
3558    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3559    /// seven minutes and 14,267 output tokens that arrived as an empty
3560    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3561    ///
3562    /// Two conditions, and both matter:
3563    ///
3564    /// - **Only when the tree is untouched.** Often the agent has already
3565    ///   written its files and only the closing message was lost; the rescue
3566    ///   commit below picks that up and there is nothing to ask for. Re-asking
3567    ///   then would pay for a second implementation of work already on disk.
3568    /// - **Once.** A CLI that drops one stream can drop the next, and this
3569    ///   node is the most expensive in the graph.
3570    ///
3571    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3572    /// dropped reply still carried its `conversation_id`, so the seat is asked
3573    /// to finish what it was doing rather than sent the whole task again. It
3574    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3575    /// node's - for the same reason a re-ranked judge does: restating finished
3576    /// work is not the work.
3577    ///
3578    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3579    /// same way until it resets, while an abandoned conversation is still
3580    /// there to be picked up.
3581    async fn resume_undelivered(
3582        &mut self,
3583        results: &mut [(usize, SeatState, AgentOutcome)],
3584        sent: &[SeatJob],
3585        prompts: &Prompts,
3586        run_id: &str,
3587    ) {
3588        for (wi, seat, out) in results.iter_mut() {
3589            let Some(dropped) = (match &*out {
3590                AgentOutcome::Dropped(o) => o.dropped.clone(),
3591                _ => None,
3592            }) else {
3593                continue;
3594            };
3595            let Some(job) = sent.get(*wi) else { continue };
3596            // Already on disk? Then only the closing message was lost.
3597            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3598                self.state.event(
3599                    "implement",
3600                    format!(
3601                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3602                         work is in the tree",
3603                        seat.key, dropped.output_tokens, dropped.why
3604                    ),
3605                );
3606                continue;
3607            }
3608            // The re-ask only makes sense as a resume: `resume_after_drop`
3609            // says nothing about the task, trusting the seat to still hold it.
3610            // Without a session to resume — sessions disabled, or this CLI's
3611            // drop shape happened not to carry a session id — that prompt
3612            // would open a brand-new conversation with no context at all,
3613            // which is worse than leaving this as the ordinary failure it
3614            // already is.
3615            if !has_context(&job.spec, seat, job.sessions) {
3616                self.state.event(
3617                    "implement",
3618                    format!(
3619                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3620                         is no session left to resume",
3621                        seat.key, dropped.output_tokens, dropped.why
3622                    ),
3623                );
3624                continue;
3625            }
3626            self.state.event(
3627                "implement",
3628                format!(
3629                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3630                     conversation",
3631                    seat.key, dropped.output_tokens, dropped.why
3632                ),
3633            );
3634            let mut retry = job.clone();
3635            retry.seat = seat.clone();
3636            retry.prompt = prompt::resume_after_drop(&dropped.why);
3637            retry.timeout = retry_budget(job.timeout, true);
3638            retry.stem = format!("{}-resume", job.stem);
3639            let cache = self.state.config.cache_dir();
3640            let ctx = WaveCtx {
3641                carry_seats: false,
3642                pauses: Some((&self.pause, &self.interrupt)),
3643                run: run_id,
3644                node: "implement",
3645                prompts,
3646                cache: cache.as_deref(),
3647                round: None,
3648            };
3649            let (resumed_seat, resumed) =
3650                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3651            *seat = resumed_seat;
3652            *out = resumed;
3653        }
3654    }
3655
3656    /// Fall an implement seat through to the next untried agent in the
3657    /// implementer roster when it lost to quota — or, since the handover was
3658    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3659    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3660    /// quota path itself being unchanged — instead of leaving the
3661    /// seat's loss final the moment one agent's account runs dry.
3662    ///
3663    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3664    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3665    /// truncates to the single slot rotation picked, so a solo task whose one
3666    /// implementer hits quota mid-run used to have nothing else to try. This
3667    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3668    /// unrotated roster — which is the only place the *other* candidates in
3669    /// the machine's roster still exist once `implementers` has been cut down
3670    /// to size.
3671    ///
3672    /// Walks forward from just past the seat's own original position in the
3673    /// roster, never wrapping back to the front: a later candidate slot (say
3674    /// `beta`, the roster's second entry) must fall through to the *next*
3675    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3676    /// almost certainly a different candidate's own agent already — and once
3677    /// the roster's tail is exhausted there is nothing left to fall through
3678    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3679    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3680    /// let this retry that id forever. The loop keeps falling through until
3681    /// an attempt lands something other than `Quota` or the roster's tail
3682    /// runs out of untried ids, at which point the seat is left exactly as
3683    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3684    /// `QuotaLoss` recorded, the candidate failed/empty.
3685    ///
3686    /// `sent` is taken mutably and updated with the fallback agent's spec:
3687    /// `resume_unconfirmed_commands`, which runs after this and also reads
3688    /// `sent`, must see whichever agent actually ended up answering the seat
3689    /// — reading the stale, original spec there would check session
3690    /// eligibility against the wrong CLI and could hand a fallback agent's
3691    /// session id to the agent that just lost the seat to quota.
3692    ///
3693    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3694    /// — `self.seat` only reuses state when the agent id is unchanged, so
3695    /// handing it a different id already gets this for free. Reusing the old
3696    /// seat would resume a different CLI's session as if it were a
3697    /// continuation of this one.
3698    ///
3699    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3700    /// a quota loss cuts an agent off mid-turn, so anything already in the
3701    /// tree is unfinished work, not a completed candidate a re-ask would pay
3702    /// for twice. A dirty tree is rescued into a commit first (the same
3703    /// neutral-identity rescue `implement`'s own outcome loop gives every
3704    /// candidate) so the next agent starts clean.
3705    ///
3706    /// The new agent gets the implementer's full prompt and full
3707    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3708    /// it has no session and no context, and is implementing the task from
3709    /// nothing, unlike a resumed drop which is only restating work already
3710    /// done.
3711    ///
3712    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3713    /// `implement` event, never into `self.state.quota` — that is what
3714    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3715    /// go unspent, and a seat that ultimately recovered on its second or
3716    /// third agent is not the stalled panel that check exists to catch. Only
3717    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3718    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3719    /// outcome loop already has — this helper never pushes to it itself.
3720    async fn resume_seat_handovers(
3721        &mut self,
3722        results: &mut [(usize, SeatState, AgentOutcome)],
3723        sent: &mut [SeatJob],
3724        prompts: &Prompts,
3725        run_id: &str,
3726    ) -> Result<()> {
3727        let instruction = seeded_instruction(&self.state);
3728        let language = self.state.config.graph.language.clone();
3729        let github_language = self.state.config.graph.github_language.clone();
3730        let brief = self
3731            .state
3732            .advice
3733            .as_ref()
3734            .and_then(|a| a.synthesis.as_deref())
3735            .map(str::to_owned);
3736        let attachments = self.state.attachments.clone();
3737        for (wi, seat, out) in results.iter_mut() {
3738            // Who holds the other candidate seats of this wave right now
3739            // (earlier handovers already written back to `sent`).
3740            let others: BTreeSet<String> = sent
3741                .iter()
3742                .enumerate()
3743                .filter(|(j, _)| j != wi)
3744                .map(|(_, j)| j.spec.id.clone())
3745                .collect();
3746            let Some(job) = sent.get_mut(*wi) else {
3747                continue;
3748            };
3749            // Where the seat's own original agent sits in the roster — the
3750            // fallback walk starts just past here, never at the front, so a
3751            // later candidate slot's quota loss does not fall back onto an
3752            // earlier slot's own agent.
3753            let start = self
3754                .roles
3755                .implementer_roster
3756                .iter()
3757                .position(|s| s.id == job.spec.id)
3758                .unwrap_or(0);
3759            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3760            let mut fallback_attempt = 0usize;
3761            let mut prev: Option<FailClass> = None;
3762            while let Some(cur) = FailClass::of(&*out) {
3763                if !should_hand_over(prev.as_ref(), &cur) {
3764                    break;
3765                }
3766                let Some(next) =
3767                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3768                        .cloned()
3769                else {
3770                    break;
3771                };
3772                tried.insert(next.id.clone());
3773                fallback_attempt += 1;
3774
3775                let coordination = self.coordinate(&job.cwd).await?;
3776                if let Ok(r) = git::rescue_commit(
3777                    &job.cwd,
3778                    &format!(
3779                        "magi: candidate {} (uncommitted work before {} fallback)",
3780                        seat.key,
3781                        if cur == FailClass::Quota {
3782                            "quota"
3783                        } else {
3784                            "handover"
3785                        }
3786                    ),
3787                )
3788                .await
3789                {
3790                    self.state.note_withheld("implement", &r.withheld);
3791                }
3792                drop(coordination);
3793
3794                record_handover(
3795                    &mut self.state,
3796                    "implement",
3797                    &seat.key,
3798                    &seat.agent,
3799                    &next.id,
3800                    &cur,
3801                    &fail_reason(&*out),
3802                );
3803                prev = Some(cur.clone());
3804
3805                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3806                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3807                // Kept in sync on `sent` itself, not just the local retry: a
3808                // later helper (`resume_unconfirmed_commands`) reads `sent`
3809                // after this one returns and must see whichever agent is now
3810                // occupying the seat, not the one that just quota'd out —
3811                // otherwise it would judge session/continuation eligibility
3812                // by the wrong CLI and could resend a fallback's session id
3813                // to the agent that lost it the seat in the first place.
3814                job.spec = next.clone();
3815                let mut retry = job.clone();
3816                retry.seat = new_seat;
3817                retry.prompt = prompt::implement_in(
3818                    &instruction,
3819                    &job.cwd.to_string_lossy(),
3820                    &language,
3821                    &github_language,
3822                    brief.as_deref(),
3823                    &attachments,
3824                );
3825                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3826                let cache = self.state.config.cache_dir();
3827                let ctx = WaveCtx {
3828                    carry_seats: false,
3829                    pauses: Some((&self.pause, &self.interrupt)),
3830                    run: run_id,
3831                    node: "implement",
3832                    prompts,
3833                    cache: cache.as_deref(),
3834                    round: None,
3835                };
3836                let (fallback_seat, fallback_out) = run_one(
3837                    retry,
3838                    Arc::clone(&self.sem),
3839                    &ctx,
3840                    &mut self.state,
3841                    fallback_attempt,
3842                )
3843                .await;
3844                *seat = fallback_seat;
3845                *out = fallback_out;
3846            }
3847        }
3848        Ok(())
3849    }
3850
3851    /// Ask an implement seat's own CLI to confirm what it started, once, when
3852    /// its reply reported a command whose completion status it never
3853    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3854    /// that does and does not mean.
3855    ///
3856    /// The completion contract this task asks for, extended to `implement`
3857    /// with the same signal `continue_fix_report` reads for the fixer,
3858    /// rather than a keyword search over the reply or a hard requirement on
3859    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3860    /// a candidate's CLI turn ended cleanly while a test run it had started
3861    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3862    /// named in it at all is untouched by this: `commands` is empty, so
3863    /// there is nothing to be unconfirmed.
3864    ///
3865    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3866    /// this is not about recovering edits that might already be on disk, it
3867    /// is about a result the seat itself never vouched for, which resuming
3868    /// asks for regardless of what the tree already holds. Bounded to one
3869    /// attempt for the same reason `resume_undelivered` is — this is the
3870    /// most expensive node in the graph — and a seat that still cannot
3871    /// confirm on that attempt is left as whatever its (possibly still
3872    /// unconfirmed) reply says; this does not invent a new "failed" reason
3873    /// for a candidate that otherwise produced a real, committed change.
3874    async fn resume_unconfirmed_commands(
3875        &mut self,
3876        results: &mut [(usize, SeatState, AgentOutcome)],
3877        sent: &[SeatJob],
3878        prompts: &Prompts,
3879        run_id: &str,
3880    ) {
3881        for (wi, seat, out) in results.iter_mut() {
3882            let AgentOutcome::Ok(o) = &*out else {
3883                continue;
3884            };
3885            if !has_unconfirmed_command(&o.commands) {
3886                continue;
3887            }
3888            let Some(job) = sent.get(*wi) else { continue };
3889            if !has_context(&job.spec, seat, job.sessions) {
3890                self.state.event(
3891                    "implement",
3892                    format!(
3893                        "{}: the reply named a command whose own CLI never confirmed the exit \
3894                         status of, but there is no session left to resume",
3895                        seat.key
3896                    ),
3897                );
3898                continue;
3899            }
3900            self.state.event(
3901                "implement",
3902                format!(
3903                    "{}: the reply named a command whose own CLI never confirmed the exit \
3904                     status of; resuming the conversation",
3905                    seat.key
3906                ),
3907            );
3908            let mut retry = job.clone();
3909            retry.seat = seat.clone();
3910            retry.prompt = prompt::resume_incomplete(
3911                "a command in your last reply had no confirmed exit status",
3912            );
3913            retry.timeout = retry_budget(job.timeout, true);
3914            retry.stem = format!("{}-confirm", job.stem);
3915            let cache = self.state.config.cache_dir();
3916            let ctx = WaveCtx {
3917                carry_seats: false,
3918                pauses: Some((&self.pause, &self.interrupt)),
3919                run: run_id,
3920                node: "implement",
3921                prompts,
3922                cache: cache.as_deref(),
3923                round: None,
3924            };
3925            let (resumed_seat, resumed) =
3926                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3927            *seat = resumed_seat;
3928            *out = resumed;
3929        }
3930    }
3931
3932    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3933    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3934    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3935    /// that motivated this.
3936    ///
3937    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3938    /// own nudge loop already covers for judge/review/vote seats, and not a
3939    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3940    /// implement seats: here the CLI turn genuinely finished while the node's
3941    /// own work — the fixer's account of what it did — had not. Gated purely
3942    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3943    /// reply, never on any wording in it, so a fixer whose valid, first-try
3944    /// `FixReport` happens to mention having waited on a background test is
3945    /// never resumed — the `Ok(report)` branch at the call site returns
3946    /// before this is ever invoked.
3947    ///
3948    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3949    /// attempt ([`retry_budget`]), nothing attempted once the session is
3950    /// gone, and a quota hit ends the loop immediately rather than retrying a
3951    /// rate limit that fails the same way again.
3952    async fn continue_fix_report(
3953        &mut self,
3954        mut seat: SeatState,
3955        parse_err: String,
3956        job: &SeatJob,
3957        prompts: &Prompts,
3958        run_id: &str,
3959        round: usize,
3960    ) -> (
3961        SeatState,
3962        Option<FixReport>,
3963        Option<String>,
3964        ContinuationRecord,
3965    ) {
3966        let mut last_err = parse_err;
3967        let mut cumulative_wait_ms = 0u64;
3968        let mut attempts = 0usize;
3969        loop {
3970            if !has_context(&job.spec, &seat, job.sessions) {
3971                self.state.event(
3972                    "fix",
3973                    format!(
3974                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3975                         session left to resume into"
3976                    ),
3977                );
3978                let outcome = if attempts == 0 {
3979                    ContinuationOutcome::NoSession
3980                } else {
3981                    ContinuationOutcome::Exhausted
3982                };
3983                return (
3984                    seat,
3985                    None,
3986                    Some(format!("unparsable fix report: {last_err}")),
3987                    ContinuationRecord {
3988                        attempts,
3989                        cumulative_wait_ms,
3990                        outcome,
3991                    },
3992                );
3993            }
3994            if attempts >= MAX_FIX_CONTINUATIONS {
3995                self.state.event(
3996                    "fix",
3997                    format!(
3998                        "round {round}: fixer's reply still had no adoption report after \
3999                         {attempts} continuation(s) ({last_err}); giving up"
4000                    ),
4001                );
4002                return (
4003                    seat,
4004                    None,
4005                    Some(format!(
4006                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4007                    )),
4008                    ContinuationRecord {
4009                        attempts,
4010                        cumulative_wait_ms,
4011                        outcome: ContinuationOutcome::Exhausted,
4012                    },
4013                );
4014            }
4015            attempts += 1;
4016            self.state.event(
4017                "fix",
4018                format!(
4019                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4020                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4021                ),
4022            );
4023            let mut retry = job.clone();
4024            retry.seat = seat.clone();
4025            retry.prompt = prompt::resume_incomplete(&last_err);
4026            retry.timeout = retry_budget(job.timeout, true);
4027            retry.stem = format!("{}-continue{attempts}", job.stem);
4028            let cache = self.state.config.cache_dir();
4029            let ctx = WaveCtx {
4030                carry_seats: false,
4031                pauses: Some((&self.pause, &self.interrupt)),
4032                run: run_id,
4033                node: "fix",
4034                prompts,
4035                cache: cache.as_deref(),
4036                round: Some(round),
4037            };
4038            let (resumed_seat, resumed_out) = run_one(
4039                retry,
4040                Arc::clone(&self.sem),
4041                &ctx,
4042                &mut self.state,
4043                attempts,
4044            )
4045            .await;
4046            seat = resumed_seat;
4047            match resumed_out {
4048                AgentOutcome::Ok(o) => {
4049                    cumulative_wait_ms += o.duration_ms;
4050                    match verdict::extract_json::<FixReport>(&o.text) {
4051                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4052                            self.state.event(
4053                                "fix",
4054                                format!(
4055                                    "round {round}: fixer's adoption report recovered after \
4056                                     {attempts} continuation(s)"
4057                                ),
4058                            );
4059                            return (
4060                                seat,
4061                                Some(report),
4062                                None,
4063                                ContinuationRecord {
4064                                    attempts,
4065                                    cumulative_wait_ms,
4066                                    outcome: ContinuationOutcome::Resumed,
4067                                },
4068                            );
4069                        }
4070                        // The report parsed, but this same reply's own
4071                        // CommandEvidence — the identical record `state.jobs`
4072                        // renders — names a command whose CLI never
4073                        // confirmed an exit status. Read together, that is
4074                        // not a resolved answer: keep nudging rather than
4075                        // accept a report standing next to a command the
4076                        // seat's own CLI cannot vouch for.
4077                        Ok(_) => {
4078                            last_err = "the reply parsed, but it reported a command whose own CLI \
4079                                 never confirmed an exit status"
4080                                .to_owned();
4081                        }
4082                        Err(e) => last_err = e.to_string(),
4083                    }
4084                }
4085                AgentOutcome::Quota(o) => {
4086                    cumulative_wait_ms += o.duration_ms;
4087                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4088                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4089                    self.state.quota.push(loss);
4090                    self.state.event(
4091                        "fix",
4092                        format!(
4093                            "round {round}: continuation rate limited (quota); not retrying now"
4094                        ),
4095                    );
4096                    return (
4097                        seat,
4098                        None,
4099                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4100                        ContinuationRecord {
4101                            attempts,
4102                            cumulative_wait_ms,
4103                            outcome: ContinuationOutcome::QuotaLost,
4104                        },
4105                    );
4106                }
4107                AgentOutcome::Dropped(o) => {
4108                    cumulative_wait_ms += o.duration_ms;
4109                    let why = o
4110                        .dropped
4111                        .as_ref()
4112                        .map(|d| d.why.as_str())
4113                        .unwrap_or("the CLI ended the stream without delivering its answer");
4114                    last_err = format!("the CLI dropped the stream ({why})");
4115                }
4116                AgentOutcome::Failed(e) => last_err = e,
4117                // The continuation was never started; the report stays lost
4118                // and the caller records that, without any handover.
4119                AgentOutcome::ResourceBlocked(e) => {
4120                    return (
4121                        seat,
4122                        None,
4123                        Some(format!("the continuation was not started: {e}")),
4124                        ContinuationRecord {
4125                            attempts: attempts.saturating_sub(1),
4126                            cumulative_wait_ms,
4127                            outcome: ContinuationOutcome::NoSession,
4128                        },
4129                    );
4130                }
4131            }
4132        }
4133    }
4134
4135    fn after_implement(&mut self) -> Result<()> {
4136        if !self.state.candidate_preservation.is_empty() {
4137            bail!("candidate preservation incomplete; judging is unsafe");
4138        }
4139        // Scan every candidate patch once the set is complete.
4140        if self.state.leaks.is_empty() {
4141            let cfg = self.state.config.blind.clone();
4142            let mut leaks = Vec::new();
4143            for c in &self.state.candidates {
4144                let Some(patch) =
4145                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4146                else {
4147                    continue;
4148                };
4149                leaks.extend(blind::scan(
4150                    &format!("candidate {} patch", c.label),
4151                    &patch,
4152                    &cfg.vendor_tokens,
4153                ));
4154            }
4155            if !leaks.is_empty() {
4156                let summary = leaks
4157                    .iter()
4158                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4159                    .collect::<Vec<_>>()
4160                    .join(", ");
4161                match cfg.on_leak {
4162                    LeakPolicy::Fail => {
4163                        self.state.status = RunStatus::Failed;
4164                        self.state
4165                            .event("blind", format!("vendor text in a patch: {summary}"));
4166                        self.state.leaks = leaks;
4167                        self.state.save()?;
4168                        self.settle_questions();
4169                        bail!(
4170                            "blind.on_leak = \"fail\" and vendor text reached a \
4171                             judged patch: {summary}"
4172                        );
4173                    }
4174                    LeakPolicy::Redact => self.state.event(
4175                        "blind",
4176                        format!("redacting vendor text for judging: {summary}"),
4177                    ),
4178                    LeakPolicy::Warn => self.state.event(
4179                        "blind",
4180                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4181                    ),
4182                }
4183                self.state.leaks = leaks;
4184            }
4185        }
4186
4187        if self.state.viable().is_empty() {
4188            if self.state.all_candidates_verified_noop() {
4189                // Every candidate agreed, with evidence the adoption guard
4190                // accepted, that nothing belongs in this worktree. That is
4191                // not the same fact as a candidate that simply failed to
4192                // write anything, and settling it as an ordinary `Failed`
4193                // (see `SCHEMA`'s doc for schema 10) is what let two of
4194                // task 391f's attempts burn a retry each re-discovering the
4195                // same already-landed fix. Terminal either way, so `judge`
4196                // must never run over an empty candidate set — unlike the
4197                // `Failed` branch below this returns `Ok`, not an error:
4198                // nothing here failed.
4199                self.state.status = RunStatus::VerifiedNoop;
4200                self.state.save()?;
4201                self.settle_questions();
4202                return Ok(());
4203            }
4204            self.state.status = RunStatus::Failed;
4205            self.state.save()?;
4206            self.settle_questions();
4207            bail!("no candidate produced a change; nothing to judge");
4208        }
4209        self.state.status = RunStatus::Judging;
4210        self.state.save()?;
4211        Ok(())
4212    }
4213
4214    // --------------------------------------------------------------- judge
4215
4216    async fn judge(&mut self) -> Result<()> {
4217        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4218        // agent files with `magi task add` name the run that paid for it. The
4219        // prompt overlay is cloned alongside it because the waves borrow it
4220        // while `self` is mutably borrowed by the node's own bookkeeping.
4221        let run_id = self.state.id.clone();
4222        let prompts = self.state.config.prompts.clone();
4223        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4224            return Ok(());
4225        }
4226        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4227        if viable.len() == 1 {
4228            // Recorded so this is a one-time event: `judgements` stays empty
4229            // either way, which without this flag is indistinguishable from
4230            // "not yet judged" on the next reentry — and status is left
4231            // untouched, so a later node's conclusion (e.g. `Blocked` after
4232            // the review budget ran out) survives a resume instead of being
4233            // clobbered back to `Judging` by this node running again.
4234            self.state.judge_skipped = true;
4235            self.state.event(
4236                "judge",
4237                format!(
4238                    "only candidate {} produced a change; judging skipped",
4239                    viable[0].label
4240                ),
4241            );
4242            self.state.save()?;
4243            return Ok(());
4244        }
4245        self.state.status = RunStatus::Judging;
4246
4247        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4248        let language = self.state.config.graph.language.clone();
4249        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4250        let sessions = self.state.config.graph.sessions;
4251        let artifacts = agent::artifacts_dir(&self.state.dir());
4252        let root = self.state.worktree_root();
4253        let base_short = short(&self.state.base_commit);
4254
4255        let mut jobs = Vec::new();
4256        let mut orders = Vec::new();
4257        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4258            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4259            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4260            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4261            let seat_key = format!("judge-{}", j + 1);
4262            let seat = self.seat(&seat_key, &spec.id);
4263            jobs.push(SeatJob {
4264                prompt: prompt::judge(
4265                    &self.state.instruction,
4266                    &views,
4267                    self.roles.judges.len(),
4268                    &base_short,
4269                    &language,
4270                ),
4271                spec,
4272                seat,
4273                cwd: root.join(format!("judge-{}", j + 1)),
4274                timeout,
4275                allow_write: false,
4276                sessions,
4277                artifacts: artifacts.clone(),
4278                stem: format!("judge-{}", j + 1),
4279                handover: None,
4280            });
4281        }
4282
4283        self.state.event(
4284            "judge",
4285            format!(
4286                "{} judges ranking {} candidates blind",
4287                jobs.len(),
4288                viable.len()
4289            ),
4290        );
4291        let labels_for_check = labels.clone();
4292        let mut quota_losses = Vec::new();
4293        let cache = self.state.config.cache_dir();
4294        let ctx = WaveCtx {
4295            carry_seats: false,
4296            pauses: Some((&self.pause, &self.interrupt)),
4297            run: &run_id,
4298            node: "judge",
4299            prompts: &prompts,
4300            cache: cache.as_deref(),
4301            round: None,
4302        };
4303        let results = ask_json_wave::<Ranking>(
4304            jobs,
4305            Arc::clone(&self.sem),
4306            self.state.config.graph.retries,
4307            &self.roles.judge_roster,
4308            &ctx,
4309            &mut quota_losses,
4310            &mut self.state,
4311            &move |r: &Ranking| r.validate(&labels_for_check),
4312        )
4313        .await;
4314        if self.state.resource_block.is_some() {
4315            return self.stop_for_resource();
4316        }
4317        self.state.quota.extend(quota_losses);
4318
4319        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4320            let agent_id = seat.agent.clone();
4321            self.state.seats.insert(seat.key.clone(), seat);
4322            let mut record = Judgement {
4323                judge: j + 1,
4324                seat: format!("judge-{}", j + 1),
4325                agent: agent_id,
4326                ranking: Vec::new(),
4327                reasons: BTreeMap::new(),
4328                confidence: None,
4329                strengths: BTreeMap::new(),
4330                order: orders[j].clone(),
4331                failed: None,
4332                duration_ms: 0,
4333            };
4334            match res {
4335                Ok((ranking, out)) => {
4336                    record.ranking = ranking.normalized();
4337                    record.reasons = ranking.reasons;
4338                    record.strengths = ranking.strengths;
4339                    record.confidence = ranking.confidence;
4340                    record.duration_ms = out.duration_ms;
4341                    self.state.event(
4342                        "judge",
4343                        format!(
4344                            "judge {} ranked {}",
4345                            j + 1,
4346                            record.ranking.iter().collect::<String>()
4347                        ),
4348                    );
4349                }
4350                Err(e) => {
4351                    record.failed = Some(e.to_string());
4352                    self.state
4353                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4354                }
4355            }
4356            self.state.judgements.push(record);
4357            self.state.save()?;
4358        }
4359        Ok(())
4360    }
4361
4362    // ---------------------------------------------------------- deliberate
4363
4364    async fn deliberate(&mut self) -> Result<()> {
4365        if self.hold_base_sync().await? {
4366            return Ok(());
4367        }
4368        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4369        // agent files with `magi task add` name the run that paid for it. The
4370        // prompt overlay is cloned alongside it because the waves borrow it
4371        // while `self` is mutably borrowed by the node's own bookkeeping.
4372        let run_id = self.state.id.clone();
4373        let prompts = self.state.config.prompts.clone();
4374        let rounds = self.state.config.graph.deliberate_rounds;
4375        // Resume unfinished rounds after an outage, but never reopen a tally.
4376        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4377            return Ok(());
4378        }
4379        let tops: Vec<char> = self
4380            .state
4381            .judgements
4382            .iter()
4383            .filter_map(|j| j.ranking.first().copied())
4384            .collect();
4385        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4386            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4387                self.state.event(
4388                    "deliberate",
4389                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4390                );
4391            }
4392            self.state.status = RunStatus::Voting;
4393            self.state.save()?;
4394            return Ok(());
4395        }
4396
4397        self.state.status = RunStatus::Deliberating;
4398        self.state.event(
4399            "deliberate",
4400            format!(
4401                "split: first choices were {} — opening {rounds} round(s)",
4402                tops.iter().collect::<String>()
4403            ),
4404        );
4405
4406        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4407        let language = self.state.config.graph.language.clone();
4408        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4409        let sessions = self.state.config.graph.sessions;
4410        let artifacts = agent::artifacts_dir(&self.state.dir());
4411        let root = self.state.worktree_root();
4412        let base_short = short(&self.state.base_commit);
4413
4414        // Judges argue in sequence so that a turn can answer the one before it;
4415        // that is the difference between deliberation and three parallel
4416        // monologues.
4417        for round in self.state.deliberation.len() + 1..=rounds {
4418            let mut turns: Vec<DeliberationTurn> = Vec::new();
4419            let mut round_losses = Vec::new();
4420            let mut asked = 0;
4421            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4422                if self.state.judgements[j].failed.is_some() {
4423                    continue;
4424                }
4425                let seat_key = format!("judge-{}", j + 1);
4426                let spec = self.occupant(&seat_key, spec);
4427                let mut seat = self.seat(&seat_key, &spec.id);
4428                let transcript = self.transcript(&turns, j);
4429                let build = |context: Option<&str>| {
4430                    prompt::deliberate(
4431                        &self.state.instruction,
4432                        context,
4433                        &transcript,
4434                        round,
4435                        rounds,
4436                        &language,
4437                    )
4438                };
4439                let block = self.candidate_block(&viable, &base_short);
4440                let full = build(Some(&block));
4441                let text = if has_context(&spec, &seat, sessions) {
4442                    build(None)
4443                } else {
4444                    full.clone()
4445                };
4446                let job = SeatJob {
4447                    spec,
4448                    seat: seat.clone(),
4449                    prompt: text,
4450                    cwd: root.join(format!("judge-{}", j + 1)),
4451                    timeout,
4452                    allow_write: false,
4453                    sessions,
4454                    artifacts: artifacts.clone(),
4455                    stem: format!("delib-{round}-judge-{}", j + 1),
4456                    handover: Some(full),
4457                };
4458                let cache = self.state.config.cache_dir();
4459                let ctx = WaveCtx {
4460                    carry_seats: false,
4461                    pauses: Some((&self.pause, &self.interrupt)),
4462                    run: &run_id,
4463                    node: "deliberate",
4464                    prompts: &prompts,
4465                    cache: cache.as_deref(),
4466                    round: None,
4467                };
4468                // A turn is never nudged (`retries` 0): a failed seat is
4469                // handed to the next roster agent, which gets the full
4470                // context. An empty answer is a turn, not a failure.
4471                let mut losses = Vec::new();
4472                asked += 1;
4473                let mut results = ask_wave_with::<String>(
4474                    vec![job],
4475                    Arc::clone(&self.sem),
4476                    0,
4477                    &self.roles.judge_roster,
4478                    &ctx,
4479                    &mut losses,
4480                    &mut self.state,
4481                    &|text: &str| {
4482                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4483                    },
4484                )
4485                .await;
4486                if self.state.resource_block.is_some() {
4487                    return self.stop_for_resource();
4488                }
4489                round_losses.extend(losses.iter().cloned());
4490                self.state.quota.extend(losses);
4491                let (updated, res, _) = results.pop().expect("one job in, one result out");
4492                seat = updated;
4493                let agent_id = seat.agent.clone();
4494                self.state.seats.insert(seat.key.clone(), seat);
4495                let body = match res {
4496                    Ok((body, _)) => body,
4497                    // Skip the seat; a CLI's raw error JSON is never read as
4498                    // this judge's position.
4499                    Err(e) => {
4500                        self.state
4501                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4502                        continue;
4503                    }
4504                };
4505                let tentative = verdict::extract_json::<Position>(&body)
4506                    .ok()
4507                    .and_then(|p| p.tentative)
4508                    .and_then(|s| s.trim().chars().next())
4509                    .map(|c| c.to_ascii_uppercase());
4510                self.state.event(
4511                    "deliberate",
4512                    format!(
4513                        "round {round}: judge {} now favours {}",
4514                        j + 1,
4515                        tentative.map_or("—".to_owned(), |c| c.to_string())
4516                    ),
4517                );
4518                turns.push(DeliberationTurn {
4519                    judge: j + 1,
4520                    agent: agent_id,
4521                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4522                    tentative,
4523                });
4524            }
4525            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4526                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4527                return self.stop_for_resource();
4528            }
4529            self.state
4530                .deliberation
4531                .push(DeliberationRound { round, turns });
4532            self.state.save()?;
4533        }
4534
4535        self.state.status = RunStatus::Voting;
4536        self.state.save()?;
4537        Ok(())
4538    }
4539
4540    // ---------------------------------------------------------------- vote
4541
4542    async fn vote(&mut self) -> Result<()> {
4543        if self.hold_base_sync().await? {
4544            return Ok(());
4545        }
4546        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4547        // agent files with `magi task add` name the run that paid for it. The
4548        // prompt overlay is cloned alongside it because the waves borrow it
4549        // while `self` is mutably borrowed by the node's own bookkeeping.
4550        let run_id = self.state.id.clone();
4551        let prompts = self.state.config.prompts.clone();
4552        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4553            return Ok(());
4554        }
4555        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4556        if viable.len() == 1 {
4557            return Ok(());
4558        }
4559        self.state.status = RunStatus::Voting;
4560
4561        let language = self.state.config.graph.language.clone();
4562        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4563        let sessions = self.state.config.graph.sessions;
4564        let artifacts = agent::artifacts_dir(&self.state.dir());
4565        let root = self.state.worktree_root();
4566        let base_short = short(&self.state.base_commit);
4567        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4568
4569        let mut jobs = Vec::new();
4570        let mut seats_at = Vec::new();
4571        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4572            if self
4573                .state
4574                .judgements
4575                .get(j)
4576                .is_some_and(|r| r.failed.is_some())
4577            {
4578                continue;
4579            }
4580            let seat_key = format!("judge-{}", j + 1);
4581            let spec = self.occupant(&seat_key, spec);
4582            let seat = self.seat(&seat_key, &spec.id);
4583            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4584            let text = if has_context(&spec, &seat, sessions) {
4585                prompt::final_vote(&viable, &language)
4586            } else {
4587                full.clone()
4588            };
4589            jobs.push(SeatJob {
4590                spec,
4591                seat,
4592                prompt: text,
4593                cwd: root.join(format!("judge-{}", j + 1)),
4594                timeout,
4595                allow_write: false,
4596                sessions,
4597                artifacts: artifacts.clone(),
4598                stem: format!("vote-judge-{}", j + 1),
4599                handover: Some(full),
4600            });
4601            seats_at.push(j);
4602        }
4603
4604        self.state.event(
4605            "vote",
4606            format!(
4607                "collecting {} final votes one by one, privately",
4608                jobs.len()
4609            ),
4610        );
4611        let allowed = viable.clone();
4612        let mut quota_losses = Vec::new();
4613        let cache = self.state.config.cache_dir();
4614        let ctx = WaveCtx {
4615            carry_seats: false,
4616            pauses: Some((&self.pause, &self.interrupt)),
4617            run: &run_id,
4618            node: "vote",
4619            prompts: &prompts,
4620            cache: cache.as_deref(),
4621            round: None,
4622        };
4623        let results = ask_json_wave::<FinalVote>(
4624            jobs,
4625            Arc::clone(&self.sem),
4626            self.state.config.graph.retries,
4627            &self.roles.judge_roster,
4628            &ctx,
4629            &mut quota_losses,
4630            &mut self.state,
4631            &move |v: &FinalVote| match v.label() {
4632                Some(c) if allowed.contains(&c) => Ok(()),
4633                other => bail!("vote {other:?} is not one of {allowed:?}"),
4634            },
4635        )
4636        .await;
4637        if self.state.resource_block.is_some() {
4638            return self.stop_for_resource();
4639        }
4640        self.state.quota.extend(quota_losses);
4641
4642        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4643            let agent_id = seat.agent.clone();
4644            self.state.seats.insert(seat.key.clone(), seat);
4645            let initial = self
4646                .state
4647                .judgements
4648                .get(j)
4649                .and_then(|r| r.ranking.first().copied());
4650            let mut record = VoteRecord {
4651                judge: j + 1,
4652                agent: agent_id,
4653                vote: None,
4654                reason: String::new(),
4655                changed: false,
4656            };
4657            match res {
4658                Ok((v, _)) => {
4659                    record.vote = v.label();
4660                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4661                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4662                    self.state.event(
4663                        "vote",
4664                        format!(
4665                            "judge {} voted {}{}",
4666                            j + 1,
4667                            record.vote.unwrap_or('?'),
4668                            if record.changed { " (changed)" } else { "" }
4669                        ),
4670                    );
4671                }
4672                Err(e) => {
4673                    self.state
4674                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4675                }
4676            }
4677            self.state.votes.push(record);
4678            self.state.save()?;
4679        }
4680        Ok(())
4681    }
4682
4683    // --------------------------------------------------------------- tally
4684
4685    fn tally(&mut self) -> Result<()> {
4686        if self.state.tally.is_some() {
4687            return Ok(());
4688        }
4689        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4690        let tops: Vec<char> = self
4691            .state
4692            .judgements
4693            .iter()
4694            .filter_map(|j| j.ranking.first().copied())
4695            .collect();
4696        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4697
4698        // A judge whose private vote failed still counted once, in the initial
4699        // ranking; using it beats discarding a whole seat.
4700        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4701        let mut cast: Vec<char> = Vec::new();
4702        for (i, j) in self.state.judgements.iter().enumerate() {
4703            let vote = self
4704                .state
4705                .votes
4706                .iter()
4707                .find(|v| v.judge == i + 1)
4708                .and_then(|v| v.vote)
4709                .or_else(|| j.ranking.first().copied());
4710            if let Some(v) = vote {
4711                *first_choice.entry(v).or_insert(0) += 1;
4712                cast.push(v);
4713            }
4714        }
4715
4716        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4717        for j in &self.state.judgements {
4718            let n = j.ranking.len();
4719            for (pos, label) in j.ranking.iter().enumerate() {
4720                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4721            }
4722        }
4723
4724        let best = first_choice.values().copied().max().unwrap_or(0);
4725        let mut leaders: Vec<char> = first_choice
4726            .iter()
4727            .filter(|(_, v)| **v == best)
4728            .map(|(k, _)| *k)
4729            .collect();
4730        let mut tie_break = None;
4731        if leaders.len() > 1 {
4732            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4733            let borda_leaders: Vec<char> = leaders
4734                .iter()
4735                .copied()
4736                .filter(|l| borda[l] == top_borda)
4737                .collect();
4738            tie_break = Some(if borda_leaders.len() == 1 {
4739                format!(
4740                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4741                    leaders.len()
4742                )
4743            } else {
4744                format!(
4745                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4746                    leaders.len()
4747                )
4748            });
4749            leaders = borda_leaders;
4750            leaders.sort_unstable();
4751        }
4752        let winner = *leaders
4753            .first()
4754            .or(viable.first())
4755            .context("no candidate to declare a winner from")?;
4756
4757        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4758        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4759        let deliberated = !self.state.deliberation.is_empty();
4760
4761        // Whose verdict is this? A rate-limited seat is absent even if it
4762        // ranked before the limit hit, so presence is measured against the
4763        // recorded losses, not just "did a ranking ever appear".
4764        let quota_seats: std::collections::BTreeSet<&str> =
4765            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4766        let mut present = 0usize;
4767        for (i, j) in self.state.judgements.iter().enumerate() {
4768            if quota_seats.contains(j.seat.as_str()) {
4769                continue;
4770            }
4771            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4772            let voted = self
4773                .state
4774                .votes
4775                .iter()
4776                .any(|v| v.judge == i + 1 && v.vote.is_some());
4777            if ranked || voted {
4778                present += 1;
4779            }
4780        }
4781        // Strict majority of the configured panel. A bare majority is real
4782        // signal we can act on, while a minority verdict must never stand in
4783        // for a healthy one. A one-candidate run needs no panel at all, and
4784        // `judges` stays `0` rather than the roster size a panel that never
4785        // sat would otherwise be credited with.
4786        let needs_quorum = viable.len() > 1;
4787        let judges_total = if needs_quorum {
4788            self.roles.judges.len()
4789        } else {
4790            0
4791        };
4792        let quorum = if needs_quorum {
4793            judges_total / 2 + 1
4794        } else {
4795            0
4796        };
4797        let met_quorum = !needs_quorum || present >= quorum;
4798        let uncontested = (!needs_quorum).then(|| {
4799            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4800        });
4801
4802        self.state.event(
4803            "tally",
4804            match &uncontested {
4805                Some(reason) => format!("winner {winner} — {reason}"),
4806                None => format!(
4807                    "winner {winner} — votes {} | initial {} | {} changed | \
4808                     {present}/{judges_total} judges{}",
4809                    first_choice
4810                        .iter()
4811                        .map(|(k, v)| format!("{k}:{v}"))
4812                        .collect::<Vec<_>>()
4813                        .join(" "),
4814                    if unanimous_initial {
4815                        "unanimous"
4816                    } else {
4817                        "split"
4818                    },
4819                    changed_votes,
4820                    if met_quorum {
4821                        String::new()
4822                    } else {
4823                        format!(" — below quorum ({quorum} required)")
4824                    },
4825                ),
4826            },
4827        );
4828        if !met_quorum {
4829            self.state.event(
4830                "stall",
4831                format!(
4832                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4833                     the run stops here, resumable"
4834                ),
4835            );
4836        }
4837        self.state.tally = Some(Tally {
4838            first_choice,
4839            borda,
4840            winner,
4841            rankings: tops.len(),
4842            unanimous_initial,
4843            deliberated,
4844            changed_votes,
4845            unanimous_final,
4846            tie_break,
4847            judges: judges_total,
4848            present,
4849            quorum,
4850            met_quorum,
4851            uncontested,
4852        });
4853        self.state.status = if met_quorum {
4854            RunStatus::Reviewing
4855        } else {
4856            RunStatus::Stalled
4857        };
4858        self.state.save()?;
4859        Ok(())
4860    }
4861
4862    // ------------------------------------------------------------- recover
4863
4864    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4865    /// resumed toward completion once the transient cause clears.
4866    ///
4867    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4868    /// it toward the quorum, which is exactly the set of seats whose absence
4869    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4870    /// not depend on which node happened to hit the limit), or an ordinary
4871    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4872    /// seat is never disturbed.
4873    ///
4874    /// A seat that now answers with a usable ranking is "recovered": its
4875    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4876    /// `tally` counts it present again), and its vote re-collected. A seat that
4877    /// still fails keeps its loss and stays absent.
4878    ///
4879    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4880    /// to review/gate/merge), `false` when it is still below quorum (the run
4881    /// stays `Stalled`, still resumable for a later retry).
4882    #[allow(clippy::too_many_lines)]
4883    async fn recover_stall(&mut self) -> Result<bool> {
4884        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4885        // agent files with `magi task add` name the run that paid for it. The
4886        // prompt overlay is cloned alongside it because the waves borrow it
4887        // while `self` is mutably borrowed by the node's own bookkeeping.
4888        let run_id = self.state.id.clone();
4889        let prompts = self.state.config.prompts.clone();
4890        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4891        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4892        // is what keeps a non-quota collapse — or a quota loss recorded at the
4893        // deliberate node — from being a permanent dead-end on `--resume`.
4894        let quota_seats: BTreeSet<&str> =
4895            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4896        let absent: Vec<String> = self
4897            .state
4898            .judgements
4899            .iter()
4900            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4901            .map(|j| j.seat.clone())
4902            .collect();
4903        if absent.is_empty() {
4904            return Ok(false);
4905        }
4906        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4907        if viable.len() <= 1 {
4908            return Ok(false);
4909        }
4910        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4911        let language = self.state.config.graph.language.clone();
4912        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4913        let sessions = self.state.config.graph.sessions;
4914        let artifacts = agent::artifacts_dir(&self.state.dir());
4915        let root = self.state.worktree_root();
4916        let base_short = short(&self.state.base_commit);
4917        let candidates: Vec<Candidate> = viable.clone();
4918
4919        // Map each absent seat key to its 0-based position in `roles.judges`.
4920        let mut positions: Vec<usize> = absent
4921            .iter()
4922            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4923            .collect();
4924        if positions.is_empty() {
4925            return Ok(false);
4926        }
4927        positions.sort_unstable();
4928        positions.dedup();
4929
4930        // Re-rank the lost seats, one blind prompt each.
4931        let mut judge_jobs = Vec::new();
4932        for &j in &positions {
4933            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4934            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4935            let seat_key = format!("judge-{}", j + 1);
4936            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4937            let seat = self.seat(&seat_key, &spec.id);
4938            judge_jobs.push(SeatJob {
4939                spec,
4940                seat,
4941                prompt: prompt::judge(
4942                    &self.state.instruction,
4943                    &views,
4944                    self.roles.judges.len(),
4945                    &base_short,
4946                    &language,
4947                ),
4948                cwd: root.join(seat_key),
4949                timeout,
4950                allow_write: false,
4951                sessions,
4952                artifacts: artifacts.clone(),
4953                stem: format!("judge-{}-recover", j + 1),
4954                handover: None,
4955            });
4956        }
4957
4958        let labels_for_check = labels.clone();
4959        let mut judge_losses = Vec::new();
4960        let retries = self.state.config.graph.retries;
4961        let cache = self.state.config.cache_dir();
4962        let ctx = WaveCtx {
4963            carry_seats: false,
4964            pauses: Some((&self.pause, &self.interrupt)),
4965            run: &run_id,
4966            node: "judge",
4967            prompts: &prompts,
4968            cache: cache.as_deref(),
4969            round: None,
4970        };
4971        let results = ask_json_wave::<Ranking>(
4972            judge_jobs,
4973            Arc::clone(&self.sem),
4974            retries,
4975            &self.roles.judge_roster,
4976            &ctx,
4977            &mut judge_losses,
4978            &mut self.state,
4979            &move |r: &Ranking| r.validate(&labels_for_check),
4980        )
4981        .await;
4982        if self.state.resource_block.is_some() {
4983            self.stop_for_resource()?;
4984            return Ok(false);
4985        }
4986
4987        // Refresh the judgement of every seat that ranked again.
4988        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4989        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4990            let agent_id = seat.agent.clone();
4991            self.state.seats.insert(seat.key.clone(), seat);
4992            let record = &mut self.state.judgements[j];
4993            match res {
4994                Ok((ranking, out)) => {
4995                    record.agent = agent_id;
4996                    record.ranking = ranking.normalized();
4997                    record.reasons = ranking.reasons;
4998                    record.strengths = ranking.strengths;
4999                    record.confidence = ranking.confidence;
5000                    record.failed = None;
5001                    record.duration_ms = out.duration_ms;
5002                    recovered.insert(j);
5003                    self.state.event(
5004                        "recover",
5005                        format!("judge {} ranked again after the limit", j + 1),
5006                    );
5007                }
5008                Err(e) => {
5009                    self.state
5010                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5011                }
5012            }
5013        }
5014
5015        // Re-ask the votes of the seats that recovered a ranking.
5016        let mut vote_jobs = Vec::new();
5017        let mut vote_pos: Vec<usize> = Vec::new();
5018        for &j in &recovered {
5019            let seat_key = format!("judge-{}", j + 1);
5020            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5021            let seat = self.seat(&seat_key, &spec.id);
5022            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5023            let text = if has_context(&spec, &seat, sessions) {
5024                prompt::final_vote(&labels, &language)
5025            } else {
5026                full.clone()
5027            };
5028            vote_jobs.push(SeatJob {
5029                spec,
5030                seat,
5031                prompt: text,
5032                cwd: root.join(seat_key),
5033                timeout,
5034                allow_write: false,
5035                sessions,
5036                artifacts: artifacts.clone(),
5037                stem: format!("vote-judge-{}-recover", j + 1),
5038                handover: Some(full),
5039            });
5040            vote_pos.push(j);
5041        }
5042        let allowed = labels.clone();
5043        let mut vote_losses = Vec::new();
5044        let vote_retries = self.state.config.graph.retries;
5045        let vote_cache = self.state.config.cache_dir();
5046        let ctx = WaveCtx {
5047            carry_seats: false,
5048            pauses: Some((&self.pause, &self.interrupt)),
5049            run: &run_id,
5050            node: "vote",
5051            prompts: &prompts,
5052            cache: vote_cache.as_deref(),
5053            round: None,
5054        };
5055        let votes = ask_json_wave::<FinalVote>(
5056            vote_jobs,
5057            Arc::clone(&self.sem),
5058            vote_retries,
5059            &self.roles.judge_roster,
5060            &ctx,
5061            &mut vote_losses,
5062            &mut self.state,
5063            &move |v: &FinalVote| match v.label() {
5064                Some(c) if allowed.contains(&c) => Ok(()),
5065                other => bail!("vote {other:?} is not one of {allowed:?}"),
5066            },
5067        )
5068        .await;
5069        if self.state.resource_block.is_some() {
5070            self.stop_for_resource()?;
5071            return Ok(false);
5072        }
5073        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5074            let agent_id = seat.agent.clone();
5075            self.state.seats.insert(seat.key.clone(), seat);
5076            match res {
5077                Ok((v, _)) => {
5078                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5079                        rec.vote = v.label();
5080                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5081                    } else {
5082                        self.state.votes.push(VoteRecord {
5083                            judge: j + 1,
5084                            agent: agent_id,
5085                            vote: v.label(),
5086                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5087                            changed: false,
5088                        });
5089                    }
5090                    self.state.event(
5091                        "recover",
5092                        format!("judge {} voted again after the limit", j + 1),
5093                    );
5094                }
5095                Err(e) => {
5096                    self.state
5097                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5098                }
5099            }
5100        }
5101
5102        // A seat that ranked again is present even if its re-vote failed —
5103        // `tally` falls back to the initial ranking's first choice — so clear
5104        // its quota loss. Seats that still fail keep theirs and stay absent.
5105        let recovered_keys: BTreeSet<String> = recovered
5106            .iter()
5107            .map(|&j| format!("judge-{}", j + 1))
5108            .collect();
5109        self.state
5110            .quota
5111            .retain(|q| !recovered_keys.contains(&q.seat));
5112        // A seat that hit the limit again is a fresh loss, not the old one:
5113        // replace the stale entry so the history stays one-per-seat and the
5114        // daemon can tell this attempt's loss from a previous session's.
5115        for loss in judge_losses.into_iter().chain(vote_losses) {
5116            if recovered_keys.contains(&loss.seat) {
5117                continue;
5118            }
5119            self.state.quota.retain(|q| q.seat != loss.seat);
5120            self.state.quota.push(loss);
5121        }
5122
5123        // Recompute the verdict from the refreshed panel.
5124        self.state.tally = None;
5125        self.tally()?;
5126        Ok(self
5127            .state
5128            .tally
5129            .as_ref()
5130            .map(|t| t.met_quorum)
5131            .unwrap_or(false))
5132    }
5133
5134    // ---------------------------------------------------------------- graft
5135
5136    /// Port the strengths the judges attributed to the losing candidates onto
5137    /// the winner, once, between the tally and the review loop.
5138    ///
5139    /// Best-effort by construction: it returns nothing and fails nothing. A
5140    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5141    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5142    /// the run carries on as if the phase were off. See [`graft`] for the
5143    /// decisions and `AGENTS.md` for the invariants.
5144    ///
5145    /// The one exception is a rollback that could not be confirmed: the
5146    /// rejected commit may still be the winner's tip, so the run is blocked
5147    /// (resumable; the record stays `Running`, which makes a resume retry the
5148    /// restore) instead of reviewing, gating and merging it.
5149    async fn graft(&mut self) -> Result<()> {
5150        let Err(e) = self.graft_inner().await else {
5151            return Ok(());
5152        };
5153        if e.is::<crate::repo_lock::ResourceBlocked>() {
5154            return Err(e);
5155        }
5156        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5157            self.state.status = RunStatus::Blocked;
5158            self.state.event("graft", format!("blocked: {e:#}"));
5159            self.state.save()?;
5160            return Err(e);
5161        }
5162        // An error after the `Running` record was saved may have left the
5163        // fixer's work in the tree: the record must not stay unsettled
5164        // (a later resume would reset past the review fixes), so confirm the
5165        // restore now, or block.
5166        if let Some(rec) = self.state.graft.clone()
5167            && !rec.outcome.settled()
5168        {
5169            if let Some(winner) = self.state.winner().cloned() {
5170                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5171                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5172                        return Err(re);
5173                    }
5174                    self.state.status = RunStatus::Blocked;
5175                    self.state.event("graft", format!("blocked: {re:#}"));
5176                    self.state.save()?;
5177                    return Err(re);
5178                }
5179            }
5180            if let Some(g) = self.state.graft.as_mut() {
5181                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5182            }
5183        }
5184        self.state.event("graft", format!("skipped: {e:#}"));
5185        if let Err(e) = self.state.save() {
5186            tracing::warn!("save after graft: {e:#}");
5187        }
5188        Ok(())
5189    }
5190
5191    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5192    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5193    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5194        let _coordination = self.coordinate(wt).await?;
5195        crate::recovery::restore_repair(wt, pre)
5196            .await
5197            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5198    }
5199
5200    /// A skip is a run event, recorded once however often the node is re-entered.
5201    fn graft_skipped(&mut self, why: &str) {
5202        let message = format!("skipped: {why}");
5203        if !self
5204            .state
5205            .events
5206            .iter()
5207            .any(|e| e.node == "graft" && e.message == message)
5208        {
5209            self.state.event("graft", message);
5210        }
5211    }
5212
5213    async fn graft_inner(&mut self) -> Result<()> {
5214        // A round that was started and never finished (crash, kill): the
5215        // fixer may have left anything in the tree, so put the winner back.
5216        if let Some(rec) = self.state.graft.clone()
5217            && !rec.outcome.settled()
5218        {
5219            // Reviews exist only if the graft ended without its record being
5220            // settled (a swallowed error): the tree has moved on since, and
5221            // a reset to `pre` would discard the review fixes.
5222            if self.state.reviews.is_empty()
5223                && let Some(winner) = self.state.winner().cloned()
5224            {
5225                self.graft_restore(&winner.worktree, &rec.pre).await?;
5226            }
5227            if rec.outcome == GraftOutcome::WaitingForRestore {
5228                self.state.graft = None;
5229                self.state.save()?;
5230            } else {
5231                if let Some(g) = self.state.graft.as_mut() {
5232                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5233                }
5234                self.state.event(
5235                    "graft",
5236                    "rolled back: the previous round was interrupted; the winner is untouched",
5237                );
5238                self.state.save()?;
5239                return Ok(());
5240            }
5241        }
5242        let plan = match graft::plan(&self.state) {
5243            Ok(plan) => plan,
5244            Err(skip) => {
5245                if skip != graft::Skip::AlreadyDone {
5246                    self.graft_skipped(skip.reason());
5247                    self.state.save()?;
5248                }
5249                return Ok(());
5250            }
5251        };
5252        let Some(winner) = self.state.winner().cloned() else {
5253            return Ok(());
5254        };
5255        let wt = winner.worktree.clone();
5256        if !git::is_clean(&wt).await? {
5257            self.graft_skipped("the winner's worktree has uncommitted changes");
5258            self.state.save()?;
5259            return Ok(());
5260        }
5261        let pre = git::rev_parse(&wt, "HEAD").await?;
5262        // Saved before the fixer is called: a stop from here on is repaired
5263        // by the branch above on the next entry.
5264        self.state.graft = Some(GraftRecord {
5265            pre: pre.clone(),
5266            post: None,
5267            lines: None,
5268            limit: None,
5269            agent: None,
5270            outcome: GraftOutcome::Running,
5271            requested: graft::requested(&plan),
5272            adoption: None,
5273            adoption_error: None,
5274        });
5275        self.state.event(
5276            "graft",
5277            format!(
5278                "porting strengths of candidate(s) {} onto {}",
5279                plan.strengths
5280                    .iter()
5281                    .map(|(l, _, _)| l.to_string())
5282                    .collect::<Vec<_>>()
5283                    .join(", "),
5284                plan.winner
5285            ),
5286        );
5287        self.state.save()?;
5288
5289        let fix_prompt = prompt::graft(
5290            &self.state.instruction,
5291            plan.winner,
5292            &plan.strengths,
5293            &self.state.config.graph.language,
5294        );
5295        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5296        let sessions = self.state.config.graph.sessions;
5297        let artifacts = agent::artifacts_dir(&self.state.dir());
5298        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5299        let (_, seat, out) = self
5300            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5301                SeatJob {
5302                    prompt: fix_prompt.clone(),
5303                    spec,
5304                    seat,
5305                    cwd: wt.clone(),
5306                    timeout,
5307                    allow_write: true,
5308                    sessions,
5309                    artifacts: artifacts.clone(),
5310                    stem: "graft".to_owned(),
5311                    handover: None,
5312                }
5313            })
5314            .await;
5315        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5316            // Preserve the need to restore earlier fallback edits without
5317            // confusing an unstarted seat with an interrupted invocation.
5318            self.state.graft.as_mut().expect("graft record").outcome =
5319                GraftOutcome::WaitingForRestore;
5320            return self.stop_for_resource();
5321        }
5322        let mut why: Option<String> = None;
5323        match &out {
5324            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5325                why = Some("the fixer produced nothing usable".to_owned());
5326            }
5327            AgentOutcome::Ok(_) => {}
5328            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5329            AgentOutcome::Quota(o) => {
5330                self.state.quota.push(QuotaLoss::from_report(
5331                    seat.key.clone(),
5332                    "graft",
5333                    o.quota.as_ref(),
5334                ));
5335                why = Some("rate limited (quota)".to_owned());
5336            }
5337            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5338                why = Some(format!(
5339                    "the fixer failed: {}",
5340                    e.lines()
5341                        .next()
5342                        .unwrap_or("")
5343                        .chars()
5344                        .take(160)
5345                        .collect::<String>()
5346                ));
5347            }
5348        }
5349        let agent_id = seat.agent.clone();
5350        self.state.seats.insert(seat.key.clone(), seat);
5351
5352        let mut post = None;
5353        let mut lines = None;
5354        let _coordination = self.coordinate(&wt).await?;
5355        if why.is_none() {
5356            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5357            if let Ok(r) = &rescued {
5358                self.state.note_withheld("graft", &r.withheld);
5359            }
5360            let head = git::rev_parse(&wt, "HEAD").await?;
5361            // What is measured must be what gets reviewed and gated: a failed
5362            // rescue, or anything still uncommitted (withheld lockfiles
5363            // aside, which are never part of the tree), rejects the graft.
5364            let dirty = match &rescued {
5365                Ok(r) => git::status_porcelain(&wt)
5366                    .await
5367                    .map(|st| {
5368                        st.lines().any(|l| {
5369                            !r.withheld
5370                                .iter()
5371                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5372                        })
5373                    })
5374                    .unwrap_or(true),
5375                Err(_) => true,
5376            };
5377            if dirty {
5378                why = Some("the fixer left changes that could not be committed".to_owned());
5379            } else if head == pre {
5380                why = Some("the fixer changed nothing".to_owned());
5381            } else {
5382                lines = git::changed_lines(&wt, &pre, &head).await;
5383                post = Some(head);
5384            }
5385        }
5386        let (adoption, adoption_error) = match &out {
5387            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5388            _ => (None, None),
5389        };
5390        let requested = graft::requested(&plan);
5391        let outcome = match why {
5392            None => {
5393                self.state.event(
5394                    "graft",
5395                    format!(
5396                        "applied: {}",
5397                        lines.map_or_else(
5398                            || "changed lines unavailable".to_owned(),
5399                            |n| format!("{n} changed lines")
5400                        )
5401                    ),
5402                );
5403                GraftOutcome::Applied
5404            }
5405            Some(why) => {
5406                // Not settled until the restore is confirmed: the record
5407                // stays `Running`, so a resume retries it.
5408                crate::recovery::restore_repair(&wt, &pre)
5409                    .await
5410                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5411                self.state.event(
5412                    "graft",
5413                    format!("rolled back: {why}; the winner is untouched"),
5414                );
5415                GraftOutcome::RolledBack(why)
5416            }
5417        };
5418        self.state.graft = Some(GraftRecord {
5419            pre,
5420            post,
5421            lines,
5422            limit: None,
5423            agent: Some(agent_id),
5424            outcome,
5425            requested,
5426            adoption,
5427            adoption_error,
5428        });
5429        self.state.save()?;
5430        Ok(())
5431    }
5432
5433    // ----------------------------------------------------------------- fold
5434
5435    async fn fold_losers(&mut self) -> Result<()> {
5436        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5437            return Ok(());
5438        };
5439        if !self.state.candidate_preservation.is_empty() {
5440            bail!("candidate preservation incomplete; refusing cleanup");
5441        }
5442        let repo = self.state.repo.clone();
5443        let _coordination = self.coordinate(&repo).await?;
5444        let home = crate::run::home();
5445        let root = self.state.worktree_root();
5446        let isolated = crate::build_target::isolated(&self.state.config);
5447        let mut folded = Vec::new();
5448        for i in 0..self.state.candidates.len() {
5449            let c = &self.state.candidates[i];
5450            if c.label == winner || c.folded {
5451                continue;
5452            }
5453            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5454            let target = fold_target(&home, &root, &wt, isolated);
5455            remove_preserved_worktree(&repo, &wt).await?;
5456            reclaim_fold_target(&home, target);
5457            if git::branch_exists(&repo, &branch).await?
5458                && !git::branch_delete(&repo, &branch).await?
5459            {
5460                bail!("candidate branch removal refused");
5461            }
5462            self.state.candidates[i].folded = true;
5463            self.state.save()?;
5464            folded.push(label.to_string());
5465        }
5466        // The judges are finished; their checkouts are pure cost from here.
5467        for j in 1..=self.roles.judges.len() {
5468            let wt = root.join(format!("judge-{j}"));
5469            if wt.exists() {
5470                let target = fold_target(&home, &root, &wt, isolated);
5471                remove_read_seat_worktree(&mut self.state, &wt).await?;
5472                reclaim_fold_target(&home, target);
5473                self.state.save()?;
5474            }
5475        }
5476        // The design-deliberation stage is finished by the time a tally
5477        // exists — same reasoning as the judges above.
5478        if self.state.config.graph.advise {
5479            for k in 1..=self.state.config.graph.advisors {
5480                let wt = root.join(format!("advisor-{k}"));
5481                if wt.exists() {
5482                    let target = fold_target(&home, &root, &wt, isolated);
5483                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5484                    reclaim_fold_target(&home, target);
5485                    self.state.save()?;
5486                }
5487            }
5488        }
5489        if !folded.is_empty() {
5490            self.state
5491                .event("fold", format!("folded candidates {}", folded.join(", ")));
5492            self.state.save()?;
5493        }
5494        Ok(())
5495    }
5496
5497    // ------------------------------------------------------------ base sync
5498
5499    async fn hold_base_sync(&mut self) -> Result<bool> {
5500        self.hold_base_sync_as(None).await
5501    }
5502
5503    async fn hold_base_sync_kind(
5504        &mut self,
5505        kind: crate::base_sync_recovery::StopKind,
5506    ) -> Result<()> {
5507        self.hold_base_sync_as(Some(kind)).await?;
5508        Ok(())
5509    }
5510
5511    async fn hold_base_sync_as(
5512        &mut self,
5513        kind: Option<crate::base_sync_recovery::StopKind>,
5514    ) -> Result<bool> {
5515        if !self.state.base_sync_blocked() {
5516            self.state.base_sync_recovery.stop = None;
5517            return Ok(false);
5518        }
5519        let head = match self.state.winner() {
5520            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5521                .await
5522                .unwrap_or_default(),
5523            None => String::new(),
5524        };
5525        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5526            && !authorization.consumed
5527            && authorization.stop.head != head
5528        {
5529            authorization.refuse(format!(
5530                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5531                authorization.stop.head
5532            ));
5533        }
5534        self.state.record_base_sync_stop(&head);
5535        if let Some(kind) = kind {
5536            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5537            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5538                stop.kind = kind;
5539            }
5540        }
5541        self.state.save()?;
5542        Ok(true)
5543    }
5544
5545    async fn resume_legacy_sequencer_stop(
5546        &mut self,
5547        winner: &Candidate,
5548        scratch: &Path,
5549        head: &str,
5550    ) -> Result<()> {
5551        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5552
5553        if !resumable_sequencer_stop(&self.state)
5554            || legacy_sequencer_head(&self.state) != Some(head)
5555            || self.state.base_recovery_pending()
5556            || self
5557                .state
5558                .repair_grants
5559                .iter()
5560                .any(|grant| !grant.succeeded)
5561        {
5562            return Ok(());
5563        }
5564        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5565            return Ok(());
5566        };
5567        let owner = crate::queue::Queue::open().get(task)?;
5568        if owner.execution_runs().last() != Some(&self.state.id)
5569            || owner.status == crate::queue::TaskStatus::Done
5570            || owner.fresh_start
5571            || owner.review_branch.is_some()
5572            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5573        {
5574            return Ok(());
5575        }
5576
5577        let repo = self.state.repo.clone();
5578        let wait = repository_wait(&self.state, None);
5579        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5580        let common = crate::repo_lock::common_dir(&repo).await?;
5581        let op = self.state.base_sync_recovery.operations.last().unwrap();
5582        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5583            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5584            || git::current_branch(&winner.worktree).await?.as_deref()
5585                != Some(winner.branch.as_str())
5586            || common.is_none()
5587            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5588            || crate::repo_lock::common_dir(&owner.repo).await? != common
5589            || !git::is_clean(&winner.worktree).await?
5590        {
5591            return Ok(());
5592        }
5593        if scratch.try_exists()? {
5594            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5595            if admin.join("locked").try_exists()?
5596                || !git::git(
5597                    scratch,
5598                    &[
5599                        "status",
5600                        "--porcelain",
5601                        "--untracked-files=all",
5602                        "--ignored",
5603                    ],
5604                )
5605                .await?
5606                .is_empty()
5607            {
5608                return Ok(());
5609            }
5610            if git::checked_rebase_in_progress(scratch).await? {
5611                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5612                    || crate::rebase::rebase_target(scratch).await? != op.tip
5613                    || !git::unmerged_paths(scratch).await?.is_empty()
5614                {
5615                    return Ok(());
5616                }
5617            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5618                || git::rev_parse(scratch, "HEAD").await? != head
5619            {
5620                return Ok(());
5621            }
5622        }
5623
5624        self.state
5625            .base_sync_recovery
5626            .operations
5627            .last_mut()
5628            .unwrap()
5629            .finished = false;
5630        let diagnostic = self
5631            .state
5632            .base_sync
5633            .as_mut()
5634            .unwrap()
5635            .conflict
5636            .take()
5637            .unwrap();
5638        self.state.base_sync_recovery.stop = None;
5639        self.state.event(
5640            "rebase",
5641            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5642        );
5643        self.state.save()
5644    }
5645
5646    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5647    /// anything verifies it.
5648    ///
5649    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5650    /// read whatever is checked out in the winner's worktree. Left alone that
5651    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5652    /// it when the run *branched* - and a run takes long enough that the base
5653    /// has usually moved by the time it gets here. A gate that ran there
5654    /// answers "green on the commit this run started from", not "green on
5655    /// what is about to land", and the difference showed up three times in
5656    /// one day as a green run whose merge would have reverted a file another
5657    /// pull request had already landed.
5658    ///
5659    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5660    /// `land::Step::Rebase` calls, rather than a second implementation of the
5661    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5662    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5663    /// doc warns about ("two answers to a question nobody notices until a
5664    /// diff is wrong").
5665    ///
5666    /// Foreign-checkout reviews instead merge the base into the owned shadow
5667    /// worktree, preserving the ancestry required for fast-forward delivery.
5668    /// A conflicting merge is aborted and held for operator resolution.
5669    ///
5670    /// A conflict is not the end of the road: the standing rebase is handed
5671    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5672    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5673    /// land). Once it finishes, review and the gate run as usual on the
5674    /// rebased tree, which is where a breakage the new base caused is caught
5675    /// by the ordinary gate-fix round. magi resolves nothing itself.
5676    ///
5677    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5678    /// the current durable recovery interval, bounds how often the base is
5679    /// synchronized during active recovery (lifetime attempts remain evidence).
5680    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5681    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5682    /// what was tried (rounds spent, paths still conflicted) and the branch
5683    /// and worktree stay exactly as they were - untouched, for a person to
5684    /// look at - which is also what makes re-entering this function
5685    /// afterwards a no-op instead of a second attempt at the same wall. A
5686    /// push failure ends the same way.
5687    async fn sync_to_base(&mut self) -> Result<()> {
5688        if self.state.status == RunStatus::AlreadyInBase {
5689            return Ok(());
5690        }
5691        self.hold_base_sync().await?;
5692        let Some(winner) = self.state.winner().cloned() else {
5693            return Ok(());
5694        };
5695
5696        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5697
5698        let repo = self.state.repo.clone();
5699        let remote = self.state.config.merge.remote.clone();
5700        let base_branch = self.state.base_branch.clone();
5701        let tracking = format!("{remote}/{base_branch}");
5702
5703        let fetched_base =
5704            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5705        if !fetched_base
5706            && self
5707                .state
5708                .base_sync_recovery
5709                .stop
5710                .as_ref()
5711                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5712        {
5713            self.state.event(
5714                "land",
5715                "cannot recheck recorded public branch divergence without a fresh base",
5716            );
5717            self.state.save()?;
5718            return Ok(());
5719        }
5720        // No network, or the remote never had this branch: the run already
5721        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5722        // otherwise), and one that got this far is not blocked by a fetch
5723        // that fails now. It just has no newer tip to compare against.
5724        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5725            return Ok(());
5726        };
5727
5728        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5729        self.state.ensure_base_episode();
5730        let scratch = self.state.dir().join("base-sync");
5731        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
5732            .await?;
5733        let conflicted = self
5734            .state
5735            .base_sync
5736            .as_ref()
5737            .is_some_and(|s| s.conflict.is_some());
5738        let mut pending = self.state.pending_base_operation().cloned();
5739        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
5740        {
5741            Ok(active) => active,
5742            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
5743            Err(error) => return Err(error),
5744        };
5745        if in_progress {
5746            // Older resource stops predate operation reservations. Import the
5747            // standing Git operation, never retarget it to today's main.
5748            if pending.is_none()
5749                && self.state.base_sync_recovery.operations.is_empty()
5750                && !conflicted
5751                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5752                    .await
5753                    .ok()
5754                    .as_deref()
5755                    == Some(head.as_str())
5756                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5757                && git::is_clean(&winner.worktree).await?
5758            {
5759                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5760                if self.state.base_sync.is_none() {
5761                    self.state.base_sync = Some(BaseSync {
5762                        tip: saved_tip.clone(),
5763                        behind: 0,
5764                        attempts: 0,
5765                        conflict: None,
5766                        already_in: None,
5767                    });
5768                }
5769                self.state.reserve_base_operation(&head, &saved_tip);
5770                self.state.event(
5771                    "base-recovery",
5772                    "imported standing legacy rebase as a spent synchronization reservation",
5773                );
5774                self.state.save()?;
5775                pending = self.state.base_sync_recovery.operations.last().cloned();
5776            }
5777            let expected = pending.as_ref().map(|op| op.tip.as_str());
5778            if expected.is_none()
5779                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5780            {
5781                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5782                if self.state.base_sync.is_none() {
5783                    self.state.base_sync = Some(BaseSync {
5784                        tip: tip.clone(),
5785                        behind: 0,
5786                        attempts: 0,
5787                        conflict: None,
5788                        already_in: None,
5789                    });
5790                }
5791                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5792                self.state.event("land", why);
5793                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5794                    .await?;
5795                return Ok(());
5796            }
5797        }
5798        if let Some(op) = &pending {
5799            // A replay may add the pinned base's commits, never foreign work.
5800            let mut replay_proven =
5801                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5802            if !replay_proven && !in_progress && scratch.try_exists()? {
5803                let wait = repository_wait(&self.state, None);
5804                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5805                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5806                    Ok(true) => {
5807                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5808                        self.state.save()?;
5809                        git::worktree_remove(&repo, &scratch).await.ok();
5810                        replay_proven = true;
5811                    }
5812                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5813                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5814                }
5815            }
5816            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5817                if self.state.foreign_checkout.is_some() {
5818                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5819                        .await
5820                        .ok()
5821                        .as_deref()
5822                        == Some(op.head.as_str())
5823                        && git::rev_parse(&repo, &format!("{head}^2"))
5824                            .await
5825                            .ok()
5826                            .as_deref()
5827                            == Some(op.tip.as_str());
5828                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5829                    .await
5830                    .is_ok_and(|m| m.is_empty())
5831                    && let Ok(added) =
5832                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5833                {
5834                    replay_proven = true;
5835                    for commit in added {
5836                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5837                            replay_proven = false;
5838                            break;
5839                        }
5840                    }
5841                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5842                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5843                }
5844            }
5845            // Never retarget an operation across a crash, even if main moved.
5846            // sync_to_head resets and cleans with -x, so even ignored untracked
5847            // files must stop recovery independently of the old tracked tree.
5848            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5849                || (head != op.head
5850                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5851                        .await?
5852                        .is_empty())
5853                || (!git::is_clean(&winner.worktree).await?
5854                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5855                        .await
5856                        .is_ok_and(|o| o.ok()))
5857                || !replay_proven
5858            {
5859                let why = format!(
5860                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5861                    op.id
5862                );
5863                let sync = self
5864                    .state
5865                    .base_sync
5866                    .as_mut()
5867                    .context("reserved synchronization has no lifetime accounting")?;
5868                sync.conflict = Some(why.clone());
5869                self.state.event("land", why);
5870                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5871                    .await?;
5872                return Ok(());
5873            }
5874            if head != op.head {
5875                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5876            }
5877            tip = op.tip.clone();
5878        }
5879        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5880        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5881        if pending.is_none()
5882            && !conflicted
5883            && fetched_base
5884            && self
5885                .state
5886                .base_sync_recovery
5887                .episodes
5888                .last()
5889                .is_some_and(|e| e.boundary.is_some())
5890            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5891            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5892            && owner.execution_runs().last() == Some(&self.state.id)
5893            && owner.status != crate::queue::TaskStatus::Done
5894            && !owner.fresh_start
5895            && owner.review_branch.is_none()
5896            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5897            && let Some(approval) = owner.resumption.as_ref()
5898            && approval.instruction == owner.instruction
5899            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5900            && git::is_clean(&winner.worktree).await?
5901            && self.state.renew_base_episode(&task, approval, &head, &tip)
5902        {
5903            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5904            self.state.save()?;
5905        }
5906
5907        // Before any rebase, and before a recorded conflict is honoured: a
5908        // branch whose change reached the base under other commit ids has
5909        // nothing to rebase and nothing to conflict with, and a run that
5910        // already stopped on that phantom conflict recovers here on resume.
5911        // `behind == 0` with head == tip is a branch the base has since taken
5912        // in whole, whether or not a conflict was ever recorded: the ancestry
5913        // proof must still run (`classify` ignores a head still on the start
5914        // commit).
5915        if (behind > 0 || conflicted || head == tip)
5916            && self
5917                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5918                .await?
5919        {
5920            return Ok(());
5921        }
5922        if conflicted && self.state.base_recovery_pending() {
5923            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5924            let owner =
5925                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5926            let owner_valid = owner.as_ref().is_ok_and(|t| {
5927                t.execution_runs().last() == Some(&self.state.id)
5928                    && t.status != crate::queue::TaskStatus::Done
5929                    && !t.fresh_start
5930                    && t.review_branch.is_none()
5931            });
5932            let invalidation = if !owner_valid {
5933                Some("latest task ownership changed")
5934            } else if !owner.as_ref().is_ok_and(|t| {
5935                authorization
5936                    .generation
5937                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5938            }) {
5939                Some("owner approval generation changed")
5940            } else if authorization.question.as_ref().is_some_and(|question| {
5941                !crate::base_recovery_control::decision_current(
5942                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5943                    &self.state,
5944                    &authorization.task,
5945                    question,
5946                )
5947            }) {
5948                Some("recovery decision ownership, routing or stop evidence changed")
5949            } else if authorization.request.is_some()
5950                && !owner
5951                    .as_ref()
5952                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5953            {
5954                Some("owner decision changed")
5955            } else if let Some(scope) = &authorization.scope {
5956                if scope.tip != tip {
5957                    Some("fetched base changed")
5958                } else if !self
5959                    .state
5960                    .base_sync_recovery
5961                    .episodes
5962                    .last()
5963                    .is_some_and(|e| e.id == scope.episode)
5964                {
5965                    Some("active synchronization interval changed")
5966                } else if !owner
5967                    .as_ref()
5968                    .is_ok_and(|t| t.instruction == scope.instruction)
5969                {
5970                    Some("task instruction changed")
5971                } else {
5972                    None
5973                }
5974            } else {
5975                None
5976            };
5977            if let Some(reason) = invalidation {
5978                let authorization = self
5979                    .state
5980                    .base_sync_recovery
5981                    .authorizations
5982                    .last_mut()
5983                    .unwrap();
5984                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5985                self.state.save()?;
5986                return Ok(());
5987            }
5988            if !fetched_base
5989                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5990                || !git::is_clean(&winner.worktree).await?
5991                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5992            {
5993                return Ok(());
5994            }
5995        }
5996        let recovery = conflicted && self.state.consume_base_recovery(&head);
5997        if conflicted {
5998            // Consumption (including a refused changed HEAD) is durable before Git.
5999            self.state.save()?;
6000            if !recovery {
6001                return Ok(());
6002            }
6003        }
6004
6005        if behind == 0 {
6006            // A fixer-finished rebase moves the branch ref before the
6007            // winner's worktree is told (`sync_to_head` below). A run that
6008            // died in between resumes here with `behind == 0` and a tree still
6009            // holding the pre-rebase files, which review and the gate would
6010            // then read. That state is exactly: HEAD moved off the tip the
6011            // rebase started from, yet the tree is still identical to that
6012            // tip. A tree with edits of its own differs from it, so nothing
6013            // is thrown away.
6014            if let Some(from) = self
6015                .state
6016                .rebase_fixes
6017                .iter()
6018                .rev()
6019                .find_map(|r| r.from.clone())
6020                && from != head
6021                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6022                    .await
6023                    .is_ok_and(|o| o.ok())
6024            {
6025                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6026            }
6027            // An earlier attempt may have rebased the branch locally and died
6028            // before pushing it (only the fresh-rebase arm below pushes).
6029            // Publish it now, so the plain push at PR time is not refused as
6030            // a non-fast-forward. A run already holding a recorded conflict
6031            // never reaches here; that case is out of scope.
6032            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6033            if let Some(why) = &conflict {
6034                self.state.status = RunStatus::Blocked;
6035                self.state.event("land", why.clone());
6036            }
6037            self.state.base_sync = Some(BaseSync {
6038                tip,
6039                behind: 0,
6040                attempts,
6041                conflict,
6042                already_in: None,
6043            });
6044            if pending.is_some() {
6045                self.state.finish_base_operation(Some(&head));
6046            }
6047            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6048                .await?;
6049            self.state.save()?;
6050            return Ok(());
6051        }
6052
6053        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6054            let why = format!(
6055                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6056                 synchronization(s); synchronizing again would only race it",
6057                winner.branch
6058            );
6059            self.state.status = RunStatus::Blocked;
6060            self.state.base_sync = Some(BaseSync {
6061                tip,
6062                behind,
6063                attempts,
6064                conflict: Some(why.clone()),
6065                already_in: None,
6066            });
6067            self.state.event("land", why);
6068            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6069                .await?;
6070            self.state.save()?;
6071            return Ok(());
6072        }
6073
6074        if self.state.foreign_checkout.is_some() {
6075            // Delivery to the operator's checkout is fast-forward only. A
6076            // rebase here would discard its saved head from our ancestry.
6077            let wait = repository_wait(&self.state, None);
6078            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6079            if self.state.base_sync.is_none() {
6080                self.state.base_sync = Some(BaseSync {
6081                    tip: tip.clone(),
6082                    behind,
6083                    attempts: 0,
6084                    conflict: None,
6085                    already_in: None,
6086                });
6087            }
6088            self.state.reserve_base_operation(&head, &tip);
6089            self.state.save()?;
6090            let merged = git::git_raw(
6091                &winner.worktree,
6092                &[
6093                    "-c",
6094                    "core.hooksPath=/dev/null",
6095                    "merge",
6096                    "--no-ff",
6097                    "--no-autostash",
6098                    "--no-edit",
6099                    "-m",
6100                    &format!("Merge {tracking} before verifying"),
6101                    &tip,
6102                ],
6103            )
6104            .await?;
6105            let conflict = if merged.ok() {
6106                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6107                self.state.event(
6108                    "land",
6109                    format!("merged {tracking} into {} before verifying", winner.branch),
6110                );
6111                None
6112            } else {
6113                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6114                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6115                }
6116                let why = format!(
6117                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6118                    winner.branch,
6119                    merged.stderr.chars().take(600).collect::<String>()
6120                );
6121                self.state.status = RunStatus::Blocked;
6122                self.state.event("land", &why);
6123                Some(why)
6124            };
6125            let synced = conflict.is_none();
6126            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6127            self.state
6128                .finish_base_operation(synced.then_some(fresh.as_str()));
6129            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6130            self.state.base_sync = Some(BaseSync {
6131                tip,
6132                behind: if synced { 0 } else { behind },
6133                attempts,
6134                conflict,
6135                already_in: None,
6136            });
6137            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6138                .await?;
6139            self.state.save()?;
6140            return Ok(());
6141        }
6142
6143        self.state.event(
6144            "land",
6145            format!(
6146                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6147                winner.branch
6148            ),
6149        );
6150        self.state.save()?;
6151
6152        // The remote's copy of the branch, read now and only if the fetch
6153        // really succeeded (a stale tracking ref must never pin a lease). It is
6154        // pushed over after a rebase only when it is a commit this branch
6155        // already contains, by ancestry or by patch (an earlier rebase of ours
6156        // that never reached the remote): anything else is somebody else's work.
6157        let branch_tracking = format!("{remote}/{}", winner.branch);
6158        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6159        let remote_tip = if self.state.task_pr_branch().is_none()
6160            && matches!(&fetched_branch, Ok(o) if o.ok())
6161        {
6162            git::rev_parse(&repo, &branch_tracking).await.ok()
6163        } else {
6164            None
6165        };
6166        // A remote tip this branch does not contain is somebody else's work:
6167        // rebasing would leave a local tip that can never be pushed. Stop
6168        // before touching anything and say so.
6169        if let Some(theirs) = &remote_tip
6170            && !git::is_ancestor(&repo, theirs, &head).await
6171            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6172                .await
6173                .is_ok_and(|missing| missing.is_empty())
6174        {
6175            let why = format!(
6176                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6177                 them",
6178                short(theirs),
6179                winner.branch
6180            );
6181            self.state.status = RunStatus::Blocked;
6182            self.state.base_sync = Some(BaseSync {
6183                tip,
6184                behind,
6185                attempts,
6186                conflict: Some(why.clone()),
6187                already_in: None,
6188            });
6189            self.state.event("land", why);
6190            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6191                .await?;
6192            self.state.save()?;
6193            return Ok(());
6194        }
6195
6196        if self.state.base_sync.is_none() {
6197            self.state.base_sync = Some(BaseSync {
6198                tip: tip.clone(),
6199                behind,
6200                attempts: 0,
6201                conflict: None,
6202                already_in: None,
6203            });
6204        }
6205        let scratch = self.state.dir().join("base-sync");
6206        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6207        {
6208            if error.is::<crate::repo_lock::ResourceBlocked>() {
6209                return Ok(());
6210            }
6211            return Err(error);
6212        }
6213        self.state.reserve_base_operation(&head, &tip);
6214        self.state.save()?;
6215        let rebased =
6216            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6217                .await
6218            {
6219                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6220                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6221                Err(e) => Err(e),
6222            };
6223        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6224        let stop_kind = match &rebased {
6225            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6226            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6227            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6228        };
6229        match rebased {
6230            Ok(None) => {
6231                // The branch ref moved, but a worktree that already had it
6232                // checked out (the winner's) was not told; sync its index and
6233                // files before anything reads them.
6234                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6235                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6236                self.state.finish_base_operation(Some(&fresh));
6237                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6238                let mut conflict = None;
6239                if let Some(pinned) = &remote_tip {
6240                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6241                    match pushed {
6242                        Ok(o) if o.ok() => self.state.event(
6243                            "land",
6244                            format!("pushed rebased {} to {remote}", winner.branch),
6245                        ),
6246                        Ok(o) => {
6247                            conflict = Some(format!(
6248                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6249                                winner.branch,
6250                                short(pinned),
6251                                o.stderr.chars().take(600).collect::<String>()
6252                            ));
6253                        }
6254                        Err(e) => {
6255                            conflict = Some(format!(
6256                                "rebased {} locally but could not push it: {e:#}",
6257                                winner.branch
6258                            ));
6259                        }
6260                    }
6261                }
6262                if let Some(why) = &conflict {
6263                    self.state.status = RunStatus::Blocked;
6264                    self.state.event("land", why.clone());
6265                }
6266                self.state.base_sync = Some(BaseSync {
6267                    tip: tip.clone(),
6268                    behind: 0,
6269                    attempts,
6270                    conflict,
6271                    already_in: None,
6272                });
6273                self.state
6274                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6275            }
6276            Ok(Some(conflict)) => {
6277                self.state.finish_base_operation(None);
6278                let why = format!(
6279                    "{} conflicts with {tracking} and did not rebase: {}",
6280                    winner.branch,
6281                    conflict.chars().take(600).collect::<String>()
6282                );
6283                self.state.status = RunStatus::Blocked;
6284                self.state.base_sync = Some(BaseSync {
6285                    tip,
6286                    behind,
6287                    attempts,
6288                    conflict: Some(why.clone()),
6289                    already_in: None,
6290                });
6291                self.state.event("land", why);
6292            }
6293            // A refused Git write or a busy repository: nothing is wrong with
6294            // the branch. The scratch rebase stays standing and the run
6295            // resumes into it (`base_sync` must not claim a conflict).
6296            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6297                self.state.save()?;
6298                return Ok(());
6299            }
6300            Err(e) => {
6301                self.state.finish_base_operation(None);
6302                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6303                self.state.status = RunStatus::Blocked;
6304                self.state.base_sync = Some(BaseSync {
6305                    tip,
6306                    behind,
6307                    attempts,
6308                    conflict: Some(why.clone()),
6309                    already_in: None,
6310                });
6311                self.state.event("land", why);
6312            }
6313        }
6314        if !self.state.base_sync_blocked() {
6315            self.state.base_sync_recovery.stop = None;
6316        }
6317        self.hold_base_sync_kind(stop_kind).await?;
6318        self.state.save()?;
6319        Ok(())
6320    }
6321
6322    /// Push a branch an earlier attempt rebased locally but never published,
6323    /// pinned to the remote tip read right after a successful fetch. Returns
6324    /// the reason when the run must stop; `None` when there was nothing to do
6325    /// (no remote copy, the same tip, or a remote copy this branch already
6326    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6327    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6328        // Task competitions publish only after the PR text gate, to their
6329        // public head; never resurrect a candidate branch on the remote.
6330        if self.state.task_pr_branch().is_some() {
6331            return None;
6332        }
6333        let repo = self.state.repo.clone();
6334        let remote = self.state.config.merge.remote.clone();
6335        let fetched = git::fetch(&repo, &remote, branch).await;
6336        if !matches!(&fetched, Ok(o) if o.ok()) {
6337            return None;
6338        }
6339        let branch_tracking = format!("{remote}/{branch}");
6340        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6341        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6342            return None;
6343        }
6344        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6345            .await
6346            .is_ok_and(|missing| missing.is_empty())
6347        {
6348            return Some(format!(
6349                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6350                 them",
6351                short(&theirs)
6352            ));
6353        }
6354        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6355            Ok(o) if o.ok() => {
6356                self.state
6357                    .event("land", format!("pushed rebased {branch} to {remote}"));
6358                None
6359            }
6360            Ok(o) => Some(format!(
6361                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6362                 someone may have pushed): {}",
6363                short(&theirs),
6364                o.stderr.chars().take(600).collect::<String>()
6365            )),
6366            Err(e) => Some(format!(
6367                "{branch} is rebased locally but could not be pushed: {e:#}"
6368            )),
6369        }
6370    }
6371
6372    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6373    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6374    /// whether it did.
6375    ///
6376    /// Checked only when the base is ahead of the branch. A failing check is
6377    /// "not proven" - the ordinary rebase path then decides - never a reason to
6378    /// stop the run.
6379    ///
6380    /// The remote copy of the branch is held to the same standard as the local
6381    /// one: if it carries a tip this worktree does not, that tip must itself be
6382    /// proven in the base, or nothing is settled (a pull request would
6383    /// otherwise be closed over commits nobody checked). The pull request is
6384    /// closed *before* the terminal status is saved; if that fails for a
6385    /// reason other than a refusal (no network, a `gh` error) the run is left
6386    /// `Blocked` with the reason as its conflict, which a resume retries -
6387    /// the same recovery a phantom conflict gets.
6388    async fn settle_already_in(
6389        &mut self,
6390        branch: &str,
6391        tip: &str,
6392        head: &str,
6393        attempts: usize,
6394        behind: usize,
6395    ) -> Result<bool> {
6396        let repo = self.state.repo.clone();
6397        let remote = self.state.config.merge.remote.clone();
6398        let start = self.state.base_commit.clone();
6399        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6400            Ok(Some(e)) => e,
6401            Ok(None) => return Ok(false),
6402            Err(e) => {
6403                tracing::warn!("already-in-base check for {branch}: {e:#}");
6404                return Ok(false);
6405            }
6406        };
6407        let mut verified = vec![head.to_owned()];
6408        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6409        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6410        let divergence = self
6411            .state
6412            .base_sync_recovery
6413            .stop
6414            .as_ref()
6415            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6416        if matches!(&fetched, Ok(o) if o.ok()) {
6417            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6418                Ok(theirs) if theirs != head => {
6419                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6420                        Ok(Some(_)) => verified.push(theirs),
6421                        _ => return Ok(false),
6422                    }
6423                }
6424                Err(_) if divergence => return Ok(false),
6425                _ => {}
6426            }
6427        } else if divergence
6428            && !matches!(
6429                git::remote_has_branch(&repo, &remote, &public_branch).await,
6430                Ok(false)
6431            )
6432        {
6433            // A failed fetch cannot discharge a recorded divergence.
6434            return Ok(false);
6435        }
6436        let base_branch = self.state.base_branch.clone();
6437        let message = format!(
6438            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6439             land",
6440            evidence.names(),
6441            evidence.proof.as_str()
6442        );
6443        let closed =
6444            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6445                .await;
6446        match closed {
6447            Ok(Ok(url)) => self
6448                .state
6449                .event("land", format!("closed {url}: superseded on {base_branch}")),
6450            Ok(Err(why)) => self
6451                .state
6452                .event("land", format!("did not close a pull request: {why}")),
6453            Err(e) => {
6454                let why = format!(
6455                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6456                     not be closed ({e:#}); resume to retry"
6457                );
6458                self.state.status = RunStatus::Blocked;
6459                self.state.base_sync = Some(BaseSync {
6460                    tip: tip.to_owned(),
6461                    behind,
6462                    attempts,
6463                    conflict: Some(why.clone()),
6464                    already_in: None,
6465                });
6466                self.state.event("land", why);
6467                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6468                    .await?;
6469                self.state.save()?;
6470                return Ok(true);
6471            }
6472        }
6473        self.state.status = RunStatus::AlreadyInBase;
6474        self.state.base_sync_recovery.stop = None;
6475        self.state.base_sync = Some(BaseSync {
6476            tip: tip.to_owned(),
6477            behind,
6478            attempts,
6479            conflict: None,
6480            already_in: Some(evidence),
6481        });
6482        self.state.event("land", message);
6483        self.state.save()?;
6484        self.settle_questions();
6485        Ok(true)
6486    }
6487
6488    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6489    /// last landed the winner on, once it has run, else the commit the run
6490    /// branched from.
6491    ///
6492    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6493    /// and `vote` all happen before there is a winner to rebase, so they
6494    /// compare every candidate against the branch point on purpose, and a
6495    /// base that moves after they are already done cannot change an answer
6496    /// they already gave.
6497    fn landing_base(&self) -> String {
6498        self.state
6499            .base_sync
6500            .as_ref()
6501            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6502    }
6503
6504    // ------------------------------------------------------- operator fix
6505
6506    /// Route specific, already-recorded review findings to a fixer for a
6507    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6508    /// entry point.
6509    ///
6510    /// Distinct from `review_loop`'s own fix step in three ways: it never
6511    /// runs a reviewer wave, it never spends review-round budget, and what
6512    /// happened is recorded as an [`OperatorFixRequest`] appended to
6513    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6514    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6515    /// and vote must never be rewritten to look like a manufactured blocking
6516    /// verdict.
6517    ///
6518    /// Only meaningful once review has actually concluded: `Ready` (handed
6519    /// off with findings still open, or simply concluded clean while minor
6520    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6521    /// gate failed). Everything else is refused: a run still in progress
6522    /// should simply be resumed, and a `Merged` run's branch has already
6523    /// landed — reopening *this* run's own record cannot change that, so the
6524    /// answer there is a fresh `magi review <branch>`.
6525    ///
6526    /// A real commit here re-verifies through a fresh, ordinary review-only
6527    /// run on the same branch ([`Self::review`]) rather than reopening this
6528    /// run's own `review_loop`: once any round in this run's history went
6529    /// clean, `review_conclusion` treats that as permanent by design (the
6530    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6531    /// way to force one more genuine reviewer wave out of *this* run without
6532    /// either rewriting history or weakening that guarantee for every other
6533    /// caller. A review-only run costs nothing extra — no implementation, no
6534    /// judging, no vote — and exercises the exact same review → verify →
6535    /// gate → (human) merge path, unmodified.
6536    pub async fn fix_selected(
6537        &mut self,
6538        ids: &[String],
6539        reason: &str,
6540        allow_stale: bool,
6541    ) -> Result<()> {
6542        let reason = reason.trim();
6543        if reason.is_empty() {
6544            bail!("a fix request needs a reason — that is the operator's own record of why");
6545        }
6546        if ids.is_empty() {
6547            bail!("no finding id given");
6548        }
6549        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6550            bail!(
6551                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6552                 has already concluded — can be given a targeted fix. A run still \
6553                 in progress should simply be resumed; a `merged` run's branch has \
6554                 already landed, so its answer is a fresh `magi review <branch>`, \
6555                 not reopening this run's own record",
6556                self.state.id,
6557                self.state.status.as_str()
6558            );
6559        }
6560        // Reassignment shares this claim through its atomic task save. Check
6561        // the canonical run identity inside it, before preflight or any await.
6562        let _claim = FixClaim::acquire(&self.state.dir())?;
6563        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6564        let home = crate::run::home();
6565        // The ordinary driver takes these same locks at admission. Keep the
6566        // execution lease through the fix, but never the owner lock across Git
6567        // or agent awaits.
6568        let execution = {
6569            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6570            let disk = RunState::load(&self.state.id)?;
6571            crate::pr_head::ensure_owner(&disk)?;
6572            anyhow::ensure!(
6573                disk.status == self.state.status && disk.released_to.is_none(),
6574                "run changed since it was loaded; reload before fixing"
6575            );
6576            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6577            anyhow::ensure!(
6578                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6579                "run {} is currently being worked on or its ownership is unknown",
6580                disk.id
6581            );
6582            let lease = crate::driver::maintenance(&home, &disk.id).context(
6583                "run is currently being worked on or its execution lease is unavailable",
6584            )?;
6585            self.state = disk;
6586            lease
6587        };
6588        let Some(winner) = self.state.winner().cloned() else {
6589            bail!("run {} has no winning candidate to fix", self.state.id);
6590        };
6591        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6592            bail!(
6593                "branch `{}` no longer exists; this run cannot be extended",
6594                winner.branch
6595            );
6596        }
6597        // Resolve every id before spending anything — an unknown id refuses
6598        // the whole request rather than silently dropping it — and dedup
6599        // while keeping the operator's own order.
6600        let mut seen = BTreeSet::new();
6601        let mut findings = Vec::new();
6602        let mut missing = Vec::new();
6603        for id in ids {
6604            if !seen.insert(id.clone()) {
6605                continue;
6606            }
6607            match self.state.finding(id) {
6608                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6609                    id: f.id.clone(),
6610                    severity: f.severity,
6611                    reviewer_vote: rec.vote,
6612                    round: round.round,
6613                    round_head: round.head.clone(),
6614                    reviewer: rec.reviewer,
6615                    agent: rec.agent.clone(),
6616                    file: f.file.clone(),
6617                    line: f.line,
6618                    title: f.title.clone(),
6619                    detail: f.detail.clone(),
6620                    outcome: OperatorFixOutcome::Pending,
6621                }),
6622                None => missing.push(id.clone()),
6623            }
6624        }
6625        if !missing.is_empty() {
6626            bail!(
6627                "unknown finding id(s): {}; nothing was changed",
6628                missing.join(", ")
6629            );
6630        }
6631
6632        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6633        let stale_details: Vec<(String, String)> = findings
6634            .iter()
6635            .filter(|f| f.round_head != head_at_request)
6636            .map(|f| (f.id.clone(), f.round_head.clone()))
6637            .collect();
6638        let stale = !stale_details.is_empty();
6639        if stale && !allow_stale {
6640            bail!(
6641                "the branch has moved since some finding(s) were raised — {} — now \
6642                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6643                stale_details
6644                    .iter()
6645                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6646                    .collect::<Vec<_>>()
6647                    .join(", "),
6648                short(&head_at_request)
6649            );
6650        }
6651
6652        let request = OperatorFixRequest {
6653            requested_at: Timestamp::now(),
6654            reason: reason.to_owned(),
6655            findings,
6656            head_at_request: head_at_request.clone(),
6657            allow_stale,
6658            stale,
6659            fix: None,
6660            result_head: None,
6661            follow_up_review_run: None,
6662        };
6663        self.state.event(
6664            "fix",
6665            format!(
6666                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6667                request.findings.len(),
6668                request
6669                    .findings
6670                    .iter()
6671                    .map(|f| f.id.as_str())
6672                    .collect::<Vec<_>>()
6673                    .join(", "),
6674            ),
6675        );
6676        // Recorded now, before any worktree work or the fixer call itself —
6677        // and re-saved at each checkpoint below: a crash at any point after
6678        // this (mid fixer call, mid follow-up review) must not lose the fact
6679        // that this was requested, for which findings, and why. Everything
6680        // past this point reads and writes through `request_index` rather
6681        // than a local variable, since `request` itself is moved here.
6682        self.state.operator_fixes.push(request);
6683        self.state.save()?;
6684        let request_index = self.state.operator_fixes.len() - 1;
6685
6686        // A fresh, dedicated worktree for this one call, never the winner's
6687        // own worktree in place: that one may already be gone (folded away),
6688        // and reusing it in place would leave the branch checked out there
6689        // when the follow-up review below tries to check it out again. Freed
6690        // immediately after, either way — but only once confirmed clean:
6691        // `worktree_remove` is a `git worktree remove --force`, which would
6692        // otherwise discard uncommitted work left there by the operator or
6693        // another process before this had a chance to even look at it.
6694        let repo = self.state.repo.clone();
6695        let coordination = self.coordinate(&repo).await?;
6696        if winner.worktree.exists() {
6697            // Lockfiles a rescue commit withheld stay untracked on purpose and
6698            // are already recorded; they are not the operator's work to protect.
6699            let dirty = git::git(
6700                &winner.worktree,
6701                &["status", "--porcelain", "--untracked-files=all"],
6702            )
6703            .await?;
6704            let only_withheld = dirty.lines().all(|l| {
6705                l.strip_prefix("?? ")
6706                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6707            });
6708            if !only_withheld {
6709                bail!(
6710                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6711                     discard them first",
6712                    winner.worktree.display()
6713                );
6714            }
6715            git::worktree_remove(&self.state.repo, &winner.worktree)
6716                .await
6717                .ok();
6718        }
6719        let fix_worktree = self.state.worktree_root().join("operator-fix");
6720        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6721        git::git(
6722            &self.state.repo,
6723            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6724        )
6725        .await
6726        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6727        if !git::is_clean(&fix_worktree).await? {
6728            git::worktree_remove(&self.state.repo, &fix_worktree)
6729                .await
6730                .ok();
6731            bail!(
6732                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6733                winner.branch
6734            );
6735        }
6736        let repo_for_setup = self.state.repo.clone();
6737        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6738            Ok(()) => {
6739                worktree_setup::prepare_with(
6740                    &self.state.config,
6741                    &repo_for_setup,
6742                    &fix_worktree,
6743                    crate::build_target::Coordination::Held(coordination.as_ref()),
6744                )
6745                .await
6746            }
6747            Err(e) => Err(e),
6748        };
6749        if let Err(e) = setup {
6750            git::worktree_remove(&self.state.repo, &fix_worktree)
6751                .await
6752                .ok();
6753            return Err(e);
6754        }
6755
6756        // This explicit operator request retries availability independently
6757        // of execute(); the previous call has already saved and cleaned up.
6758        self.state.resource_block = None;
6759
6760        let run_id = self.state.id.clone();
6761        let prompts = self.state.config.prompts.clone();
6762        let language = self.state.config.graph.language.clone();
6763        let sessions = self.state.config.graph.sessions;
6764        let artifacts = agent::artifacts_dir(&self.state.dir());
6765        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6766            .findings
6767            .iter()
6768            .map(|f| Finding {
6769                id: f.id.clone(),
6770                severity: f.severity,
6771                file: f.file.clone(),
6772                line: f.line,
6773                title: f.title.clone(),
6774                detail: f.detail.clone(),
6775            })
6776            .collect();
6777        let fix_prompt = prompt::operator_fix_in(
6778            &self.state.instruction,
6779            &finding_list,
6780            reason,
6781            &stale_details,
6782            &head_at_request,
6783            &language,
6784            &self.state.config.graph.github_language,
6785        );
6786        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6787        drop(coordination);
6788        let (job, seat, out) = self
6789            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6790                prompt: fix_prompt.clone(),
6791                spec,
6792                seat,
6793                cwd: fix_worktree.clone(),
6794                timeout,
6795                allow_write: true,
6796                sessions,
6797                artifacts: artifacts.clone(),
6798                stem: "operator-fix".to_owned(),
6799                handover: None,
6800            })
6801            .await;
6802        let agent_id = seat.agent.clone();
6803
6804        let mut fix = FixRecord {
6805            agent: agent_id,
6806            addressed: Vec::new(),
6807            rejected: Vec::new(),
6808            notes: String::new(),
6809            committed: false,
6810            failed: None,
6811            duration_ms: 0,
6812            continuation: None,
6813        };
6814        let mut final_seat = seat.clone();
6815        match out {
6816            AgentOutcome::Ok(o) => {
6817                fix.duration_ms = o.duration_ms;
6818                let parsed = verdict::extract_json::<FixReport>(&o.text);
6819                let incomplete_reason = match &parsed {
6820                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6821                        "the reply parsed, but it reported a command whose own CLI \
6822                         never confirmed an exit status"
6823                            .to_owned(),
6824                    ),
6825                    Ok(_) => None,
6826                    Err(e) => Some(e.to_string()),
6827                };
6828                match incomplete_reason {
6829                    None => {
6830                        let report = parsed.expect("checked Ok above");
6831                        fix.addressed = report.addressed;
6832                        fix.rejected = report.rejected;
6833                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6834                    }
6835                    Some(reason) => {
6836                        let (resumed_seat, resolved, failure, cont) = self
6837                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6838                            .await;
6839                        fix.duration_ms += cont.cumulative_wait_ms;
6840                        fix.continuation = Some(cont);
6841                        final_seat = resumed_seat;
6842                        match resolved {
6843                            Some(report) => {
6844                                fix.addressed = report.addressed;
6845                                fix.rejected = report.rejected;
6846                                fix.notes =
6847                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6848                            }
6849                            None => fix.failed = failure,
6850                        }
6851                    }
6852                }
6853            }
6854            AgentOutcome::Dropped(o) => {
6855                fix.duration_ms = o.duration_ms;
6856                let why = o
6857                    .dropped
6858                    .as_ref()
6859                    .map(|d| d.why.as_str())
6860                    .unwrap_or("the CLI ended the stream without delivering its answer");
6861                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6862            }
6863            AgentOutcome::Quota(o) => {
6864                self.state.quota.push(QuotaLoss::from_report(
6865                    final_seat.key.clone(),
6866                    "fix",
6867                    o.quota.as_ref(),
6868                ));
6869                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6870            }
6871            AgentOutcome::Failed(e) => fix.failed = Some(e),
6872            AgentOutcome::ResourceBlocked(e) => {
6873                fix.failed = Some(format!("the fixer was not started: {e}"));
6874            }
6875        }
6876        // Even a deferred call must rescue edits, release the worktree and
6877        // finalize its record below so an explicit `magi fix` can retry.
6878        if fix.continuation.is_none() {
6879            fix.continuation = Some(ContinuationRecord::not_needed());
6880        }
6881        self.state.seats.insert(final_seat.key.clone(), final_seat);
6882
6883        let rescue_message = format!(
6884            "magi: operator-selected fix ({}) (uncommitted work)",
6885            self.state.operator_fixes[request_index]
6886                .findings
6887                .iter()
6888                .map(|f| f.id.as_str())
6889                .collect::<Vec<_>>()
6890                .join(", ")
6891        );
6892        let repo = self.state.repo.clone();
6893        let coordination = self.coordinate(&repo).await?;
6894        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6895            self.state.note_withheld("fix", &r.withheld);
6896        }
6897        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6898        fix.committed = after != head_at_request;
6899        git::worktree_remove(&self.state.repo, &fix_worktree)
6900            .await
6901            .ok();
6902        drop(coordination);
6903
6904        self.state.event(
6905            "fix",
6906            match &fix.failed {
6907                Some(reason) => format!(
6908                    "operator fix: adoption report was lost ({reason}); {}",
6909                    if fix.committed {
6910                        "committed"
6911                    } else {
6912                        "NO new commit"
6913                    }
6914                ),
6915                None => format!(
6916                    "operator fix: {} addressed, {} rejected, {}",
6917                    fix.addressed.len(),
6918                    fix.rejected.len(),
6919                    if fix.committed {
6920                        "committed"
6921                    } else {
6922                        "NO new commit"
6923                    }
6924                ),
6925            },
6926        );
6927
6928        // Every selected finding gets an outcome — never left `Pending` once
6929        // the fixer's own turn is over. A report that never came back at all
6930        // marks every one of them `Unreported`, not silently "not addressed":
6931        // quota, a dropped stream, or an exhausted continuation are gaps in
6932        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6933        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6934        for f in &mut self.state.operator_fixes[request_index].findings {
6935            f.outcome = if fix.failed.is_some() {
6936                OperatorFixOutcome::Unreported
6937            } else if fix.addressed.contains(&f.id) {
6938                OperatorFixOutcome::Addressed
6939            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6940                OperatorFixOutcome::Rejected { why: r.why.clone() }
6941            } else {
6942                OperatorFixOutcome::Unreported
6943            };
6944        }
6945
6946        let committed = fix.committed;
6947        if committed {
6948            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6949        }
6950        self.state.operator_fixes[request_index].fix = Some(fix);
6951        // Saved again now that the fixer's own outcome is final, on top of
6952        // the save right after the request was first pushed above.
6953        self.state.save()?;
6954        if self.state.resource_block.is_some() {
6955            return self.stop_for_resource();
6956        }
6957
6958        if committed {
6959            self.state.event(
6960                "fix",
6961                format!(
6962                    "operator fix committed {}; opening a follow-up review-only run",
6963                    short(&after)
6964                ),
6965            );
6966            self.state.save()?;
6967            drop(execution);
6968            // The new review owns its own execution. Update only its audit link
6969            // afterwards, since publication may have changed the old record.
6970            let event_count = self.state.events.len();
6971            let save_follow_up = |state: &mut RunState| -> Result<()> {
6972                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
6973                let _execution = crate::driver::maintenance(&home, &state.id)?;
6974                let mut disk = RunState::load(&state.id)?;
6975                disk.events.extend(state.events.drain(event_count..));
6976                let follow_up = state.operator_fixes[request_index]
6977                    .follow_up_review_run
6978                    .clone();
6979                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
6980                disk.save()?;
6981                *state = disk;
6982                Ok(())
6983            };
6984            // The operator asked for the fix, and the follow-up serves whatever
6985            // task the run it follows served.
6986            let origin =
6987                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6988            match Self::review(
6989                &self.state.repo,
6990                &winner.branch,
6991                self.state.config.clone(),
6992                origin,
6993            )
6994            .await
6995            {
6996                Ok(mut follow_up) => {
6997                    follow_up.state.event(
6998                        "start",
6999                        format!(
7000                            "requested by an operator fix on run {} for finding(s) {}",
7001                            self.state.id,
7002                            self.state.operator_fixes[request_index]
7003                                .findings
7004                                .iter()
7005                                .map(|f| f.id.as_str())
7006                                .collect::<Vec<_>>()
7007                                .join(", "),
7008                        ),
7009                    );
7010                    follow_up.state.save()?;
7011                    let follow_up_id = follow_up.state.id.clone();
7012                    // The follow-up is a run like any other: it belongs to the
7013                    // task of the run it follows, or to one filed for it.
7014                    let adopted = match crate::direct::adopt(
7015                        &follow_up.state,
7016                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7017                    ) {
7018                        Ok(a) => a,
7019                        Err(e) => {
7020                            // An ownerless run must not spend agent calls; it
7021                            // stays saved, and `magi run --resume` adopts it.
7022                            self.state.event(
7023                                "fix",
7024                                format!(
7025                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7026                                ),
7027                            );
7028                            save_follow_up(&mut self.state)?;
7029                            return Ok(());
7030                        }
7031                    };
7032                    let executed = follow_up.execute().await;
7033                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7034                    if let Some(a) = adopted {
7035                        a.finish(&follow_up.state, executed);
7036                    }
7037                    if let Some(e) = failure {
7038                        self.state.event(
7039                            "fix",
7040                            format!(
7041                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7042                            ),
7043                        );
7044                    }
7045                    self.state.operator_fixes[request_index].follow_up_review_run =
7046                        Some(follow_up_id);
7047                }
7048                Err(e) => {
7049                    self.state.event(
7050                        "fix",
7051                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7052                    );
7053                }
7054            }
7055            save_follow_up(&mut self.state)?;
7056        }
7057
7058        Ok(())
7059    }
7060
7061    // --------------------------------------------------------------- review
7062
7063    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7064    /// names, in order, each at most once, moving on only when the call
7065    /// advances (an error, a quota hit or nothing usable - the same decision
7066    /// point `agent::chain_advances` is for the other chained roles).
7067    ///
7068    /// Each agent gets its own seat from `Runner::seat`: the same agent
7069    /// continues its conversation (the winner's own implementer seat when it
7070    /// is the winner's author, now that the competition is over), another
7071    /// takes a fresh one so the full prompt is sent again. A handover is
7072    /// recorded under `node`, which is what makes the fallback stick for the
7073    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7074    /// is returned, so an exhausted chain reads exactly like a single failed
7075    /// fixer: one quota loss, the same wording, the same refund. An earlier
7076    /// attempt's edits are left in the tree and judged, with the final
7077    /// attempt's, by what git says afterwards.
7078    ///
7079    /// Returns the job that produced the outcome, for `continue_fix_report`.
7080    async fn ask_fixer(
7081        &mut self,
7082        winner: &Candidate,
7083        node: &'static str,
7084        round: Option<usize>,
7085        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7086    ) -> (SeatJob, SeatState, AgentOutcome) {
7087        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7088        self.ask_fixer_among(attempts, node, round, None, build)
7089            .await
7090    }
7091
7092    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7093    /// worktree and a commit: before the next agent is asked after one that
7094    /// did not satisfy the call, the worktree is put back on that commit, so
7095    /// a failed agent's partial edits are not carried into the next one.
7096    async fn ask_fixer_among(
7097        &mut self,
7098        attempts: Vec<(AgentSpec, String)>,
7099        node: &'static str,
7100        round: Option<usize>,
7101        restore: Option<(&Path, &str)>,
7102        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7103    ) -> (SeatJob, SeatState, AgentOutcome) {
7104        let run_id = self.state.id.clone();
7105        let prompts = self.state.config.prompts.clone();
7106        let cache = self.state.config.cache_dir();
7107        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7108        let mut last = None;
7109        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7110            let seat = self.seat(&key, &spec.id);
7111            let mut job = build(spec.clone(), seat);
7112            if i > 0 {
7113                job.stem = format!("{}-{}", job.stem, spec.id);
7114            }
7115            let ctx = WaveCtx {
7116                carry_seats: false,
7117                pauses: Some((&self.pause, &self.interrupt)),
7118                run: &run_id,
7119                node,
7120                prompts: &prompts,
7121                cache: cache.as_deref(),
7122                round,
7123            };
7124            let (seat, out) =
7125                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7126            // A resource block never advances the chain: the chosen agent
7127            // was not asked, so it must be the one asked again on resume.
7128            let advances = match &out {
7129                AgentOutcome::Ok(o) => agent::output_advances(o),
7130                AgentOutcome::ResourceBlocked(_) => false,
7131                _ => true,
7132            };
7133            if let Some(next) = ids.get(i + 1)
7134                && advances
7135            {
7136                self.state.seats.insert(seat.key.clone(), seat.clone());
7137                let class =
7138                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7139                let reason = match &out {
7140                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7141                    other => fail_reason(other),
7142                };
7143                // A failed agent's edits must not reach the next one, and a
7144                // restore that did not work ends the chain: the call fails
7145                // and the caller's own (confirmed) restore decides.
7146                if let Some((wt, rev)) = restore
7147                    && let Err(e) = self.graft_restore(wt, rev).await
7148                {
7149                    let why =
7150                        format!("could not restore the worktree before the next fixer: {e:#}");
7151                    tracing::warn!("{why}");
7152                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7153                        AgentOutcome::ResourceBlocked(why)
7154                    } else {
7155                        AgentOutcome::Failed(why)
7156                    };
7157                    last = Some((job, seat, out));
7158                    break;
7159                }
7160                record_handover(
7161                    &mut self.state,
7162                    node,
7163                    &seat.key,
7164                    &spec.id,
7165                    next,
7166                    &class,
7167                    &reason,
7168                );
7169                continue;
7170            }
7171            last = Some((job, seat, out));
7172            break;
7173        }
7174        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7175        if let AgentOutcome::Quota(output) = &out
7176            && node != "graft"
7177        {
7178            // Graft is best effort: its caller records the loss and restores
7179            // the pre-graft tree, then proceeds to review and gate.
7180            // Every fallback was tried. Machine outages cannot be repaired by
7181            // spending a fix round; use each caller's resumable resource path.
7182            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7183            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7184            self.state.quota.push(loss);
7185            self.state.seats.insert(seat.key.clone(), seat.clone());
7186            self.state.status = RunStatus::Blocked;
7187            return (
7188                job,
7189                seat,
7190                AgentOutcome::ResourceBlocked(
7191                    "fixer unavailable; restore agent availability and resume".into(),
7192                ),
7193            );
7194        }
7195        (job, seat, out)
7196    }
7197
7198    /// The one repair a verification-only failure earns (see
7199    /// [`crate::recovery`]), before the first review round of a run that took
7200    /// a branch over.
7201    ///
7202    /// Saved as started *before* the fixer is called, so a resume never
7203    /// repairs twice; a start found on re-entry is rolled back to the commit
7204    /// it began from. A failed or unusable fixer leaves the tree as it was and
7205    /// the review goes on over it, so the first round's own verification
7206    /// reports the failure again. The failure is never carried into a round as
7207    /// a result: verification is re-run on whatever commit this leaves.
7208    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7209        use crate::recovery::{Mode, Repair};
7210        if !self.state.reviews.is_empty() {
7211            return Ok(());
7212        }
7213        let Some(mut rec) = self.state.recovery.clone() else {
7214            return Ok(());
7215        };
7216        if rec.mode != Mode::VerifyRepair {
7217            return Ok(());
7218        }
7219        let wt = winner.worktree.clone();
7220        let mut head = git::rev_parse(&wt, "HEAD").await?;
7221        match rec.repair.clone() {
7222            Repair::Done { .. } => return Ok(()),
7223            Repair::WaitingForRestore { before } => {
7224                self.graft_restore(&wt, &before).await?;
7225                head = before;
7226                rec.repair = Repair::NotStarted;
7227                self.state.recovery = Some(rec.clone());
7228                self.state.save()?;
7229            }
7230            Repair::Started { before } => {
7231                // Interrupted: the unfinished edits are not trusted.
7232                // An unconfirmed rollback blocks the run with `Started` kept,
7233                // so a resume retries it; the tree is never reviewed as is.
7234                if let Err(e) = self.graft_restore(&wt, &before).await {
7235                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7236                        return Err(e);
7237                    }
7238                    return self
7239                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7240                        .await;
7241                }
7242                rec.repair = Repair::Done {
7243                    before: before.clone(),
7244                    after: before,
7245                    committed: false,
7246                    failed: Some("interrupted; rolled back".to_owned()),
7247                };
7248                self.state
7249                    .event("recovery", "the repair was interrupted and rolled back");
7250                self.state.recovery = Some(rec);
7251                self.state.save()?;
7252                return Ok(());
7253            }
7254            Repair::NotStarted => {}
7255        }
7256        if crate::recovery::recheck(&mut rec, &head) {
7257            self.state.event("recovery", rec.summary());
7258            self.state.recovery = Some(rec);
7259            self.state.save()?;
7260            return Ok(());
7261        }
7262        rec.repair = Repair::Started {
7263            before: head.clone(),
7264        };
7265        self.state.recovery = Some(rec.clone());
7266        self.state.save()?;
7267
7268        let language = self.state.config.graph.language.clone();
7269        let sessions = self.state.config.graph.sessions;
7270        let artifacts = agent::artifacts_dir(&self.state.dir());
7271        let fix_prompt = prompt::recovery_fix(
7272            &self.state.instruction,
7273            &rec,
7274            self.state.config.graph.review_rounds,
7275            &language,
7276        );
7277        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7278        self.state.event(
7279            "recovery",
7280            format!(
7281                "repair: the fixer starts from the failed verification on {}",
7282                short(&head)
7283            ),
7284        );
7285        let (_job, seat, out) = self
7286            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7287                prompt: fix_prompt.clone(),
7288                spec,
7289                seat,
7290                cwd: wt.clone(),
7291                timeout,
7292                allow_write: true,
7293                sessions,
7294                artifacts: artifacts.clone(),
7295                stem: "fix-recovery".to_owned(),
7296                handover: None,
7297            })
7298            .await;
7299        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7300            rec.repair = Repair::WaitingForRestore { before: head };
7301            self.state.recovery = Some(rec);
7302            return self.stop_for_resource();
7303        }
7304        let failed = match &out {
7305            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7306            AgentOutcome::Quota(o) => {
7307                self.state.quota.push(QuotaLoss::from_report(
7308                    seat.key.clone(),
7309                    "fix",
7310                    o.quota.as_ref(),
7311                ));
7312                Some("rate limited (quota); the fixer could not run".to_owned())
7313            }
7314            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7315            AgentOutcome::Failed(e) => Some(e.clone()),
7316        };
7317        self.state.seats.insert(seat.key.clone(), seat);
7318        let coordination = self.coordinate(&wt).await?;
7319        let failed = match failed {
7320            // The agent's partial edits are not kept.
7321            Some(why) => {
7322                if let Err(e) = git::restore_to(&wt, &head).await {
7323                    return self
7324                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7325                        .await;
7326                }
7327                Some(why)
7328            }
7329            None => {
7330                if let Ok(r) = git::rescue_commit(
7331                    &wt,
7332                    "magi: recovery repair of the failed verification (uncommitted work)",
7333                )
7334                .await
7335                {
7336                    self.state.note_withheld("fix", &r.withheld);
7337                }
7338                None
7339            }
7340        };
7341        let after = git::rev_parse(&wt, "HEAD").await?;
7342        drop(coordination);
7343        self.state.event(
7344            "recovery",
7345            match &failed {
7346                Some(why) => format!("repair: nothing kept ({why})"),
7347                None if after != head => {
7348                    format!("repair: committed {}", short(&after))
7349                }
7350                None => "repair: the fixer made no commit".to_owned(),
7351            },
7352        );
7353        rec.repair = Repair::Done {
7354            before: head.clone(),
7355            committed: after != head,
7356            after,
7357            failed,
7358        };
7359        self.state.recovery = Some(rec);
7360        self.state.save()?;
7361        Ok(())
7362    }
7363
7364    /// A repair whose rollback could not be confirmed: the run is blocked and
7365    /// resumable, and the unconfirmed state is never reviewed.
7366    async fn stop_recovery(
7367        &mut self,
7368        mut rec: crate::recovery::RecoveryRecord,
7369        head: &str,
7370        why: String,
7371    ) -> Result<()> {
7372        // `Started` stays recorded: a resume retries the restore.
7373        rec.repair = crate::recovery::Repair::Started {
7374            before: head.to_owned(),
7375        };
7376        self.state.recovery = Some(rec);
7377        self.state
7378            .event("recovery", format!("repair could not be undone: {why}"));
7379        self.state.status = RunStatus::Blocked;
7380        self.state.save()?;
7381        bail!("recovery repair could not be rolled back: {why}")
7382    }
7383
7384    async fn review_loop(&mut self) -> Result<()> {
7385        if self.hold_base_sync().await? {
7386            return Ok(());
7387        }
7388        loop {
7389            if self
7390                .state
7391                .base_sync
7392                .as_ref()
7393                .is_some_and(|s| s.conflict.is_some())
7394            {
7395                return Ok(());
7396            }
7397            if self.catchup_repairable() {
7398                let record = self.state.reviews.last().expect("repairable round").clone();
7399                let winner = self
7400                    .state
7401                    .winner()
7402                    .cloned()
7403                    .context("catch-up repair has no winner")?;
7404                if !self.fix_review_round(&winner, record).await? {
7405                    return Ok(());
7406                }
7407            }
7408            self.review_loop_pass().await?;
7409            if !self.catchup_repairable() {
7410                return Ok(());
7411            }
7412        }
7413    }
7414
7415    /// Derive an owed catch-up repair from durable round evidence, including
7416    /// reentry after a crash before the fixer was dispatched.
7417    fn catchup_repairable(&self) -> bool {
7418        self.state.reviews.len() < self.state.config.graph.review_rounds
7419            && self.state.reviews.last().is_some_and(|r| {
7420                !r.clean
7421                    && r.blocking == 0
7422                    && r.fix.is_none()
7423                    && r.e2e_status() == E2eStatus::Failed
7424            })
7425    }
7426
7427    async fn review_loop_pass(&mut self) -> Result<()> {
7428        // A base that would not rebase is a person's decision, not a review
7429        // round: nothing here would change the answer, and reviewers and a
7430        // fixer would be spending real budget on a tree that cannot land
7431        // regardless of what they find.
7432        if self
7433            .state
7434            .base_sync
7435            .as_ref()
7436            .is_some_and(|s| s.conflict.is_some())
7437        {
7438            return Ok(());
7439        }
7440        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7441        // agent files with `magi task add` name the run that paid for it. The
7442        // prompt overlay is cloned alongside it because the waves borrow it
7443        // while `self` is mutably borrowed by the node's own bookkeeping.
7444        let run_id = self.state.id.clone();
7445        let prompts = self.state.config.prompts.clone();
7446        let Some(winner) = self.state.winner().cloned() else {
7447            return Ok(());
7448        };
7449        let granted_review = self
7450            .state
7451            .repair_grants
7452            .last()
7453            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7454            .cloned();
7455        let fresh_review = granted_review
7456            .as_ref()
7457            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7458        let max_rounds = granted_review
7459            .as_ref()
7460            .map_or(self.state.config.graph.review_rounds, |g| {
7461                g.review_start.saturating_add(1)
7462            });
7463        // A clean round, an exhausted round budget, or a stalled tree (see
7464        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7465        // they are recorded — recomputed here, not read off `status`, so a
7466        // reentry into a run that already stopped restates the identical
7467        // verdict instead of silently handing back whatever an earlier node
7468        // in this same walk clobbered `status` to (a solo-candidate
7469        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7470        // below runs an empty range once the budget is spent, and would
7471        // otherwise fall through without touching `status` at all.
7472        if let Some(status) =
7473            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7474        {
7475            // A reentry after a crash between the last round's save and
7476            // `stop_reviewing` reaches the hand-off here, not there.
7477            if status == RunStatus::Gating {
7478                self.record_contested_handoff();
7479            }
7480            self.state.status = status;
7481            self.state.save()?;
7482            return Ok(());
7483        }
7484        self.state.status = RunStatus::Reviewing;
7485        // A last recorded round whose own verification never resolved
7486        // (`ResourceBlocked` — the shared build cache, not the patch) is
7487        // never a concluded round, whatever the round budget says: starting
7488        // a fresh round on top of it would spend a whole new reviewer wave
7489        // re-reading an unchanged patch instead of just retrying the one
7490        // check that actually needs it, and once the budget is spent the
7491        // loop below has nothing left to do at all (its range is empty).
7492        // Retry that check directly instead, exactly the same retry
7493        // `stop_reviewing` already does for its own catch-up case.
7494        if !fresh_review
7495            && self.state.reviews.last().is_some_and(|r| {
7496                r.e2e_status() == E2eStatus::ResourceBlocked
7497                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7498            })
7499        {
7500            let shell = self.state.config.shell();
7501            return self
7502                .stop_unresolved_review(
7503                    "the last round's own verification never resolved",
7504                    &shell,
7505                    &winner.worktree,
7506                )
7507                .await;
7508        }
7509
7510        if granted_review.is_none() {
7511            self.recovery_repair(&winner).await?;
7512        }
7513        if self.resource_halt()? {
7514            return Ok(());
7515        }
7516
7517        let repo = self.state.repo.clone();
7518        let root = self.state.worktree_root();
7519        let language = self.state.config.graph.language.clone();
7520        let sessions = self.state.config.graph.sessions;
7521        let artifacts = self.merge_repair_artifacts();
7522        let base = self.landing_base();
7523        let base_short = short(&base);
7524        let reviewers = self.roles.reviewers.clone();
7525        let shell = self.state.config.shell();
7526
7527        for round in (self.state.reviews.len() + 1)..=max_rounds {
7528            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7529            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7530            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7531            // The prior round's own record, already persisted — never a
7532            // hand-carried variable of just its failing output: that is
7533            // exactly what let a round's e2e result drift out of sync with
7534            // which commit it was actually about (see `SCHEMA`'s doc for
7535            // schema 8). Judged against `head`, the commit reviewers are
7536            // about to look at now, so the summary always reads as "an
7537            // earlier head" here — this round's own patch has not been
7538            // checked yet.
7539            let prev_verification = self
7540                .state
7541                .reviews
7542                .last()
7543                .and_then(|r| r.verification_summary(&head));
7544            // Only the first round of a run that took a branch over: later
7545            // rounds have this run's own history.
7546            let prior_section = match (&self.state.recovery, round) {
7547                (Some(rec), 1) if self.state.reviews.is_empty() => {
7548                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7549                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7550                            Some(crate::recovery::head_of(
7551                                &git::diff(&winner.worktree, reviewed, "HEAD")
7552                                    .await
7553                                    .unwrap_or_default(),
7554                                crate::recovery::SINCE_DIFF_MAX,
7555                            ))
7556                        }
7557                        _ => None,
7558                    };
7559                    Some(prompt::recovery_review(rec, since.as_deref()))
7560                }
7561                _ => None,
7562            };
7563
7564            // Each reviewer gets its own detached checkout of exactly this
7565            // commit: nobody can perturb the winner's tree, and the fixer can
7566            // keep working without racing a reviewer.
7567            let mut jobs = Vec::new();
7568            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7569                self.coordinate(&repo).await?
7570            } else {
7571                None
7572            };
7573            for (r, spec) in reviewers.iter().cloned().enumerate() {
7574                let wt = root.join(format!("review-{}", r + 1));
7575                // `clean -fdx` in a reset wipes setup's products, so every
7576                // round sets the seat up again.
7577                if wt.exists() {
7578                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7579                } else {
7580                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7581                        None
7582                    } else {
7583                        self.coordinate(&repo).await?
7584                    };
7585                    git::worktree_add_detached(&repo, &wt, &head).await?;
7586                }
7587                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7588                    None
7589                } else {
7590                    self.coordinate(&repo).await?
7591                };
7592                self.setup_seat_worktree(
7593                    &repo,
7594                    &wt,
7595                    false,
7596                    coordination.as_ref().or(_setup_lease.as_ref()),
7597                )
7598                .await?;
7599                let seat_key = format!("review-{}", r + 1);
7600                // The seat starts the round on whoever answered it last, not
7601                // on the agent the spec names, so a failure is not re-paid.
7602                let spec = pick_start_spec(
7603                    &self.roles.reviewer_roster,
7604                    spec,
7605                    self.state.seat_history.get(&seat_key),
7606                );
7607                let seat = self.seat(&seat_key, &spec.id);
7608                jobs.push(SeatJob {
7609                    prompt: prompt::review(&prompt::ReviewCtx {
7610                        instruction: &self.state.instruction,
7611                        branch: &winner.branch,
7612                        base_short: &base_short,
7613                        stat: &stat,
7614                        patch: &patch,
7615                        verification: prev_verification.as_ref(),
7616                        prior: prior_section.as_deref(),
7617                        reviewers: reviewers.len(),
7618                        round,
7619                        rounds: max_rounds,
7620                        // A review-only run has no rankings, so nothing
7621                        // competed for this patch and the reviewer is told so.
7622                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7623                        lens: Lens::for_seat(r),
7624                        language: &language,
7625                        github_language: &self.state.config.graph.github_language,
7626                    }),
7627                    spec,
7628                    seat,
7629                    cwd: wt,
7630                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7631                    allow_write: false,
7632                    sessions,
7633                    artifacts: artifacts.clone(),
7634                    stem: format!("review-{round}-{}", r + 1),
7635                    handover: None,
7636                });
7637            }
7638
7639            drop(coordination);
7640            self.state.event(
7641                "review",
7642                format!(
7643                    "round {round}: {} reviewers on {}",
7644                    jobs.len(),
7645                    short(&head)
7646                ),
7647            );
7648            let mut quota_losses = Vec::new();
7649            let review_retries = self.state.config.graph.retries;
7650            let review_cache = self.state.config.cache_dir();
7651            let ctx = WaveCtx {
7652                carry_seats: true,
7653                pauses: Some((&self.pause, &self.interrupt)),
7654                run: &run_id,
7655                node: "review",
7656                prompts: &prompts,
7657                cache: review_cache.as_deref(),
7658                round: Some(round),
7659            };
7660            let results = ask_json_wave::<Review>(
7661                jobs,
7662                Arc::clone(&self.sem),
7663                review_retries,
7664                &self.roles.reviewer_roster,
7665                &ctx,
7666                &mut quota_losses,
7667                &mut self.state,
7668                &|_: &Review| Ok(()),
7669            )
7670            .await;
7671            if self.state.resource_block.is_some() {
7672                return self.stop_for_resource();
7673            }
7674            // Counted before the move below: how many of *this* round's
7675            // reviewer seats were lost to their own rate limit, as opposed to
7676            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7677            let round_quota_missing = quota_losses.len();
7678            self.state.quota.extend(quota_losses);
7679
7680            let mut records = Vec::new();
7681            let mut all_findings = Vec::new();
7682            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7683                let agent_id = seat.agent.clone();
7684                self.state.seats.insert(seat.key.clone(), seat);
7685                let mut record = ReviewRecord {
7686                    reviewer: r + 1,
7687                    agent: agent_id,
7688                    summary: String::new(),
7689                    findings: Vec::new(),
7690                    vote: None,
7691                    failed: None,
7692                    duration_ms: 0,
7693                    // Set for both outcomes: `failed: Some(_)` with
7694                    // `attempts > 0` is a seat every retry still lost, not a
7695                    // recovered one — only `failed: None` with `attempts > 0`
7696                    // reads as "answered after a nudge" (see this field's own
7697                    // doc).
7698                    attempts,
7699                };
7700                match res {
7701                    Ok((review, out)) => {
7702                        // Sanitized here, at the point every other piece of
7703                        // agent prose in this file is (candidate summaries,
7704                        // deliberation turns, vote reasons): a reviewer's own
7705                        // words are the one thing about it that could name
7706                        // it, and reconsideration below broadcasts this same
7707                        // summary and these same findings to every other
7708                        // seat on the panel.
7709                        record.summary =
7710                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7711                        record.vote = Some(review.vote);
7712                        record.duration_ms = out.duration_ms;
7713                        for (n, mut f) in review.findings.into_iter().enumerate() {
7714                            // ids are magi's, never the agent's: the fixer's
7715                            // adoption report is keyed by them.
7716                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7717                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7718                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7719                            // `file` is agent-supplied prose too, never
7720                            // checked against the real tree — the same
7721                            // exposure `title`/`detail` above have, just in
7722                            // a field easy to forget because it looks like a
7723                            // path rather than free text.
7724                            f.file = f
7725                                .file
7726                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7727                            all_findings.push(f.clone());
7728                            record.findings.push(f);
7729                        }
7730                        self.state.event(
7731                            "review",
7732                            format!(
7733                                "round {round}: reviewer {} voted {} with {} finding(s)",
7734                                r + 1,
7735                                review.vote.label(),
7736                                record.findings.len()
7737                            ),
7738                        );
7739                    }
7740                    Err(e) => {
7741                        record.failed = Some(e.to_string());
7742                        self.state.event(
7743                            "review",
7744                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7745                        );
7746                    }
7747                }
7748                records.push(record);
7749            }
7750
7751            // Tally the round's votes and, if they split, spend the one
7752            // round of reconsideration the split -> deliberate -> revote
7753            // shape `judge`/`vote` use for the panel, sized down to what a
7754            // read-only review round can afford: one round, and a revote
7755            // rather than an argument, because the panel already wrote its
7756            // reasoning down as findings the first time around.
7757            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7758            let vote_split =
7759                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7760            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7761            if vote_split {
7762                self.state.event(
7763                    "review",
7764                    format!(
7765                        "round {round}: votes split ({}) — one round of reconsideration",
7766                        initial_votes
7767                            .iter()
7768                            .map(|v| v.label())
7769                            .collect::<Vec<_>>()
7770                            .join(", ")
7771                    ),
7772                );
7773                // Seats read every seat's findings and votes, still numbered
7774                // and never named — the same anonymity `review` itself keeps.
7775                let panel: Vec<ReviewSeatReport<'_>> = records
7776                    .iter()
7777                    .filter_map(|r| {
7778                        r.vote.map(|vote| ReviewSeatReport {
7779                            reviewer: r.reviewer,
7780                            vote,
7781                            summary: &r.summary,
7782                            findings: &r.findings,
7783                        })
7784                    })
7785                    .collect();
7786
7787                let mut jobs = Vec::new();
7788                let mut seats_at = Vec::new();
7789                for (r, spec) in reviewers.iter().cloned().enumerate() {
7790                    // A seat with no initial vote has nothing to reconsider
7791                    // from and stays absent, the same as it stayed absent
7792                    // from `panel` above.
7793                    if records[r].vote.is_none() {
7794                        continue;
7795                    }
7796                    let wt = root.join(format!("review-{}", r + 1));
7797                    let seat_key = format!("review-{}", r + 1);
7798                    let spec = self.occupant(&seat_key, spec);
7799                    let seat = self.seat(&seat_key, &spec.id);
7800                    // A seat with no live session has already forgotten the
7801                    // initial review's prompt — restate the patch it is
7802                    // voting on, the same as `deliberate`/`vote` do for a
7803                    // judge in the same position.
7804                    // The panel already carries this seat's own review and
7805                    // vote, so restating the patch makes the prompt whole for
7806                    // a seat handed to another agent.
7807                    let build = |with_patch: bool| {
7808                        prompt::review_reconsider(&ReviewReconsiderCtx {
7809                            instruction: &self.state.instruction,
7810                            reviewer: r + 1,
7811                            lens: Lens::for_seat(r),
7812                            panel: &panel,
7813                            patch: with_patch.then_some(ReviewPatch {
7814                                branch: &winner.branch,
7815                                base_short: &base_short,
7816                                stat: &stat,
7817                                patch: &patch,
7818                            }),
7819                            round,
7820                            rounds: max_rounds,
7821                            language: &language,
7822                        })
7823                    };
7824                    let full = build(true);
7825                    let prompt = if has_context(&spec, &seat, sessions) {
7826                        build(false)
7827                    } else {
7828                        full.clone()
7829                    };
7830                    jobs.push(SeatJob {
7831                        prompt,
7832                        spec,
7833                        seat,
7834                        cwd: wt,
7835                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7836                        allow_write: false,
7837                        sessions,
7838                        artifacts: artifacts.clone(),
7839                        stem: format!("review-{round}-reconsider-{}", r + 1),
7840                        handover: Some(full),
7841                    });
7842                    seats_at.push(r);
7843                }
7844
7845                let mut recon_quota_losses = Vec::new();
7846                let recon_cache = self.state.config.cache_dir();
7847                let recon_ctx = WaveCtx {
7848                    carry_seats: true,
7849                    pauses: Some((&self.pause, &self.interrupt)),
7850                    run: &run_id,
7851                    node: "review",
7852                    prompts: &prompts,
7853                    cache: recon_cache.as_deref(),
7854                    round: Some(round),
7855                };
7856                let recon_results = ask_json_wave::<ReviewRevote>(
7857                    jobs,
7858                    Arc::clone(&self.sem),
7859                    review_retries,
7860                    &self.roles.reviewer_roster,
7861                    &recon_ctx,
7862                    &mut recon_quota_losses,
7863                    &mut self.state,
7864                    &|_: &ReviewRevote| Ok(()),
7865                )
7866                .await;
7867                if self.state.resource_block.is_some() {
7868                    return self.stop_for_resource();
7869                }
7870                self.state.quota.extend(recon_quota_losses);
7871
7872                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7873                    let agent_id = seat.agent.clone();
7874                    self.state.seats.insert(seat.key.clone(), seat);
7875                    let mut rec = ReviewRevoteRecord {
7876                        reviewer: r + 1,
7877                        agent: agent_id,
7878                        vote: None,
7879                        reason: String::new(),
7880                        failed: None,
7881                    };
7882                    match res {
7883                        Ok((rv, _)) => {
7884                            rec.vote = Some(rv.vote);
7885                            rec.reason =
7886                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7887                            self.state.event(
7888                                "review",
7889                                format!(
7890                                    "round {round}: reviewer {} revoted {}",
7891                                    r + 1,
7892                                    rv.vote.label()
7893                                ),
7894                            );
7895                        }
7896                        Err(e) => {
7897                            rec.failed = Some(e.to_string());
7898                            self.state.event(
7899                                "review",
7900                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7901                            );
7902                        }
7903                    }
7904                    reconsideration.push(rec);
7905                }
7906            } else if initial_votes.len() > 1 {
7907                self.state.event(
7908                    "review",
7909                    format!(
7910                        "round {round}: votes agreed ({}) — no reconsideration",
7911                        initial_votes[0].label()
7912                    ),
7913                );
7914            }
7915
7916            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7917            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7918            // A round that already has a blocking finding and a round left to
7919            // try is going back to the fixer no matter what `verify.e2e`
7920            // says, so running it first only spends the loop's slowest step
7921            // (minutes, for a Rust repo's full test suite) on a head about
7922            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7923            // runs once a round has no blocking findings left (see
7924            // `round_is_clean`, which a deferred — empty — `e2e` can never
7925            // satisfy since `blocking` is nonzero whenever this branch is
7926            // taken), and `stop_reviewing` forces a real run before it will
7927            // ever read a deferred round as green.
7928            let defer_e2e =
7929                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7930            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7931                let reason =
7932                    format!("{blocking} blocking finding(s) already required a fix this round");
7933                self.state.event(
7934                    "verify",
7935                    format!(
7936                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7937                         {}); it will run once a round has none left",
7938                        short(&head)
7939                    ),
7940                );
7941                (Vec::new(), false, true, Some(reason))
7942            } else {
7943                let e2e_commands = self.state.config.verify.e2e.clone();
7944                let cache_dir = self.state.config.cache_dir();
7945                let context = format!("round {round}");
7946                let wait = self.repository_wait();
7947                let (e2e, verify_retried) = with_cache_lease(
7948                    &mut self.state,
7949                    cache_dir.as_deref(),
7950                    "e2e",
7951                    "e2e",
7952                    &winner.worktree,
7953                    &head,
7954                    verify_timeout,
7955                    &context,
7956                    &wait,
7957                    |state, budget| {
7958                        let shell = shell.clone();
7959                        let e2e_commands = e2e_commands.clone();
7960                        let worktree = winner.worktree.clone();
7961                        let context = context.clone();
7962                        let winner = winner.clone();
7963                        async move {
7964                            if !e2e_commands.is_empty() {
7965                                // The suite certifies one SHA. Format before it
7966                                // runs, or the commit `pre_gate` makes at the
7967                                // gate owes the whole suite again.
7968                                Self::run_pre_gate(state, &winner).await;
7969                            }
7970                            run_e2e_with_retry(
7971                                state,
7972                                &shell,
7973                                &e2e_commands,
7974                                &worktree,
7975                                budget,
7976                                &context,
7977                                Some(round),
7978                            )
7979                            .await
7980                        }
7981                    },
7982                )
7983                .await?;
7984                (e2e, verify_retried, false, None)
7985            };
7986
7987            let expected = records.len();
7988            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7989            let incomplete = answered < expected;
7990            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7991            let policy = self.state.config.graph.incomplete_review;
7992            let clean = round_is_clean(
7993                blocking,
7994                e2e_ok,
7995                answered,
7996                expected,
7997                round_quota_missing,
7998                policy,
7999            );
8000
8001            let mut round_record = ReviewRound {
8002                round,
8003                head: head.clone(),
8004                verified_head: None,
8005                verified_at: None,
8006                reviews: records,
8007                e2e,
8008                verify_retried,
8009                e2e_deferred,
8010                e2e_defer_reason,
8011                fix: None,
8012                blocking,
8013                answered,
8014                expected,
8015                clean,
8016                progressed: false,
8017                vote_split,
8018                reconsideration,
8019                verdict: None,
8020            };
8021            // The final vote per seat is its revote where reconsideration
8022            // ran and answered, its initial vote otherwise — the same
8023            // fallback `tally` uses for a judge whose private vote failed.
8024            round_record.verdict = ReviewVote::worst(
8025                round_record
8026                    .final_votes()
8027                    .into_iter()
8028                    .map(|(_, _, vote)| vote),
8029            );
8030            // Which commit and when magi actually attempted to check —
8031            // known the moment a command was dispatched against `head`,
8032            // whether or not it finished: a resource-blocked attempt still
8033            // targeted a specific commit at a specific time, and leaving
8034            // that unrecorded is exactly what made `verification_summary`
8035            // report a fresh attempt as "commit unknown ... recorded before
8036            // this was tracked", indistinguishable from a genuinely old,
8037            // untracked record. Only a deferred or unconfigured round never
8038            // ran at all and has nothing to record — see
8039            // `ReviewRound::verified_head`'s own doc.
8040            if !matches!(
8041                round_record.e2e_status(),
8042                E2eStatus::Deferred | E2eStatus::NotConfigured
8043            ) {
8044                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8045                // mechanical fixes before the commands ran.
8046                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8047                round_record.verified_at = Some(Timestamp::now());
8048            }
8049
8050            if incomplete {
8051                let missing: Vec<String> = round_record
8052                    .reviews
8053                    .iter()
8054                    .filter(|r| r.failed.is_some())
8055                    .map(|r| format!("review-{}", r.reviewer))
8056                    .collect();
8057                self.state.event(
8058                    "review",
8059                    format!(
8060                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8061                        missing.join(", ")
8062                    ),
8063                );
8064            }
8065
8066            if clean {
8067                self.state.event(
8068                    "review",
8069                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8070                        format!(
8071                            "round {round}: clean (warn policy, incomplete panel) — no \
8072                             blocking findings from the seats that answered, verification green"
8073                        )
8074                    } else if incomplete {
8075                        format!(
8076                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8077                             quorum) — no blocking findings from the seats that answered, \
8078                             verification green",
8079                            expected - answered
8080                        )
8081                    } else {
8082                        format!("round {round}: clean — no blocking findings, verification green")
8083                    },
8084                );
8085                self.state.reviews.push(round_record);
8086                self.state.status = RunStatus::Gating;
8087                self.state.save()?;
8088                return Ok(());
8089            }
8090
8091            // Nothing was raised and verification passed, but not every seat
8092            // answered and `round_is_clean` still refused to call it clean —
8093            // either a seat is missing for a reason other than its own quota
8094            // (a crash, a timeout, unparsable output — worth another try), or
8095            // every seat that could have answered lost its quota and nobody
8096            // is left to decide on: re-review rather than send the fixer
8097            // after a round with nothing to fix.
8098            if incomplete && blocking == 0 && e2e_ok {
8099                self.state.reviews.push(round_record);
8100                self.state.save()?;
8101                if round == max_rounds {
8102                    self.state.status = RunStatus::Blocked;
8103                    self.state.event(
8104                        "review",
8105                        format!(
8106                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8107                             refusing to call it clean",
8108                            expected - answered
8109                        ),
8110                    );
8111                    return Ok(());
8112                }
8113                continue;
8114            }
8115
8116            // Nothing for the fixer to act on (`blocking == 0`) and the only
8117            // reason this round is not clean is that magi itself never got
8118            // a command to run — the shared build cache, not the patch (see
8119            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8120            // the fixer would invite a change to appease contention that has
8121            // nothing to do with the diff, and would leave this attempt
8122            // sitting in the next round's prompt as if it were about an
8123            // earlier, superseded commit rather than what it actually is:
8124            // the same head, still waiting to be checked. Wait for it the
8125            // same way the final round's own contention is already handled,
8126            // whatever round this happens to be.
8127            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8128                self.state.reviews.push(round_record);
8129                return self
8130                    .stop_unresolved_review(
8131                        "the round's own verification could not run",
8132                        &shell,
8133                        &winner.worktree,
8134                    )
8135                    .await;
8136            }
8137
8138            if round == max_rounds {
8139                self.state.reviews.push(round_record);
8140                return self
8141                    .stop_reviewing(
8142                        &format!(
8143                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8144                        ),
8145                        &shell,
8146                        &winner.worktree,
8147                    )
8148                    .await;
8149            }
8150
8151            if !self.fix_review_round(&winner, round_record).await? {
8152                return Ok(());
8153            }
8154        }
8155        Ok(())
8156    }
8157
8158    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8159    /// False means admission or continuation policy stopped the review loop.
8160    async fn fix_review_round(
8161        &mut self,
8162        winner: &Candidate,
8163        mut round_record: ReviewRound,
8164    ) -> Result<bool> {
8165        let round = round_record.round;
8166        let shell = self.state.config.shell();
8167        let step = self.run_fix_round(winner, &mut round_record).await?;
8168        if matches!(step, FixStep::Resource) {
8169            self.stop_for_resource()?;
8170            return Ok(false);
8171        }
8172        if self.state.reviews.len() < round {
8173            self.state.reviews.push(round_record);
8174        } else {
8175            self.state.reviews[round - 1] = round_record;
8176        }
8177        self.state.save()?;
8178
8179        // The fixer's own report never came back this round, even after
8180        // `continue_fix_report`'s own budget was spent on it — not an
8181        // ordinary "no report" (dropped stream, quota, plain failure),
8182        // which already reads that way and is left to the existing round
8183        // budget. Stopping here, rather than opening another round, is
8184        // what keeps a next reviewer/fixer wave from ever being
8185        // dispatched onto `winner.worktree` while whatever the seat's
8186        // last call may still have running there is unaccounted for: no
8187        // process liveness check exists (and none is being added — see
8188        // AGENTS.md/this task's own scope), so the only way to honour
8189        // "nothing starts before a valid report returns" is to not start
8190        // anything further on this worktree from this run at all.
8191        if matches!(step, FixStep::Recorded { report_lost: true }) {
8192            self.stop_reviewing(
8193                "the fixer's adoption report never came back, even after resuming its \
8194                         own seat; refusing to start another round against the same worktree \
8195                         while that is unresolved",
8196                &shell,
8197                &winner.worktree,
8198            )
8199            .await?;
8200            return Ok(false);
8201        }
8202
8203        let streak = self
8204            .state
8205            .reviews
8206            .iter()
8207            .rev()
8208            .take_while(|r| !r.progressed)
8209            .count();
8210        if streak >= STAGNANT_LIMIT {
8211            self.stop_reviewing(
8212                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8213                &shell,
8214                &winner.worktree,
8215            )
8216            .await?;
8217            return Ok(false);
8218        }
8219        Ok(true)
8220    }
8221
8222    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8223    async fn run_fix_round(
8224        &mut self,
8225        winner: &Candidate,
8226        round_record: &mut ReviewRound,
8227    ) -> Result<FixStep> {
8228        let round = round_record.round;
8229        let max_rounds = self.state.config.graph.review_rounds;
8230        let run_id = self.state.id.clone();
8231        let prompts = self.state.config.prompts.clone();
8232        let language = self.state.config.graph.language.clone();
8233        let sessions = self.state.config.graph.sessions;
8234        let artifacts = self.merge_repair_artifacts();
8235        let base = self.landing_base();
8236        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8237        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8238        let this_round_verification = round_record.verification_summary(&head);
8239        let all_findings: Vec<_> = round_record
8240            .reviews
8241            .iter()
8242            .flat_map(|r| r.findings.iter().cloned())
8243            .collect();
8244        // Fix. The winner's own implementer seat continues its conversation:
8245        // the competition is over, so context is pure benefit now.
8246        let blocking_findings: Vec<_> = all_findings
8247            .iter()
8248            .filter(|f| f.severity.blocks())
8249            .cloned()
8250            .collect();
8251        let fix_prompt = prompt::fix_in(
8252            &self.state.instruction,
8253            &blocking_findings,
8254            this_round_verification.as_ref(),
8255            round,
8256            max_rounds,
8257            &language,
8258            &self.state.config.graph.github_language,
8259        );
8260        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8261        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8262        let (job, seat, out) = self
8263            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8264                prompt: fix_prompt.clone(),
8265                spec,
8266                seat,
8267                cwd: winner.worktree.clone(),
8268                timeout,
8269                allow_write: true,
8270                sessions,
8271                artifacts: artifacts.clone(),
8272                stem: format!("fix-{round}"),
8273                handover: None,
8274            })
8275            .await;
8276        // Not asked: the round is not recorded (so a resume repeats it),
8277        // no fixer was handed over to, and the seat is left as it was.
8278        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8279            return Ok(FixStep::Resource);
8280        }
8281        let agent_id = seat.agent.clone();
8282
8283        let mut fix = FixRecord {
8284            agent: agent_id,
8285            addressed: Vec::new(),
8286            rejected: Vec::new(),
8287            notes: String::new(),
8288            committed: false,
8289            failed: None,
8290            duration_ms: 0,
8291            continuation: None,
8292        };
8293        let mut continuation = ContinuationRecord::not_needed();
8294        let mut final_seat = seat.clone();
8295        match out {
8296            AgentOutcome::Ok(o) => {
8297                fix.duration_ms = o.duration_ms;
8298                let parsed = verdict::extract_json::<FixReport>(&o.text);
8299                // A parsed report standing next to a command this same
8300                // reply's own CLI never confirmed the exit status of is
8301                // not a resolved answer — the identical `CommandEvidence`
8302                // `state.jobs` renders, read here instead of only on
8303                // display, per the completion judgment and the shown
8304                // record needing to agree.
8305                let incomplete_reason = match &parsed {
8306                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8307                        "the reply parsed, but it reported a command whose own CLI never \
8308                             confirmed an exit status"
8309                            .to_owned(),
8310                    ),
8311                    Ok(_) => None,
8312                    Err(e) => Some(e.to_string()),
8313                };
8314                match incomplete_reason {
8315                    None => {
8316                        let report = parsed.expect("checked Ok above");
8317                        fix.addressed = report.addressed;
8318                        fix.rejected = report.rejected;
8319                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8320                    }
8321                    Some(reason) => {
8322                        let (resumed_seat, resolved, failure, cont) = self
8323                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8324                            .await;
8325                        fix.duration_ms += cont.cumulative_wait_ms;
8326                        continuation = cont;
8327                        final_seat = resumed_seat;
8328                        match resolved {
8329                            Some(report) => {
8330                                fix.addressed = report.addressed;
8331                                fix.rejected = report.rejected;
8332                                fix.notes =
8333                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8334                            }
8335                            None => fix.failed = failure,
8336                        }
8337                    }
8338                }
8339            }
8340            // The CLI's raw error JSON is not a fix report to parse.
8341            AgentOutcome::Dropped(o) => {
8342                fix.duration_ms = o.duration_ms;
8343                let why = o
8344                    .dropped
8345                    .as_ref()
8346                    .map(|d| d.why.as_str())
8347                    .unwrap_or("the CLI ended the stream without delivering its answer");
8348                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8349            }
8350            AgentOutcome::Quota(o) => {
8351                self.state.quota.push(QuotaLoss::from_report(
8352                    final_seat.key.clone(),
8353                    "fix",
8354                    o.quota.as_ref(),
8355                ));
8356                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8357            }
8358            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8359        }
8360        if self.state.resource_block.is_some() {
8361            self.state.seats.insert(final_seat.key.clone(), final_seat);
8362            return Ok(FixStep::Resource);
8363        }
8364        fix.continuation = Some(continuation);
8365        self.state.seats.insert(final_seat.key.clone(), final_seat);
8366        let coordination = self.coordinate(&winner.worktree).await?;
8367        if let Ok(r) = git::rescue_commit(
8368            &winner.worktree,
8369            &format!("magi: review round {round} fixes (uncommitted work)"),
8370        )
8371        .await
8372        {
8373            self.state.note_withheld("fix", &r.withheld);
8374        }
8375        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8376        fix.committed = after != before;
8377        // Judged by what `git` says moved against base, never by the
8378        // fixer's own `addressed`/`rejected` count — see
8379        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8380        // `patch` snapshot above: swallowing this error would default
8381        // `diff_after` to empty, which almost always differs from a
8382        // non-empty `patch` and reads as "progressed" — exactly backwards
8383        // for a `git` failure the stagnation check cannot see through.
8384        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8385        drop(coordination);
8386        let progressed = diff_after != patch;
8387        let commit_note = if fix.committed {
8388            "committed"
8389        } else {
8390            "NO new commit"
8391        };
8392        let tree_note = if progressed {
8393            "changed vs base"
8394        } else {
8395            "unchanged vs base"
8396        };
8397        self.state.event(
8398            "fix",
8399            match &fix.failed {
8400                // Distinct on purpose from "0 addressed, 0 rejected": the
8401                // fixer's own diff still landed (blocking counts do keep
8402                // falling round over round), only its adoption report did
8403                // not come back, so this must never read like every
8404                // finding was reviewed and declined.
8405                Some(reason) => {
8406                    format!(
8407                        "round {round}: fixer's adoption report was lost ({reason}); \
8408                             {commit_note}, tree {tree_note}"
8409                    )
8410                }
8411                None => format!(
8412                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8413                         {tree_note}{}",
8414                    fix.addressed.len(),
8415                    fix.rejected.len(),
8416                    if continuation.outcome == ContinuationOutcome::Resumed {
8417                        format!(
8418                            " (adoption report recovered after {} continuation(s))",
8419                            continuation.attempts
8420                        )
8421                    } else {
8422                        String::new()
8423                    },
8424                ),
8425            },
8426        );
8427        round_record.fix = Some(fix);
8428        round_record.progressed = progressed;
8429        Ok(FixStep::Recorded {
8430            report_lost: matches!(
8431                continuation.outcome,
8432                ContinuationOutcome::Exhausted
8433                    | ContinuationOutcome::QuotaLost
8434                    | ContinuationOutcome::NoSession
8435            ),
8436        })
8437    }
8438
8439    /// Decide, from the last recorded round's own verification, whether
8440    /// stopping the review loop is a hand-off or a genuine block.
8441    ///
8442    /// Called once the loop has given up trying — the round budget is spent,
8443    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8444    /// findings still open, never while a round is still clean or the
8445    /// incomplete-panel case handled inline above. Gate and e2e are facts
8446    /// about the tree; a lingering review finding is an opinion, and this
8447    /// workload's own `magi stats` puts reviewer precision low enough
8448    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8449    /// must not by itself stand between a green, verified change and the
8450    /// human who decides what to do with it. A red e2e is not an opinion, so
8451    /// that case still blocks, with the failing command and a tail of its
8452    /// output recorded here rather than left in `run.json` for someone to go
8453    /// find.
8454    ///
8455    /// A round that deferred its own e2e (see [`Config::graph`]'s
8456    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8457    /// only because nothing ran, and treating an empty list as a passing one
8458    /// here is exactly the "deferred painted green" bug this function exists
8459    /// to not have. When the last round's own verification never resolved —
8460    /// deferred on purpose, or a real attempt the shared build cache blocked
8461    /// — this makes (or retries) the real run, on the actual worktree this
8462    /// loop is about to stop touching, before deciding anything. A
8463    /// resource-blocked attempt is likewise never read as either green or
8464    /// red: it is evidence about the machine, not the patch (see
8465    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8466    /// blocked cache leaves this call without deciding rather than guessing
8467    /// — the caller retries on a later reentry.
8468    /// Record, once, that the review loop handed off over a blocking finding
8469    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8470    /// `land` asks the owner even with `land_approval` off. Called from every
8471    /// path that concludes `Gating`; a reentry keeps the first record.
8472    fn record_contested_handoff(&mut self) {
8473        if self.state.contested_handoff.is_some() {
8474            return;
8475        }
8476        let Some(contested) = self
8477            .state
8478            .reviews
8479            .last()
8480            .and_then(ReviewRound::contested_handoff)
8481        else {
8482            return;
8483        };
8484        self.state.event(
8485            "review",
8486            format!(
8487                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8488                 wait for the owner's approval",
8489                contested.findings.len(),
8490                contested.rejecters.len()
8491            ),
8492        );
8493        self.state.contested_handoff = Some(contested);
8494    }
8495
8496    async fn stop_unresolved_review(
8497        &mut self,
8498        why: &str,
8499        shell: &[String],
8500        worktree: &Path,
8501    ) -> Result<()> {
8502        self.stop_reviewing_inner(why, shell, worktree, true).await
8503    }
8504
8505    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8506        self.stop_reviewing_inner(why, shell, worktree, false).await
8507    }
8508
8509    async fn stop_reviewing_inner(
8510        &mut self,
8511        why: &str,
8512        shell: &[String],
8513        worktree: &Path,
8514        repairable: bool,
8515    ) -> Result<()> {
8516        let round_idx = self.state.reviews.len() - 1;
8517        // A deferred round and a resource-blocked one are the same shape
8518        // here: neither has a real result yet, and both get one more
8519        // attempt. Read off `e2e_status` — the single source for this —
8520        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8521        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8522        // still retries instead of being read as a settled result the
8523        // instant it stops being empty.
8524        let needs_catchup_run = matches!(
8525            self.state.reviews[round_idx].e2e_status(),
8526            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8527        );
8528        if needs_catchup_run {
8529            let round = self.state.reviews[round_idx].round;
8530            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8531            let commands = self.state.config.verify.e2e.clone();
8532            let before_head = git::rev_parse(worktree, "HEAD").await?;
8533            let winner = self.state.winner().cloned();
8534            let cache_dir = self.state.config.cache_dir();
8535            let context = format!(
8536                "round {round}: verification unresolved, catching up before the final decision"
8537            );
8538            let wait = self.repository_wait();
8539            let (outcomes, verify_retried) = with_cache_lease(
8540                &mut self.state,
8541                cache_dir.as_deref(),
8542                "e2e",
8543                "e2e",
8544                worktree,
8545                &before_head,
8546                timeout,
8547                &context,
8548                &wait,
8549                |state, budget| {
8550                    let shell = shell.to_vec();
8551                    let commands = commands.clone();
8552                    let context = context.clone();
8553                    async move {
8554                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8555                            // Same reason as in the round itself: format before
8556                            // the suite, not after it.
8557                            Self::run_pre_gate(state, &winner).await;
8558                        }
8559                        run_e2e_with_retry(
8560                            state,
8561                            &shell,
8562                            &commands,
8563                            worktree,
8564                            budget,
8565                            &context,
8566                            Some(round),
8567                        )
8568                        .await
8569                    }
8570                },
8571            )
8572            .await?;
8573            // After `pre_gate`: the commit the commands actually ran against.
8574            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8575            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8576                self.state.record_base_progress(&attempted_head);
8577            }
8578            let last = &mut self.state.reviews[round_idx];
8579            last.e2e = outcomes;
8580            last.verify_retried = verify_retried;
8581            // Always the commit and time this attempt actually targeted,
8582            // whether or not it happens to equal the reviewed `head` and
8583            // whether or not a command finished — see
8584            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8585            // attempt is recorded too, so a later reader sees "attempted
8586            // again at T2" rather than silence.
8587            last.verified_head = Some(attempted_head);
8588            last.verified_at = Some(Timestamp::now());
8589            if verify_inconclusive(&last.e2e) {
8590                // Still not a real result: `e2e_deferred` is left exactly
8591                // as it was, so `needs_catchup_run` above reads
8592                // `ResourceBlocked` (via `e2e_status`, which checks
8593                // `resource_blocked` before `e2e_deferred`) and retries
8594                // again on the next reentry, rather than recording
8595                // contention as a red e2e and blocking the run on it.
8596                self.state.save()?;
8597                return Ok(());
8598            }
8599            last.e2e_deferred = false;
8600            // A complete panel may have been saved as unclean solely because
8601            // verification could not run. Refresh that verdict with the new
8602            // outcomes before a granted repair consumes the round's result.
8603            // Incomplete panels retain their original policy/quota decision.
8604            if last.answered == last.expected {
8605                last.clean = round_is_clean(
8606                    last.blocking,
8607                    last.e2e.iter().all(CommandOutcome::ok),
8608                    last.answered,
8609                    last.expected,
8610                    0,
8611                    self.state.config.graph.incomplete_review,
8612                );
8613            }
8614        }
8615        let last = &self.state.reviews[round_idx];
8616        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8617
8618        match last.e2e_status() {
8619            E2eStatus::Failed => {
8620                let red: Vec<String> = last
8621                    .e2e
8622                    .iter()
8623                    .filter(|o| !o.ok())
8624                    .map(|o| {
8625                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8626                            .map(|c| format!(" ({c})"))
8627                            .unwrap_or_default();
8628                        format!(
8629                            "`{}` -> {:?}{comparison}\n{}",
8630                            o.command,
8631                            o.code,
8632                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8633                        )
8634                    })
8635                    .collect();
8636                let can_repair = last.blocking == 0 && last.fix.is_none();
8637                self.state.reviews[round_idx].clean = false;
8638                self.state
8639                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8640                self.state.status = RunStatus::Blocked;
8641                if repairable
8642                    && can_repair
8643                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8644                {
8645                    self.state.status = RunStatus::Reviewing;
8646                }
8647            }
8648            // `needs_catchup_run` above already retried once this call; if
8649            // it is still blocked, this is magi's own admission it could
8650            // not get a command to run, never a verdict on the patch — the
8651            // run is left exactly where a later reentry can retry again.
8652            E2eStatus::ResourceBlocked => {
8653                self.state.event(
8654                    "review",
8655                    format!(
8656                        "{why}; e2e could not run (resource unavailable); not \
8657                         deciding yet"
8658                    ),
8659                );
8660            }
8661            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8662                self.state.event(
8663                    "review",
8664                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8665                );
8666                self.record_contested_handoff();
8667                self.state.status = RunStatus::Gating;
8668            }
8669        }
8670        self.state.save()?;
8671        Ok(())
8672    }
8673
8674    // ----------------------------------------------------------------- gate
8675
8676    async fn gate(&mut self) -> Result<()> {
8677        if self.hold_base_sync().await? {
8678            return Ok(());
8679        }
8680        // Judged by the review record itself, not by `status`: a solo
8681        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8682        // reentry (see `judge`), and trusting it here is exactly how a run
8683        // that exhausted its review budget got gated and merged a second
8684        // time around. `review_conclusion` recomputes the review loop's own
8685        // verdict from the round records themselves — `Gating` for a clean
8686        // round or a hand-off (see `stop_reviewing`), anything else means the
8687        // loop is still going or genuinely blocked.
8688        // A base the winner could not be replayed onto is a decision, not a
8689        // round: there is no landing tree to gate. Read as its own record for
8690        // the same reason the review verdict is.
8691        if self.state.status == RunStatus::Failed
8692            || self
8693                .state
8694                .base_sync
8695                .as_ref()
8696                .is_some_and(|s| s.conflict.is_some())
8697            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8698                != Some(RunStatus::Gating)
8699        {
8700            return Ok(());
8701        }
8702        let Some(winner) = self.state.winner().cloned() else {
8703            return Ok(());
8704        };
8705        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8706        self.state.reconcile_verification_head(&head);
8707        self.state.save()?;
8708        let wait = self.repository_wait();
8709        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8710            return Ok(());
8711        }
8712        if self.state.gate_ran {
8713            // `review_loop` derives its conclusion from the clean review
8714            // record on every reentry and therefore puts a completed run back
8715            // in `Gating`. A recorded gate is a stronger, terminal fact:
8716            // retain its original command output (or lack of any, for a repo
8717            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8718            // doc) and restore `Blocked` on a real failure rather than
8719            // pretending the command is still running or running it a second
8720            // time. `gate_ran == false` remains the only shape — unattempted,
8721            // or a resource-blocked retry — that may still need to execute a
8722            // command.
8723            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8724                self.state.status = RunStatus::Blocked;
8725                self.state.save()?;
8726            }
8727            return Ok(());
8728        }
8729        self.state.status = RunStatus::Gating;
8730        let mut outcomes = self.run_gate(&winner).await?;
8731        let mut attempted_head = self.state.gate_head.clone();
8732        loop {
8733            // A resource-blocked outcome means the gate command never actually
8734            // ran - the shared build cache could not be acquired or confirmed
8735            // fresh in time - which is evidence about the machine, not about
8736            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8737            // Recording it as a red gate would mark a run `Blocked` on nothing
8738            // but contention magi has already logged; leaving `self.state.gate`
8739            // empty and `self.state.gate_ran` false instead keeps the shape
8740            // this function already treats as "still needs to run" (see the
8741            // early-return above), so the next call retries the command
8742            // rather than concluding anything.
8743            if verify_inconclusive(&outcomes) {
8744                self.state.save()?;
8745                return Ok(());
8746            }
8747            if outcomes.iter().all(CommandOutcome::ok) {
8748                break;
8749            }
8750            let fixes_before = self.state.gate_fixes.len();
8751            match self.gate_fix_round(&winner, &outcomes).await? {
8752                GateFix::Retry => {
8753                    outcomes = self.run_gate(&winner).await?;
8754                    attempted_head = self.state.gate_head.clone();
8755                }
8756                GateFix::Stop => {
8757                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8758                    if self.state.gate_fixes.len() > fixes_before
8759                        && attempted_head.as_deref() != Some(current.as_str())
8760                        && verify_current_head(&mut self.state, &winner, &wait).await?
8761                    {
8762                        // A new SHA owes a gate even when a spent fixer changed only
8763                        // commit metadata. This does not grant another repair round.
8764                        outcomes = self.run_gate(&winner).await?;
8765                        attempted_head = self.state.gate_head.clone();
8766                    } else {
8767                        break;
8768                    }
8769                }
8770                GateFix::Defer => {
8771                    self.state.save()?;
8772                    return Ok(());
8773                }
8774            }
8775        }
8776        let passed = outcomes.iter().all(CommandOutcome::ok);
8777        self.state.gate = outcomes;
8778        self.state.gate_ran = true;
8779        self.state.gate_head = attempted_head;
8780        if !self.state.gate.is_empty()
8781            && !verify_inconclusive(&self.state.gate)
8782            && let Some(head) = self.state.gate_head.clone()
8783        {
8784            self.state.record_base_progress(&head);
8785        }
8786        self.state.save()?;
8787        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8788            return Ok(());
8789        }
8790        if !passed {
8791            self.state.status = RunStatus::Blocked;
8792            let spent = self.state.gate_fixes.len();
8793            self.state.event(
8794                "gate",
8795                if spent == 0 {
8796                    "gate failed; not merging".to_owned()
8797                } else {
8798                    format!("gate failed after {spent} gate-fix round(s); not merging")
8799                },
8800            );
8801        }
8802        self.state.save()?;
8803        Ok(())
8804    }
8805
8806    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8807    /// changed into one commit. Runs before `verify.e2e` in the review loop
8808    /// and again before the gate commands, always on the winner and never on
8809    /// a candidate awaiting judging.
8810    ///
8811    /// Before e2e as well as before the gate because command evidence belongs
8812    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8813    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8814    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8815    /// own call then finds nothing left to change. The commands must be
8816    /// idempotent; one that is not makes a commit per call.
8817    ///
8818    /// Never fails the run: a non-zero exit or timeout is a warning and a
8819    /// recorded outcome, and the gate remains the single arbiter. Nothing
8820    /// configured means nothing happens - no event, no commit. `commit_all`
8821    /// commits any leftover change under the neutral identity and returns
8822    /// `false` when the tree is clean, so no empty commit is ever made.
8823    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8824        let commands = state.config.verify.pre_gate.clone();
8825        if commands.is_empty() {
8826            return;
8827        }
8828        let shell = state.config.shell();
8829        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8830        let (outcomes, _) = run_commands(
8831            state,
8832            "pre_gate",
8833            "pre_gate",
8834            0,
8835            &shell,
8836            &commands,
8837            &winner.worktree,
8838            timeout,
8839        )
8840        .await;
8841        for o in &outcomes {
8842            if !o.ok() {
8843                tracing::warn!(
8844                    "pre_gate `{}` failed ({:?}); the gate decides",
8845                    o.command,
8846                    o.code
8847                );
8848            }
8849            state.event(
8850                "pre_gate",
8851                format!(
8852                    "`{}` -> {}",
8853                    o.command,
8854                    if o.ok() {
8855                        "pass".to_owned()
8856                    } else {
8857                        format!(
8858                            "FAIL ({:?})\n{}",
8859                            o.code,
8860                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8861                        )
8862                    }
8863                ),
8864            );
8865        }
8866        state.pre_gate = outcomes;
8867        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8868            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8869                Ok(head) => {
8870                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8871                    state.pre_gate_commit = Some(head);
8872                }
8873                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8874            },
8875            Ok(false) => {}
8876            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8877        }
8878        if let Err(e) = state.save() {
8879            tracing::warn!("could not persist the pre_gate record: {e:#}");
8880        }
8881    }
8882
8883    /// Run `verify.gate` once against the winner's current tree, logging one
8884    /// event per command. Empty when nothing is configured.
8885    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8886        let wait = self.repository_wait();
8887        run_landing_gate(&mut self.state, winner, &wait).await
8888    }
8889
8890    /// One bounded fix round for a failing gate.
8891    ///
8892    /// The fixer is told the failure came from the gate itself, not from a
8893    /// reviewer, and is shown the failed commands, their exit codes and a tail
8894    /// of their output - whatever `[verify].gate` holds, nothing here knows
8895    /// what those commands run. Only a normal non-zero exit that printed
8896    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8897    /// command or a full disk says nothing about the code, and a fixer sent
8898    /// after it can only appease the machine. The round is judged by what git
8899    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8900    /// again before the gate does, so a fix cannot trade a green gate for a
8901    /// red e2e unnoticed.
8902    async fn gate_fix_round(
8903        &mut self,
8904        winner: &Candidate,
8905        outcomes: &[CommandOutcome],
8906    ) -> Result<GateFix> {
8907        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8908            g.phase == crate::repair_budget::Phase::Fixing
8909                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8910        }) {
8911            self.state.gate_fixes.len().saturating_add(1)
8912        } else {
8913            self.state.config.graph.gate_fix_rounds
8914        };
8915        let spent = self.state.gate_fixes.len();
8916        if spent >= cap {
8917            if cap > 0 {
8918                self.state.event(
8919                    "gate",
8920                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8921                );
8922            }
8923            return Ok(GateFix::Stop);
8924        }
8925        if !gate_fixable(outcomes) {
8926            self.state.event(
8927                "gate",
8928                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8929                 command or similar); not spending a fix round on it",
8930            );
8931            return Ok(GateFix::Stop);
8932        }
8933        let min_free = self.state.config.disk.min_free_bytes;
8934        if min_free > 0 {
8935            match crate::disk::free_bytes(&winner.worktree) {
8936                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8937                Ok(free) => {
8938                    self.state.event(
8939                        "gate",
8940                        format!(
8941                            "only {free} bytes free ({min_free} required by `[disk] \
8942                             min_free_bytes`); not spending a fix round on a failure the disk \
8943                             may explain"
8944                        ),
8945                    );
8946                    return Ok(GateFix::Stop);
8947                }
8948                Err(e) => {
8949                    self.state.event(
8950                        "gate",
8951                        format!("free disk space could not be measured ({e:#}); no fix round"),
8952                    );
8953                    return Ok(GateFix::Stop);
8954                }
8955            }
8956        }
8957
8958        let attempt = spent + 1;
8959        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8960        let base = self.landing_base();
8961        let fix_prompt = prompt::gate_fix_in(
8962            &self.state.instruction,
8963            &failed,
8964            attempt,
8965            cap,
8966            &self.state.config.graph.language,
8967            &self.state.config.graph.github_language,
8968        );
8969        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8970        let sessions = self.state.config.graph.sessions;
8971        let artifacts = self.merge_repair_artifacts();
8972        self.state.event(
8973            "gate",
8974            format!("gate failed; gate-fix round {attempt} of {cap}"),
8975        );
8976        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8977        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8978        // Persist before invoking the fixer: it may commit and then be
8979        // interrupted before its result (or the following e2e) is saved.
8980        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8981            before.clone(),
8982            false,
8983            Vec::new(),
8984        ));
8985        self.state.save()?;
8986        let (_, seat, out) = self
8987            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8988                prompt: fix_prompt.clone(),
8989                spec,
8990                seat,
8991                cwd: winner.worktree.clone(),
8992                timeout,
8993                allow_write: true,
8994                sessions,
8995                artifacts: artifacts.clone(),
8996                stem: format!("gate-fix-{attempt}"),
8997                handover: None,
8998            })
8999            .await;
9000        // The fixer was never asked: no round is spent (nothing is recorded)
9001        // and a later reentry asks the same agent again.
9002        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9003            return Ok(GateFix::Defer);
9004        }
9005        let mut record = GateFixRecord {
9006            agent: seat.agent.clone(),
9007            failed,
9008            notes: String::new(),
9009            committed: false,
9010            error: None,
9011        };
9012        match out {
9013            AgentOutcome::Ok(o) => {
9014                // A missing report is not a failed fix: the round is judged
9015                // by the tree below, and the report only carries prose.
9016                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9017                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9018                }
9019            }
9020            AgentOutcome::Dropped(_) => {
9021                record.error = Some("the CLI dropped the stream".to_owned());
9022            }
9023            AgentOutcome::Quota(o) => {
9024                self.state.quota.push(QuotaLoss::from_report(
9025                    seat.key.clone(),
9026                    "gate-fix",
9027                    o.quota.as_ref(),
9028                ));
9029                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9030            }
9031            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9032        }
9033        self.state.seats.insert(seat.key.clone(), seat);
9034        let coordination = self.coordinate(&winner.worktree).await?;
9035        if let Ok(r) = git::rescue_commit(
9036            &winner.worktree,
9037            &format!("magi: gate fix {attempt} (uncommitted work)"),
9038        )
9039        .await
9040        {
9041            self.state.note_withheld("gate-fix", &r.withheld);
9042        }
9043        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9044        record.committed = after != before;
9045        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9046        let note = record.error.clone();
9047        self.state.gate_fixes.push(record);
9048        self.state.save()?;
9049        if !changed {
9050            self.state.event(
9051                "gate",
9052                match note {
9053                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9054                    None => format!("gate-fix round {attempt}: the tree did not change"),
9055                },
9056            );
9057            return Ok(GateFix::Stop);
9058        }
9059        self.state.event(
9060            "gate",
9061            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9062        );
9063
9064        drop(coordination);
9065        let wait = self.repository_wait();
9066        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9067    }
9068
9069    // ---------------------------------------------------------------- merge
9070
9071    /// One read-only rewrite by the summary's author; a text the gate still
9072    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9073    /// applies on their word or on silence. `None` means the run is parked on
9074    /// that question and nothing may be pushed or opened yet.
9075    async fn guarded_pr_message(
9076        &mut self,
9077        winner: &Candidate,
9078        facts: Option<&BranchFacts>,
9079        posting: bool,
9080    ) -> Result<Option<PrMessage>> {
9081        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9082        let head = match final_head.as_deref() {
9083            Some(h) => crate::pr_outcome::FinalHead::At(h),
9084            None => crate::pr_outcome::FinalHead::Unknown,
9085        };
9086        // Only a pull request that is about to be posted pays for a summary.
9087        let summarized = if posting {
9088            Some(self.summarize_change(winner, final_head.as_deref()).await)
9089        } else {
9090            None
9091        };
9092        // A busy shared resource is not a permanent cause: publishing an
9093        // "unavailable" description would stick (a later head move never
9094        // edits the body). Stop before anything is pushed or opened; the
9095        // run is `Blocked` and a resume asks the summary again.
9096        if self.state.resource_block.is_some() {
9097            self.state.event(
9098                "pr-summary",
9099                "a shared resource was busy; nothing was published, resume to summarize again",
9100            );
9101            return Ok(None);
9102        }
9103        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9104            anyhow::bail!(
9105                "the final commit moved during public description generation; retry before publishing"
9106            );
9107        }
9108        let note = match (&summarized, &self.state.change_summary) {
9109            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9110            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9111            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9112            (None, _) => ChangeNote::NotAsked,
9113        };
9114        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9115        if !posting {
9116            let identity = crate::scrub::Identity::current();
9117            return Ok(Some(PrMessage {
9118                title: crate::scrub::scrub(&pr.title, &identity),
9119                body: crate::scrub::scrub(&pr.body, &identity),
9120            }));
9121        }
9122        // This very text was already rejected and asked about: no second
9123        // judge call, rewrite or question, just carry the record on.
9124        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9125        if let Some(known) = self
9126            .state
9127            .github_text
9128            .clone()
9129            .filter(|g| g.fingerprint == raw_fp)
9130        {
9131            return self.settle_withheld(winner, &pr, known).await;
9132        }
9133        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9134        let mut violations =
9135            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9136        let identity = crate::scrub::Identity::current();
9137        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9138            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9139            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9140        {
9141            violations.push(crate::github_text::Violation::SensitiveData);
9142        }
9143        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9144        // only a language violation starts one; sensitive data alone goes
9145        // straight to the owner, with the redacted text as the fallback.
9146        let has_language = violations
9147            .iter()
9148            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9149        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9150            self.state.event(
9151                "github-text",
9152                if has_language {
9153                    format!("description rejected: {violations:?}; requesting one rewrite")
9154                } else {
9155                    format!("description rejected: {violations:?}; asking the owner")
9156                },
9157            );
9158            let mut rewritten = false;
9159            let mut rejected_rewrite = None;
9160            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9161            {
9162                let output = text;
9163                if let Some(title) = summary_title(&output) {
9164                    // Judge the redacted candidate that will actually be posted.
9165                    // Sensitive data alone must not discard a useful rewrite.
9166                    let raw_body = summary_without_title(&output);
9167                    let clean_title = crate::scrub::scrub(&title, &identity);
9168                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9169                    let redacted = clean_title != title || body != raw_body;
9170                    let title = clean_title;
9171                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9172                    if !complete {
9173                        self.state.event(
9174                            "github-text",
9175                            "description rewrite omitted required findings",
9176                        );
9177                    }
9178                    if !body.trim().is_empty() {
9179                        body.push_str("\n\n");
9180                        body.push_str(&public_pr_evidence(&self.state, head));
9181                    }
9182                    let marker = format!("magi:run/{}", self.state.id);
9183                    if !body.trim().is_empty() && !body.contains(&marker) {
9184                        body.push_str(&format!("\n\n{marker}"));
9185                    }
9186                    let rewrite = PrMessage {
9187                        title: title.clone(),
9188                        body: body.clone(),
9189                    };
9190                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9191                    let mut failed = crate::github_text::check_for(
9192                        &self.state.config.graph,
9193                        &title,
9194                        &body,
9195                        redecision,
9196                    );
9197                    if (!crate::github_text::shareable(&title)
9198                        || !crate::github_text::shareable(&body))
9199                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9200                    {
9201                        failed.push(crate::github_text::Violation::SensitiveData);
9202                    }
9203                    if complete
9204                        && !title.trim().is_empty()
9205                        && !body.trim().is_empty()
9206                        && !failed.is_empty()
9207                    {
9208                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9209                            title: title.clone(),
9210                            body: body.clone(),
9211                            failed: failed
9212                                .iter()
9213                                .map(|v| crate::github_text::category(*v).to_owned())
9214                                .collect(),
9215                        });
9216                    }
9217                    if complete
9218                        && !title.trim().is_empty()
9219                        && !raw_body.trim().is_empty()
9220                        && failed.is_empty()
9221                    {
9222                        decision = redecision;
9223                        pr = PrMessage { title, body };
9224                        rewritten = true;
9225                        self.state
9226                            .event("github-text", "description rewrite passed");
9227                        if redacted {
9228                            self.state.event(
9229                                "github-text",
9230                                "sensitive data removed from description rewrite",
9231                            );
9232                        }
9233                    }
9234                }
9235            }
9236            if !rewritten {
9237                self.state.event(
9238                    "github-text",
9239                    "description rewrite unavailable or rejected; asking the owner",
9240                );
9241                if let Some(w) =
9242                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9243                {
9244                    // A different text than the one asked about before: that
9245                    // question no longer describes anything.
9246                    self.retire_github_text_question("the withheld text changed");
9247                    let record = crate::run::GithubTextAsk {
9248                        rewrite: rejected_rewrite,
9249                        fingerprint: raw_fp,
9250                        title: w.title,
9251                        body: w.body,
9252                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9253                        question: None,
9254                        asks: 0,
9255                        resolved: false,
9256                        chosen_title: None,
9257                        choice: None,
9258                        publication: None,
9259                    };
9260                    return self.settle_withheld(winner, &pr, record).await;
9261                }
9262            }
9263        }
9264        let (title, body) =
9265            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9266        Ok(Some(PrMessage { title, body }))
9267    }
9268
9269    /// Describe the whole change from its final diff in either run mode.
9270    ///
9271    /// The summary is tied to the final commit and to the merge base of the
9272    /// resolved remote base; a record for any other pair is dropped and the
9273    /// agent asked again, so a description never outlives the diff it was
9274    /// written from. The seat is read-only and the prompt tells it to read the
9275    /// diff and the code around it. `[roles] synthesizer` selects the agents
9276    /// (unset: the default pick), each asked at most once, advancing on an
9277    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9278    /// carries the reason it is unavailable; nothing is invented then.
9279    async fn summarize_change(
9280        &mut self,
9281        winner: &Candidate,
9282        head: Option<&str>,
9283    ) -> std::result::Result<(), String> {
9284        let Some(head) = head else {
9285            return Err("the final commit could not be read".to_owned());
9286        };
9287        let remote = self.state.config.merge.remote.clone();
9288        let tracking = format!("{remote}/{}", self.state.base_branch);
9289        if !git::rev_exists(&winner.worktree, &tracking).await {
9290            return Err(format!("the remote base `{tracking}` could not be read"));
9291        }
9292        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9293            Ok(b) if !b.is_empty() => b,
9294            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9295        };
9296        let evidence = crate::pr_outcome::summary_evidence(
9297            &self.state,
9298            crate::pr_outcome::FinalHead::At(head),
9299        );
9300        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9301        if self
9302            .state
9303            .change_summary
9304            .as_ref()
9305            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9306        {
9307            return Ok(());
9308        }
9309        if self.state.change_summary.take().is_some() {
9310            self.state.event(
9311                "pr-summary",
9312                "the final diff or evidence changed; the earlier change summary was discarded",
9313            );
9314        }
9315        // Save the source snapshot even if no generation agent is available.
9316        if let Err(e) = write_artifact(
9317            &self.state,
9318            &format!("public-description-{fingerprint}.md"),
9319            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9320        ) {
9321            tracing::warn!("could not save public description evidence: {e:#}");
9322        }
9323        let chain = match agent::pick_chain(
9324            &self.state.config.agents,
9325            self.state.config.roles.synthesizer.as_ref(),
9326            &agent::installed,
9327            "synthesizer",
9328        ) {
9329            Ok(chain) => chain,
9330            Err(e) => {
9331                tracing::warn!("no agent for the change summary: {e:#}");
9332                self.state.event("pr-summary", "no summary agent available");
9333                return Err("no agent was available to summarize it".to_owned());
9334            }
9335        };
9336        let subjects = git::subjects(&winner.worktree, &base, head)
9337            .await
9338            .unwrap_or_default();
9339        let stat = git::diff_stat(&winner.worktree, &base, head)
9340            .await
9341            .unwrap_or_default();
9342        let stat: String = stat.chars().take(6_000).collect();
9343        let mut prompt = crate::prompt::change_summary_in(
9344            &base,
9345            head,
9346            &subjects,
9347            stat.trim(),
9348            &self.state.config.graph.github_language,
9349        );
9350        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."));
9351        let sessions = self.state.config.graph.sessions;
9352        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9353        let prompts = self.state.config.prompts.clone();
9354        let cache = self.state.config.cache_dir();
9355        let run = self.state.id.clone();
9356        for (i, spec) in chain.into_iter().enumerate() {
9357            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9358            let github_spec = match agent::for_github_text(
9359                &spec,
9360                &self.state.config.graph.github_language,
9361                &winner.worktree,
9362            ) {
9363                Ok(spec) => spec,
9364                Err(e) => {
9365                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9366                    continue;
9367                }
9368            };
9369            let job = SeatJob {
9370                spec: github_spec,
9371                seat,
9372                cwd: winner.worktree.clone(),
9373                prompt: prompt.clone(),
9374                timeout,
9375                allow_write: false,
9376                sessions,
9377                artifacts: agent::artifacts_dir(&self.state.dir()),
9378                stem: if i == 0 {
9379                    "change-summary".to_owned()
9380                } else {
9381                    format!("change-summary-{}", spec.id)
9382                },
9383                handover: None,
9384            };
9385            let ctx = WaveCtx {
9386                run: &run,
9387                node: "pr-summary",
9388                prompts: &prompts,
9389                cache: cache.as_deref(),
9390                round: None,
9391                carry_seats: false,
9392                pauses: Some((&self.pause, &self.interrupt)),
9393            };
9394            let (seat, outcome) =
9395                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9396            self.state.seats.insert(seat.key.clone(), seat);
9397            let text = match outcome {
9398                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9399                AgentOutcome::ResourceBlocked(why) => {
9400                    // No agent was asked: the run stops resumably before
9401                    // anything is published (see `guarded_pr_message`).
9402                    if self.state.resource_block.is_none() {
9403                        self.state.resource_block = Some(crate::run::ResourceBlock {
9404                            cause: crate::run::ResourceBlockCause::Other,
9405                            node: "pr-summary".to_owned(),
9406                            kind: "shared resource".to_owned(),
9407                            detail: why,
9408                            at: Timestamp::now(),
9409                        });
9410                    }
9411                    return Err("a shared resource was busy".to_owned());
9412                }
9413                _ => continue,
9414            };
9415            let blind = &self.state.config.blind;
9416            let Some(title) = summary_title(&text) else {
9417                continue;
9418            };
9419            let body: String = summary_without_title(&text)
9420                .lines()
9421                .filter(|l| !l.contains("magi:run/"))
9422                .collect::<Vec<_>>()
9423                .join("\n");
9424            let body = blind::sanitize_prose(body.trim(), blind);
9425            let title = blind::sanitize_prose(&title, blind);
9426            if body.trim().is_empty() || title.trim().is_empty() {
9427                continue;
9428            }
9429            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9430                continue;
9431            }
9432            // The branch must still be the one the agent was shown.
9433            if git::rev_parse(&winner.worktree, "HEAD")
9434                .await
9435                .ok()
9436                .as_deref()
9437                != Some(head)
9438            {
9439                return Err("the branch moved while the summary was written".to_owned());
9440            }
9441            if git::merge_base(&winner.worktree, &tracking, head)
9442                .await
9443                .ok()
9444                .as_deref()
9445                != Some(base.as_str())
9446                || crate::pr_outcome::summary_evidence(
9447                    &self.state,
9448                    crate::pr_outcome::FinalHead::At(head),
9449                ) != evidence
9450            {
9451                return Err("the summary evidence changed while it was written".to_owned());
9452            }
9453            self.state.change_summary = Some(crate::run::ChangeSummary {
9454                head: head.to_owned(),
9455                base,
9456                evidence: fingerprint,
9457                title,
9458                body,
9459            });
9460            self.state.event(
9461                "pr-summary",
9462                format!("change summary written by {} for the final diff", spec.id),
9463            );
9464            if let Err(e) = self.state.save() {
9465                tracing::warn!("could not save the change summary: {e:#}");
9466            }
9467            return Ok(());
9468        }
9469        self.state
9470            .event("pr-summary", "no agent produced a change summary");
9471        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9472    }
9473
9474    /// One read-only rewrite request for a withheld description. The
9475    /// implementer's own conversation is tried first when it exists and can be
9476    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9477    /// writes it in a separate conversation, skipping the implementer's agent.
9478    /// The prompt carries the whole text, so no agent needs any memory. Each
9479    /// agent is asked at most once and the chain advances on an error, quota,
9480    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9481    /// that has run out of quota must not end the rewrite. Nothing is recorded
9482    /// as a handover.
9483    async fn rewrite_pr_text(
9484        &mut self,
9485        winner: &Candidate,
9486        pr: &PrMessage,
9487        violations: &[crate::github_text::Violation],
9488    ) -> Option<String> {
9489        let prompt = format!(
9490            "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{}",
9491            pr.title, pr.body
9492        );
9493        let sessions = self.state.config.graph.sessions;
9494        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9495        // (spec, the resumed implementer's seat). A fallback seat is created
9496        // only when its turn comes, so an unused fallback leaves no record.
9497        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9498        let key = format!("impl-{}", winner.label);
9499        if let Some(spec) = self
9500            .state
9501            .config
9502            .agents
9503            .iter()
9504            .find(|a| a.id == winner.agent)
9505            .cloned()
9506            && let Some(existing) = self.state.seats.get(&key)
9507            && existing.agent == spec.id
9508            && agent::has_session(spec.kind, existing, sessions)
9509        {
9510            attempts.push((spec, Some(existing.clone())));
9511        }
9512        match agent::pick_chain(
9513            &self.state.config.agents,
9514            self.state.config.roles.language_judge.as_ref(),
9515            &agent::installed,
9516            "language_judge",
9517        ) {
9518            Ok(chain) => {
9519                for spec in chain {
9520                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9521                        continue;
9522                    }
9523                    attempts.push((spec, None));
9524                }
9525            }
9526            Err(e) if attempts.is_empty() => {
9527                tracing::warn!("no agent for the description rewrite: {e:#}");
9528                self.state
9529                    .event("github-text", "no rewrite agent available");
9530                return None;
9531            }
9532            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9533        }
9534        let prompts = self.state.config.prompts.clone();
9535        let cache = self.state.config.cache_dir();
9536        let run = self.state.id.clone();
9537        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9538            let resumed = resumed_seat.is_some();
9539            let seat = resumed_seat.unwrap_or_else(|| {
9540                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9541            });
9542            let github_spec = match agent::for_github_text(
9543                &spec,
9544                &self.state.config.graph.github_language,
9545                &winner.worktree,
9546            ) {
9547                Ok(spec) => spec,
9548                Err(e) => {
9549                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9550                    continue;
9551                }
9552            };
9553            let job = SeatJob {
9554                spec: github_spec,
9555                seat,
9556                cwd: winner.worktree.clone(),
9557                prompt: prompt.clone(),
9558                timeout: retry_budget(timeout_full, resumed),
9559                allow_write: false,
9560                sessions,
9561                artifacts: agent::artifacts_dir(&self.state.dir()),
9562                stem: if i == 0 {
9563                    "github-text-rewrite".to_owned()
9564                } else {
9565                    format!("github-text-rewrite-{}", spec.id)
9566                },
9567                handover: None,
9568            };
9569            let ctx = WaveCtx {
9570                run: &run,
9571                node: "github-text",
9572                prompts: &prompts,
9573                cache: cache.as_deref(),
9574                round: None,
9575                carry_seats: false,
9576                pauses: Some((&self.pause, &self.interrupt)),
9577            };
9578            let (seat, outcome) =
9579                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9580            self.state.seats.insert(seat.key.clone(), seat);
9581            match outcome {
9582                AgentOutcome::Ok(o)
9583                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9584                {
9585                    return Some(o.text);
9586                }
9587                AgentOutcome::ResourceBlocked(_) => return None,
9588                _ => {}
9589            }
9590        }
9591        None
9592    }
9593
9594    /// Abandon the standing posting-gate question, if any.
9595    fn retire_github_text_question(&mut self, why: &str) {
9596        let Some(id) = self
9597            .state
9598            .github_text
9599            .as_ref()
9600            .and_then(|g| g.question.clone())
9601        else {
9602            return;
9603        };
9604        let _ = ask::Questions::open().update(&id, |q| {
9605            q.abandon(why);
9606            Ok(())
9607        });
9608    }
9609
9610    /// Carry a withheld text to its end: file the question, park while it is
9611    /// open, and on an answer, silence or timeout pick the text to post. The
9612    /// decision is saved before it is used, so it applies once.
9613    async fn settle_withheld(
9614        &mut self,
9615        winner: &Candidate,
9616        pr: &PrMessage,
9617        mut g: crate::run::GithubTextAsk,
9618    ) -> Result<Option<PrMessage>> {
9619        use crate::github_text as gt;
9620        let store = ask::Questions::open();
9621        let timeout = self.state.config.graph.answer_timeout;
9622        if !g.resolved {
9623            let mut standing = g
9624                .question
9625                .as_ref()
9626                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9627            if let Some(q) = standing.as_ref()
9628                && q.status.open()
9629                && !store.held_reply(&q.id)
9630                && gt::expired(q, timeout)
9631            {
9632                let why = format!("no answer within {}s of asking", timeout.max(1));
9633                standing = store
9634                    .update(&q.id, |q| {
9635                        q.abandon(&why);
9636                        Ok(())
9637                    })
9638                    .ok()
9639                    .map(|(q, ())| q);
9640            }
9641            let mut ask_again: Option<Option<Vec<String>>> = None;
9642            match standing {
9643                // Recorded but never written (a stop between the two saves),
9644                // or removed: ask again without spending the retry.
9645                None if g.asks <= 1 => {
9646                    g.asks = 0;
9647                    ask_again = Some(None);
9648                }
9649                None => {
9650                    g.resolved = true;
9651                    g.chosen_title = None;
9652                    g.choice = Some(GithubTextChoice::Fallback);
9653                }
9654                Some(q) if q.status.open() => {
9655                    self.park_on_github_text(&g)?;
9656                    return Ok(None);
9657                }
9658                Some(q) => match gt::read_reply(&q) {
9659                    gt::Reply::Fallback => {
9660                        g.resolved = true;
9661                        g.chosen_title = None;
9662                        g.choice = Some(GithubTextChoice::Fallback);
9663                    }
9664                    gt::Reply::Original => {
9665                        g.resolved = true;
9666                        g.chosen_title = None;
9667                        g.choice = Some(GithubTextChoice::Original);
9668                    }
9669                    gt::Reply::Rewrite => {
9670                        g.resolved = true;
9671                        g.chosen_title = None;
9672                        g.choice = Some(if g.rewrite.is_some() {
9673                            GithubTextChoice::Rewrite
9674                        } else {
9675                            GithubTextChoice::Fallback
9676                        });
9677                    }
9678                    gt::Reply::Title(text) => {
9679                        let first = text
9680                            .lines()
9681                            .map(str::trim)
9682                            .find(|l| !l.is_empty())
9683                            .unwrap_or("");
9684                        let decision = if first.is_empty() {
9685                            None
9686                        } else {
9687                            let candidate = PrMessage {
9688                                title: first.to_owned(),
9689                                body: String::new(),
9690                            };
9691                            self.judge_pr_language(&winner.worktree, &candidate).await
9692                        };
9693                        match gt::vet_title(
9694                            &text,
9695                            decision,
9696                            self.state.config.graph.github_english(),
9697                        ) {
9698                            Ok(title) => {
9699                                g.resolved = true;
9700                                g.chosen_title = Some(title);
9701                                g.choice = Some(GithubTextChoice::MyTitle);
9702                            }
9703                            Err(cats) if g.asks < 2 => {
9704                                ask_again = Some(Some(
9705                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9706                                ))
9707                            }
9708                            Err(_) => {
9709                                g.resolved = true;
9710                                g.chosen_title = None;
9711                                g.choice = Some(GithubTextChoice::Fallback);
9712                            }
9713                        }
9714                    }
9715                },
9716            }
9717            if let Some(rejected) = ask_again {
9718                // A retry (after a rejected replacement title) is still about
9719                // the original text: the same ORIGINAL / FALLBACK comparison.
9720                let w = gt::Withheld {
9721                    title: g.title,
9722                    body: g.body,
9723                    categories: g.categories.clone(),
9724                };
9725                // Named by the original text's fingerprint alone, so a resume
9726                // rewrites the same file and the detail stays identical.
9727                let artifact = match crate::run::write_artifact(
9728                    &self.state,
9729                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9730                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9731                ) {
9732                    Ok(p) => Some(p),
9733                    Err(e) => {
9734                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9735                        None
9736                    }
9737                };
9738                let (detail, comparison) = gt::question_content(
9739                    &w,
9740                    &pr.title,
9741                    &pr.body,
9742                    &self.state.id,
9743                    rejected.as_deref(),
9744                    artifact.as_deref(),
9745                    g.rewrite.as_ref(),
9746                );
9747                let mut q = ask::Question::new(
9748                    self.state.id.clone(),
9749                    gt::ASK_NODE.to_owned(),
9750                    gt::ASK_SEAT.to_owned(),
9751                    gt::question_summary(&self.state.config.graph.language, &w),
9752                    detail,
9753                    gt::question_choices(&w, g.rewrite.as_ref()),
9754                );
9755                q.posting_comparison = Some(comparison);
9756                q.answer_timeout = timeout;
9757                // Recorded before it is written: a stop in between leaves a
9758                // record naming a question the resume then files again.
9759                g.question = Some(q.id.clone());
9760                g.asks += 1;
9761                self.state.github_text = Some(g.clone());
9762                self.state.event(
9763                    "github-text",
9764                    format!("asking the owner about the withheld text ({})", q.short()),
9765                );
9766                self.state.save()?;
9767                store
9768                    .put_executable(&mut q)
9769                    .context("file the posting-gate question")?;
9770                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9771                    tracing::warn!(
9772                        "could not notify about posting-gate question {}: {e:#}",
9773                        q.short()
9774                    );
9775                }
9776                self.park_on_github_text(&g)?;
9777                return Ok(None);
9778            }
9779        }
9780        let resolved = g.chosen_title.clone();
9781        let original = g.choice == Some(GithubTextChoice::Original);
9782        // Field names only: the event log never records the text.
9783        self.state.event(
9784            "github-text",
9785            if original {
9786                format!(
9787                    "posting the original text for: {}",
9788                    match (g.title, g.body) {
9789                        (true, true) => "title, description",
9790                        (true, false) => "title",
9791                        _ => "description",
9792                    }
9793                )
9794            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9795                "posting the saved rewrite title and description".to_owned()
9796            } else if resolved.is_some() {
9797                "posting the owner's replacement title".to_owned()
9798            } else {
9799                "posting the neutral text for the withheld fields".to_owned()
9800            },
9801        );
9802        self.state.github_text = Some(g.clone());
9803        self.state.save()?;
9804        if g.choice == Some(GithubTextChoice::Rewrite)
9805            && let Some(r) = g.rewrite.as_ref()
9806        {
9807            return Ok(Some(PrMessage {
9808                title: r.title.clone(),
9809                body: r.body.clone(),
9810            }));
9811        }
9812        let w = gt::Withheld {
9813            title: g.title,
9814            body: g.body,
9815            categories: g.categories.clone(),
9816        };
9817        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9818        if let Some(t) = resolved {
9819            title = t;
9820        }
9821        // Every withheld field is now neutral or vetted English.
9822        let english = gt::LanguageDecision {
9823            title_english: true,
9824            body_english: true,
9825            body_complete: true,
9826        };
9827        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9828        if original {
9829            // The owner's explicit choice overrides the gate for the fields it
9830            // was made for; the others keep what the gate produced.
9831            if g.title {
9832                title = pr.title.clone();
9833            }
9834            if g.body {
9835                body = pr.body.clone();
9836            }
9837        }
9838        Ok(Some(PrMessage { title, body }))
9839    }
9840
9841    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9842        self.state.github_text = Some(g.clone());
9843        self.state.end_pass_parked(ParkCause::Question);
9844        self.state.parked = true;
9845        self.state.event(
9846            "github-text",
9847            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9848        );
9849        self.state.save()
9850    }
9851
9852    /// Ask `[roles] language_judge` about this text and record which source
9853    /// decided; the text itself is never recorded.
9854    async fn judge_pr_language(
9855        &mut self,
9856        cwd: &Path,
9857        pr: &PrMessage,
9858    ) -> Option<crate::github_text::LanguageDecision> {
9859        self.state.config.roles.language_judge.as_ref()?;
9860        if !self.state.config.graph.language_gate() {
9861            return None;
9862        }
9863        let decision =
9864            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9865        self.state.event(
9866            "github-text",
9867            if decision.is_some() {
9868                "language decided by the language judge"
9869            } else {
9870                "language judge unavailable; using built-in heuristics"
9871            },
9872        );
9873        decision
9874    }
9875
9876    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9877        Box::pin(self.merge_inner())
9878    }
9879
9880    async fn merge_inner(&mut self) -> Result<()> {
9881        if self.resource_halt()? || self.hold_base_sync().await? {
9882            return Ok(());
9883        }
9884        // Same reasoning as `gate`: ask the review and gate records directly
9885        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9886        // skip can rewrite on reentry to something that no longer says
9887        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9888        // so a hand-off (open findings, green verification) reaches merge
9889        // exactly like a genuinely clean round does.
9890        //
9891        // A run resumed mid-`land` never reaches here at all: `execute`
9892        // recognises `RunStatus::Landing` before it even calls `prep`, and
9893        // routes straight to `run_land` instead. That has to happen a level
9894        // up from this function, not with a check in here, because
9895        // `review_loop`'s own status recomputation (see its doc) runs
9896        // *before* `merge` on every reentry and would otherwise overwrite
9897        // the `Landing` marker with `Gating` before this node ever saw it.
9898        if self
9899            .state
9900            .base_sync
9901            .as_ref()
9902            .is_some_and(|s| s.conflict.is_some())
9903            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9904                != Some(RunStatus::Gating)
9905            // `gate_ran == false` is not "passed" - `gate` leaves it false
9906            // both before it has ever run and when its last attempt was
9907            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9908            // permission to merge on nothing but the review record. Only a
9909            // gate that actually ran may proceed; an intentional local
9910            // review can also finish with verification explicitly not configured.
9911            // `RunState::gate_status` computes that distinction.
9912            || !self.state.gate_allows_progress()
9913        {
9914            return Ok(());
9915        }
9916        // This node's own record, not `status`: `status == Ready` is not
9917        // unique to the harmless `MergeMode::None` path this line was
9918        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9919        // run's PR was closed without merging — and on that run `mode` is
9920        // still `Pr`, so a reentry that fell through here would push and
9921        // open a second pull request. `self.state.merge` is set exactly once
9922        // this node (or `land`) has already produced a verdict, under every
9923        // mode, which is what "already done" actually means here.
9924        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9925            return Ok(());
9926        }
9927        let Some(winner) = self.state.winner().cloned() else {
9928            return Ok(());
9929        };
9930        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9931        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9932            self.state.status = RunStatus::Blocked;
9933            self.state.event(
9934                "gate",
9935                "winner changed after gate; fresh verification required",
9936            );
9937            self.state.save()?;
9938            return Ok(());
9939        }
9940        let wait = self.repository_wait();
9941        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9942            return Ok(());
9943        }
9944        let repo = self.state.repo.clone();
9945        let base = self.state.base_branch.clone();
9946        let mode = self.state.config.merge.mode;
9947        let style = self.state.config.merge.style;
9948        let facts = if is_review_run(&self.state) {
9949            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9950            let start = review_base(
9951                &repo,
9952                &self.state.config.merge.remote,
9953                &base,
9954                &self.state.base_commit,
9955                &winner.branch,
9956            )
9957            .await;
9958            branch_facts(&repo, &start, &winner.branch).await
9959        } else {
9960            None
9961        };
9962        // `None` when the base could not be freshly read: then an adopted
9963        // pull request's title is left alone.
9964        let leaked = if is_review_run(&self.state) {
9965            leaked_subjects(&self.state, &winner.branch).await
9966        } else {
9967            Some(Vec::new())
9968        };
9969        // `None`: parked on the owner's word about a withheld title or body.
9970        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9971        // the resume arrives here again.
9972        let Some(pr) = self
9973            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9974            .await?
9975        else {
9976            return Ok(());
9977        };
9978        let message = pr.commit_message();
9979
9980        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9981        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9982            return Ok(());
9983        }
9984        let outcome = match mode {
9985            MergeMode::None => MergeOutcome {
9986                mode,
9987                ok: true,
9988                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9989                empty: false,
9990            },
9991            MergeMode::Pr | MergeMode::Local
9992                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9993            {
9994                MergeOutcome {
9995                    mode,
9996                    ok: false,
9997                    detail: empty_candidate_detail(&self.state, &base),
9998                    empty: true,
9999                }
10000            }
10001            MergeMode::Local => {
10002                let on = git::current_branch(&repo).await?;
10003                if on.as_deref() != Some(base.as_str()) {
10004                    MergeOutcome {
10005                        mode,
10006                        ok: false,
10007                        detail: format!(
10008                            "{} has {} checked out, not the base branch {base}",
10009                            repo.display(),
10010                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10011                        ),
10012                        empty: false,
10013                    }
10014                } else if !git::is_clean(&repo).await? {
10015                    MergeOutcome {
10016                        mode,
10017                        ok: false,
10018                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10019                        empty: false,
10020                    }
10021                } else {
10022                    let out = match style {
10023                        MergeStyle::Merge => {
10024                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10025                        }
10026                        MergeStyle::Squash => {
10027                            git::merge_squash(&repo, &winner.branch, &message).await?
10028                        }
10029                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10030                    };
10031                    MergeOutcome {
10032                        mode,
10033                        ok: out.ok(),
10034                        detail: if out.ok() { out.stdout } else { out.stderr },
10035                        empty: false,
10036                    }
10037                }
10038            }
10039            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10040                self.state.pr_publication_pending = true;
10041                self.state.save()?;
10042                let out =
10043                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10044                self.state.pr_publication_pending = out.is_err();
10045                MergeOutcome {
10046                    mode,
10047                    ok: out.is_ok(),
10048                    detail: match out {
10049                        Ok(url) => url,
10050                        Err(e) => format!("{e:#}"),
10051                    },
10052                    empty: false,
10053                }
10054            }
10055            MergeMode::Pr => {
10056                let remote = self.state.config.merge.remote.clone();
10057                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10058                let pushed = if self.state.foreign_checkout.is_some() {
10059                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10060                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10061                } else {
10062                    git::push(&winner.worktree, &remote, &winner.branch).await?
10063                };
10064                if !pushed.ok() {
10065                    MergeOutcome {
10066                        mode,
10067                        ok: false,
10068                        detail: pushed.stderr,
10069                        empty: false,
10070                    }
10071                } else {
10072                    if self.state.foreign_checkout.is_some() {
10073                        self.state.pr_pushed_head = Some(delivery_head.clone());
10074                    }
10075                    // A retry or resume of a run whose branch already has an
10076                    // open pull request adopts it rather than failing on a
10077                    // duplicate. Only this winner branch into this base:
10078                    // `branch_for` derives the name from the run id, so a
10079                    // different run's pull request never matches.
10080                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10081                    let out = match pr_merge_plan(found) {
10082                        PrPlan::Create => {
10083                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10084                                .await
10085                        }
10086                        PrPlan::Adopt { url, title } => {
10087                            self.state
10088                                .event("merge", format!("Pr: adopted open pull request {url}"));
10089                            if self.state.explicit_github_text_selection() {
10090                                // An explicit publication selection applies the prepared
10091                                // payload; acceptance alone is not publication proof.
10092                                land::set_pr_text_verbatim(
10093                                    &winner.worktree,
10094                                    &url,
10095                                    &pr.title,
10096                                    &pr.body,
10097                                )
10098                                .await
10099                                .map(|()| url)
10100                            } else {
10101                                if title != pr.title
10102                                    && (!is_review_run(&self.state)
10103                                        || leaked
10104                                            .as_deref()
10105                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10106                                    && let Err(e) =
10107                                        if self.state.github_text.as_ref().is_some_and(|g| {
10108                                            g.resolved
10109                                                && g.title
10110                                                && g.choice == Some(GithubTextChoice::Original)
10111                                        }) {
10112                                            // The owner chose to post this title unmodified.
10113                                            land::set_pr_title_verbatim(
10114                                                &winner.worktree,
10115                                                &url,
10116                                                &pr.title,
10117                                            )
10118                                            .await
10119                                        } else {
10120                                            land::set_pr_title(
10121                                                &mut self.state,
10122                                                &winner.worktree,
10123                                                &url,
10124                                                &pr.title,
10125                                            )
10126                                            .await
10127                                        }
10128                                {
10129                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10130                                    self.state
10131                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10132                                }
10133                                Ok(url)
10134                            }
10135                        }
10136                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10137                    };
10138                    match out {
10139                        Ok(url) => MergeOutcome {
10140                            mode,
10141                            ok: true,
10142                            detail: url,
10143                            empty: false,
10144                        },
10145                        Err(e) => MergeOutcome {
10146                            mode,
10147                            ok: false,
10148                            detail: e.to_string(),
10149                            empty: false,
10150                        },
10151                    }
10152                }
10153            }
10154        };
10155
10156        self.state.status = match (mode, outcome.ok) {
10157            (MergeMode::None, _) => RunStatus::Ready,
10158            (_, true) if outcome.empty => RunStatus::Ready,
10159            (MergeMode::Pr, true) => RunStatus::Ready,
10160            (_, true) => RunStatus::Merged,
10161            (_, false) => RunStatus::Blocked,
10162        };
10163        self.state.event(
10164            "merge",
10165            format!(
10166                "{:?}: {}",
10167                mode,
10168                outcome.detail.lines().next().unwrap_or("")
10169            ),
10170        );
10171        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10172            self.state.record_github_text_publication(&outcome.detail);
10173        }
10174        self.state.merge = Some(outcome);
10175        self.state.save()?;
10176
10177        // The PR is open and the run would historically stop here, leaving the
10178        // operator to watch checks, feed review comments back to a fixer, and
10179        // merge. That was done by hand six times in one session before this
10180        // existed. Opt-in, because merging is the one irreversible thing magi
10181        // can do to a repository.
10182        if self.state.config.graph.land
10183            && mode == MergeMode::Pr
10184            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10185        {
10186            self.run_land().await?;
10187        }
10188        // `run_land` may have left `status` at `Landing` - still waiting on
10189        // CI or the owner's approval, not actually settled - so this has to
10190        // read whatever `status` ended up as here, not the `Merged` this
10191        // function set a few lines up.
10192        self.settle_questions();
10193        Ok(())
10194    }
10195
10196    /// Enter `land`.
10197    ///
10198    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10199    /// a resumed run's re-entry. `land::land` itself is what serialises the
10200    /// two git-mutating moments inside the loop — the rebase push and
10201    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10202    /// to hold a lock across the whole call, and doing so would serialise
10203    /// this run's CI wait against a *different* run's land-approval resume
10204    /// in the same repository, which is exactly the "must not wait on
10205    /// another task" property the daemon's slot-freeing exists to give.
10206    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10207        Box::pin(self.run_land_inner())
10208    }
10209
10210    async fn run_land_inner(&mut self) -> Result<()> {
10211        crate::pr_head::ensure_owner(&self.state)?;
10212        let url = self
10213            .state
10214            .pr
10215            .as_ref()
10216            .map(|pr| pr.url.clone())
10217            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10218            .unwrap_or_default();
10219        let url = url.lines().next().unwrap_or("").trim().to_owned();
10220        if !url.starts_with("http") {
10221            return Ok(());
10222        }
10223        // A land failure is not a lost run: the work is on a branch and the
10224        // pull request is open, which is exactly where a human takes over.
10225        loop {
10226            match land::land(&mut self.state, &url).await {
10227                Ok(_)
10228                    if self
10229                        .state
10230                        .merge_repairs
10231                        .last()
10232                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10233                {
10234                    if self.repair_merge_review().await? {
10235                        continue;
10236                    }
10237                }
10238                Ok(_) if self.state.resource_block.is_some() => {
10239                    return self.stop_for_resource();
10240                }
10241                Ok(pr) if self.state.parked => {
10242                    // `land` already saved the parked marker; nothing here
10243                    // overrides `status` back to a terminal value while an
10244                    // approval is still outstanding.
10245                    let _ = pr;
10246                }
10247                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10248                    self.state.status = RunStatus::Superseded;
10249                    self.state.save()?;
10250                }
10251                Ok(pr) => {
10252                    self.state.status = match pr.state {
10253                        land::PrLifecycle::Merged => RunStatus::Merged,
10254                        _ => RunStatus::Blocked,
10255                    };
10256                    // Downstream of a confirmed merge only - see
10257                    // `bump::should_release_bump`'s own doc for why this one
10258                    // check covers all three of `land`'s success paths.
10259                    // Best-effort: the run already landed, so a failure here
10260                    // (the decision call, `gh`, `cargo`) is recorded and never
10261                    // turns a landed run into a failed one.
10262                    if bump::should_release_bump(self.state.status)
10263                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10264                    {
10265                        // The event is the run's own record. Not-eligible cases
10266                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10267                        // `Err` is a bump that was tried and failed:
10268                        // `after_merge` itself raises the operator notice for
10269                        // that, whether or not a release PR exists yet.
10270                        self.state
10271                            .event("bump", format!("release bump skipped: {e:#}"));
10272                    }
10273                    // Independent of the bump, and best-effort in the same way:
10274                    // findings the merge left open become follow-up tasks.
10275                    if self.state.status == RunStatus::Merged {
10276                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10277                    }
10278                    self.state.save()?;
10279                }
10280                Err(e) => {
10281                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10282                        return Err(e);
10283                    }
10284                    self.state.status = RunStatus::Blocked;
10285                    self.state.event("land", format!("gave up: {e}"));
10286                    self.state.save()?;
10287                }
10288            }
10289            break;
10290        }
10291        Ok(())
10292    }
10293
10294    /// One repair cycle stays under the existing driver/task claim. An
10295    /// interrupted fixer is rolled back and held rather than run twice.
10296    async fn repair_merge_review(&mut self) -> Result<bool> {
10297        use crate::run::MergeRepairPhase as Phase;
10298        crate::pr_head::ensure_owner(&self.state)?;
10299        let i = self.state.merge_repairs.len() - 1;
10300        let request = self.state.merge_repairs[i].clone();
10301        if request.phase == Phase::Fixing {
10302            let restored = match self.state.winner().cloned() {
10303                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10304                None => Err(anyhow::anyhow!("repair has no winning branch")),
10305            };
10306            let why = match restored {
10307                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10308                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10309                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10310            };
10311            self.hold_merge_repair(i, why)?;
10312            return Ok(false);
10313        }
10314        // A completed repair gate is a publication checkpoint. On reentry,
10315        // reject external changes before the ordinary gate path can replace
10316        // that evidence by verifying a new head. Requested repairs still
10317        // start their own review generation below.
10318        if request.phase == Phase::Reviewing && self.state.gate_ran {
10319            let winner = self
10320                .state
10321                .winner()
10322                .context("repair has no winning branch")?;
10323            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10324            if self.state.gate_head.as_deref() != Some(head.as_str())
10325                || !git::is_clean(&winner.worktree).await?
10326            {
10327                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())?;
10328                return Ok(false);
10329            }
10330        }
10331        let failure = if i >= self.state.config.graph.land_rounds
10332            || self.state.config.graph.review_rounds == 0
10333        {
10334            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10335        } else {
10336            None
10337        };
10338        if let Some(why) = failure {
10339            self.hold_merge_repair(i, why)?;
10340            return Ok(false);
10341        }
10342        if request.phase == Phase::Requested {
10343            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10344                Ok(pr) => pr,
10345                Err(e) => {
10346                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10347                    return Ok(false);
10348                }
10349            };
10350            self.state.merge_repairs[i].phase = Phase::Fixing;
10351            self.state.land_approval = None;
10352            self.state.land_armed_head = None;
10353            self.state.save()?;
10354            // Serialize the exact records, including finding ids/details,
10355            // reconsideration reasons, final votes and verification output.
10356            let evidence = serde_json::to_string_pretty(&request)?;
10357            let reason = format!(
10358                "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}"
10359            );
10360            let budget = self.state.config.graph.land_rounds;
10361            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10362            match result {
10363                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10364                Ok(land::Fixed::Deferred) => {
10365                    // An unavailable fixer did not spend this repair request.
10366                    // Restore partial fallback work before retrying it, as for
10367                    // an interrupted repair, without closing the request.
10368                    let worktree = self
10369                        .state
10370                        .winner()
10371                        .context("repair has no winning branch")?
10372                        .worktree
10373                        .clone();
10374                    self.graft_restore(&worktree, &request.head).await?;
10375                    self.state.merge_repairs[i].phase = Phase::Requested;
10376                    self.stop_for_resource()?;
10377                    return Ok(false);
10378                }
10379                Ok(land::Fixed::Failed(why)) => {
10380                    self.hold_merge_repair(
10381                        i,
10382                        format!(
10383                            "repair failed: {why}; inspect the branch and run an explicit review"
10384                        ),
10385                    )?;
10386                    return Ok(false);
10387                }
10388                Err(e) => {
10389                    self.hold_merge_repair(
10390                        i,
10391                        format!(
10392                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10393                        ),
10394                    )?;
10395                    return Ok(false);
10396                }
10397            }
10398            // Even no change gets a real new reviewer wave. The previous
10399            // evidence remains in the request; a former clean/concluded round
10400            // cannot short-circuit the new review or gate.
10401            self.begin_merge_repair_review(i)?;
10402        }
10403        self.review_loop().await?;
10404        self.gate().await?;
10405        if self.resource_halt()? || self.state.parked {
10406            return Ok(false);
10407        }
10408        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10409            != Some(RunStatus::Gating)
10410            || !self.state.gate_allows_progress()
10411        {
10412            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10413            return Ok(false);
10414        }
10415        // Review and gate may have added commits after the initial repair.
10416        // Publish exactly their final head to the existing PR, with a lease.
10417        let winner = self
10418            .state
10419            .winner()
10420            .cloned()
10421            .context("repair has no winning branch")?;
10422        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10423        if self.state.gate_head.as_deref() != Some(after.as_str())
10424            || !git::is_clean(&winner.worktree).await?
10425        {
10426            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())?;
10427            return Ok(false);
10428        }
10429        let expected = self
10430            .state
10431            .pr_pushed_head
10432            .as_deref()
10433            .unwrap_or(&request.head)
10434            .to_owned();
10435        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10436        // Push the checked commit itself: a local ref moving after the check
10437        // must not change which commit the forge receives.
10438        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10439            return Ok(false);
10440        }
10441        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10442        let refspec = format!("{after}:refs/heads/{public}");
10443        let push = git::git_raw(
10444            &winner.worktree,
10445            &["push", &lease, &self.state.config.merge.remote, &refspec],
10446        )
10447        .await;
10448        match push {
10449            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10450            Ok(out) => {
10451                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10452                return Ok(false);
10453            }
10454            Err(e) => {
10455                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10456                return Ok(false);
10457            }
10458        }
10459        self.state.merge_repairs[i].phase = Phase::Complete;
10460        self.state.status = RunStatus::Landing;
10461        self.state.event(
10462            "repair",
10463            "new review and gate completed; fresh owner merge decision required",
10464        );
10465        self.state.save()?;
10466        Ok(true)
10467    }
10468
10469    fn merge_repair_artifacts(&self) -> PathBuf {
10470        let artifacts = agent::artifacts_dir(&self.state.dir());
10471        match self
10472            .state
10473            .merge_repairs
10474            .last()
10475            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10476        {
10477            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10478            None => artifacts,
10479        }
10480    }
10481
10482    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10483        if let Some(e2e) = self.state.head_e2e.take() {
10484            self.state
10485                .verification_history
10486                .push(crate::run::VerificationEvidence {
10487                    superseded_by: None,
10488                    archived_at: Some(Timestamp::now()),
10489                    fixes_spent: Some(self.state.gate_fixes.len()),
10490                    gate_head: None,
10491                    gate_ran: false,
10492                    gate: Vec::new(),
10493                    e2e: Some(e2e),
10494                });
10495        }
10496        self.state.reviews.clear();
10497        self.state.gate.clear();
10498        self.state.gate_ran = false;
10499        self.state.gate_head = None;
10500        self.state.gate_fixes.clear();
10501        self.state.gate_repair_e2e = None;
10502        self.state.pre_gate.clear();
10503        self.state.pre_gate_commit = None;
10504        self.state.contested_handoff = None;
10505        self.state.land_reruns = None;
10506        self.state.land_approval = None;
10507        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10508        self.state.status = RunStatus::Reviewing;
10509        self.state.save()
10510    }
10511
10512    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10513        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10514        self.state.merge_repairs[index].failure = Some(why.clone());
10515        self.state.status = RunStatus::Blocked;
10516        self.state.event("repair", why);
10517        self.state.save()
10518    }
10519
10520    // -------------------------------------------------------------- helpers
10521
10522    /// Fetch or create a seat, keeping its conversation across nodes.
10523    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10524        if let Some(existing) = self.state.seats.get(key)
10525            && existing.agent == agent
10526        {
10527            return existing.clone();
10528        }
10529        // A seat that changes agent mints its session id from the agent too,
10530        // like a handover: the old agent's uuid is already taken by the CLI.
10531        let fresh = if self.state.seats.contains_key(key) {
10532            handover_seat(key, agent, self.state.next_seat_seed())
10533        } else {
10534            SeatState::new(key, agent, self.state.seed)
10535        };
10536        self.state.seats.insert(key.to_owned(), fresh.clone());
10537        fresh
10538    }
10539
10540    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10541    /// seat to another roster agent, in which case that agent. Nodes that
10542    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10543    /// reconsideration) must keep talking to whoever answered it, not slip
10544    /// back to the agent that failed it.
10545    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10546        match self.state.seats.get(key) {
10547            Some(s) if s.agent != spec.id => {
10548                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10549            }
10550            _ => spec,
10551        }
10552    }
10553
10554    /// A candidate rendered for judging, with the leak policy applied.
10555    fn view(&self, c: &Candidate) -> CandidateView {
10556        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10557            .unwrap_or_default();
10558        let (patch, _) = blind::sanitize_patch(
10559            &format!("candidate {} patch", c.label),
10560            &raw,
10561            &self.state.config.blind,
10562        );
10563        CandidateView {
10564            label: c.label,
10565            branch: c.branch.clone(),
10566            summary: c.summary.clone(),
10567            stat: c.stat.clone(),
10568            patch,
10569        }
10570    }
10571
10572    /// The full candidate set as prompt text, for seats with no live session.
10573    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10574        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10575        prompt::judge(
10576            "(see above)",
10577            &views,
10578            self.roles.judges.len(),
10579            base_short,
10580            "en",
10581        )
10582    }
10583
10584    /// The final-vote prompt with everything a seat that has no session of its
10585    /// own needs: the candidates, the seat's own ranking and reasons, and the
10586    /// anonymised deliberation it took part in (only when there was one, so a
10587    /// handed-over seat never sees more than the seat it replaces did). The
10588    /// `Final vote` heading stays first.
10589    fn vote_prompt_full(
10590        &self,
10591        j: usize,
10592        labels: &[char],
10593        language: &str,
10594        candidates: &[Candidate],
10595        base_short: &str,
10596    ) -> String {
10597        let mut text = format!(
10598            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10599            prompt::final_vote(labels, language),
10600            self.state.instruction,
10601            self.candidate_block(candidates, base_short)
10602        );
10603        if let Some(own) = self
10604            .state
10605            .judgements
10606            .get(j)
10607            .filter(|r| !r.ranking.is_empty())
10608        {
10609            let reasons = own
10610                .reasons
10611                .iter()
10612                .map(|(k, v)| format!("- {k}: {v}"))
10613                .collect::<Vec<_>>()
10614                .join("\n");
10615            text.push_str(&format!(
10616                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10617                own.ranking.iter().collect::<String>(),
10618                if reasons.is_empty() {
10619                    ""
10620                } else {
10621                    ", because:\n"
10622                }
10623            ));
10624        }
10625        if !self.state.deliberation.is_empty() {
10626            text.push_str("\n# What was argued before this vote\n");
10627            for t in self.transcript(&[], j) {
10628                text.push_str(&format!(
10629                    "\n## {}{}\n\n{}\n",
10630                    t.who,
10631                    if t.is_self { " (you)" } else { "" },
10632                    t.body.trim()
10633                ));
10634            }
10635        }
10636        text
10637    }
10638
10639    /// Anonymised transcript for judge `self_idx`.
10640    ///
10641    /// The initial rankings are always the opening statements. Seeding them
10642    /// only when no turn had been taken yet meant every judge after the first
10643    /// argued against a single voice instead of against the actual split — the
10644    /// disagreement is the information, so it is always on the table.
10645    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10646        let mut turns = Vec::new();
10647        for j in &self.state.judgements {
10648            if j.ranking.is_empty() {
10649                continue;
10650            }
10651            let reasons = j
10652                .reasons
10653                .iter()
10654                .map(|(k, v)| format!("- {k}: {v}"))
10655                .collect::<Vec<_>>()
10656                .join("\n");
10657            turns.push(Turn {
10658                who: format!("Judge {} (opening ranking)", j.judge),
10659                is_self: j.judge == self_idx + 1,
10660                body: format!(
10661                    "Ranked {}{}{reasons}",
10662                    j.ranking.iter().collect::<String>(),
10663                    if reasons.is_empty() {
10664                        ""
10665                    } else {
10666                        ", because:\n"
10667                    }
10668                ),
10669            });
10670        }
10671        for t in self
10672            .state
10673            .deliberation
10674            .iter()
10675            .flat_map(|r| r.turns.iter())
10676            .chain(current)
10677        {
10678            turns.push(Turn {
10679                who: format!("Judge {}", t.judge),
10680                is_self: t.judge == self_idx + 1,
10681                body: t.body.clone(),
10682            });
10683        }
10684        turns
10685    }
10686}
10687
10688/// Does this seat still hold the context a follow-up prompt would rely on?
10689fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10690    agent::has_session(spec.kind, seat, sessions)
10691}
10692
10693/// The next entry in `roster` after `start`, never wrapping back to the
10694/// front, whose id is not in `tried` yet.
10695///
10696/// Starts one past `start` rather than at the front of `roster`: `start` is
10697/// the seat's own original position, and a seat whose candidate slot already
10698/// sits on the roster's second entry must fall through to the third next, not
10699/// restart at the first — which is very likely a different candidate's own
10700/// agent already. Never wraps back past `start`, for the same reason: an
10701/// entry earlier in the roster than the seat's own position is almost
10702/// certainly some *other* candidate slot's own agent, and once the tail of
10703/// the roster is exhausted there are no more untried agents for *this* seat
10704/// to fall through to — the caller's fallback chain ends there, exactly as
10705/// "no further untried agents remain in the list for that seat" asks for.
10706///
10707/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10708/// the same id twice (an operator's `roles.implementers` typo, or a
10709/// `[[agents]]` list reused across roles) must not let
10710/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10711/// over `roster` either finds an untried id or runs out, so this always
10712/// terminates regardless of duplicates.
10713fn next_untried_in_roster<'a>(
10714    roster: &'a [AgentSpec],
10715    start: usize,
10716    tried: &BTreeSet<String>,
10717) -> Option<&'a AgentSpec> {
10718    roster
10719        .get(start + 1..)?
10720        .iter()
10721        .find(|s| !tried.contains(&s.id))
10722}
10723
10724/// The successor for a seat, shared by all four seat kinds (implement, judge,
10725/// review, advise). `others` holds the ids that *currently* occupy the other
10726/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10727/// sees them), so roster entries beyond the seat count act as spares: a failed
10728/// seat goes to an agent no other seat holds whenever the roster permits.
10729///
10730/// `carried` is `Some` only for the review loop's carried failure history.
10731/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10732/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10733/// whole roster: untried and not another seat's occupant; (3) the plain walk
10734/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10735/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10736/// a better outcome than an empty seat, and it keeps the answer to "is there
10737/// a successor at all" exactly what it was before occupants were considered,
10738/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10739/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10740/// carried failure is a cheaper bet than doubling an agent on the panel, and
10741/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10742/// the same round are handled one at a time, so a seat later in the batch
10743/// sees an earlier one's new occupant but not yet its own freed agent.
10744fn pick_successor<'a>(
10745    roster: &'a [AgentSpec],
10746    start: usize,
10747    tried: &BTreeSet<String>,
10748    carried: Option<&BTreeSet<String>>,
10749    others: &BTreeSet<String>,
10750) -> Option<&'a AgentSpec> {
10751    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10752    roster
10753        .get(start + 1..)
10754        .and_then(|tail| {
10755            tail.iter()
10756                .filter(free)
10757                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10758        })
10759        .or_else(|| {
10760            carried
10761                .is_some()
10762                .then(|| roster.iter().find(free))
10763                .flatten()
10764        })
10765        .or_else(|| match carried {
10766            Some(c) => next_for_seat(roster, start, tried, c),
10767            None => next_untried_in_roster(roster, start, tried),
10768        })
10769}
10770
10771/// The next agent for a seat that carries its failure history across rounds
10772/// (the review loop). `round_tried` is this round's own bound and starts
10773/// empty every round; `carried_failed` only decides priority.
10774///
10775/// First: an id walking forward from `start`, never wrapping, that is neither
10776/// tried this round nor failed in an earlier one. Only when that is exhausted
10777/// does it rescue: the first roster id (in roster order, so this one *does*
10778/// look before `start`) not yet tried this round, which is by then a carried
10779/// failure. Each id is rescued at most once per round, so it cannot loop.
10780fn next_for_seat<'a>(
10781    roster: &'a [AgentSpec],
10782    start: usize,
10783    round_tried: &BTreeSet<String>,
10784    carried_failed: &BTreeSet<String>,
10785) -> Option<&'a AgentSpec> {
10786    roster
10787        .get(start + 1..)?
10788        .iter()
10789        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10790        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10791}
10792
10793/// Where a reviewer seat starts a round: the agent that last answered it when
10794/// it is still on the roster and not marked failed, else the spec's own agent
10795/// unless it failed, else the next roster agent that has not failed, else the
10796/// spec's own agent again (the whole roster failed). Ids no longer on the
10797/// roster are ignored. An empty roster has no handover, so the spec stands.
10798fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10799    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10800        return spec;
10801    };
10802    let ok = |id: &str| !h.failed.contains(id);
10803    if let Some(last) = h.last_ok.as_deref()
10804        && ok(last)
10805        && let Some(s) = roster.iter().find(|s| s.id == last)
10806    {
10807        return s.clone();
10808    }
10809    if ok(&spec.id) {
10810        return spec;
10811    }
10812    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10813    roster
10814        .get(from + 1..)
10815        .into_iter()
10816        .flatten()
10817        .chain(roster.iter())
10818        .find(|s| ok(&s.id))
10819        .cloned()
10820        .unwrap_or(spec)
10821}
10822
10823/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10824/// seed so a CLI that mints its session id up front (`--session-id`) never
10825/// reuses the uuid the previous agent already opened under the same seat key.
10826pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10827    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10828}
10829
10830/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10831/// so the classifier below and the code that builds the message cannot drift.
10832const TIMED_OUT: &str = "timed out";
10833
10834impl FailClass {
10835    /// `None` for an answer; otherwise how the turn failed.
10836    fn of(out: &AgentOutcome) -> Option<Self> {
10837        match out {
10838            AgentOutcome::Ok(_) => None,
10839            AgentOutcome::Quota(_) => Some(Self::Quota),
10840            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10841            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10842            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10843            // Not a failure of the agent. Callers check for it first; `None`
10844            // here means "no class to hand over on".
10845            AgentOutcome::ResourceBlocked(_) => None,
10846        }
10847    }
10848
10849    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10850    fn stem_word(&self) -> &'static str {
10851        match self {
10852            Self::Quota => "quota",
10853            _ => "handover",
10854        }
10855    }
10856}
10857
10858/// The message's first line with its variable parts removed — digit runs and
10859/// path-like tokens — so "exit code 2" and "exit code 7" read
10860/// as one kind of failure.
10861fn failure_signature(msg: &str) -> String {
10862    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10863    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10864    // the historical machine key while the process diagnosis uses readable prose.
10865    if let Some(code) = line
10866        .strip_prefix("process exited with no usable output (exit code ")
10867        .and_then(|s| s.strip_suffix(')'))
10868        .and_then(|s| s.parse::<i32>().ok())
10869    {
10870        line = format!("exited with some({code}) and no usable output");
10871    } else if matches!(
10872        line.as_str(),
10873        "process exited with no usable output (no exit code reported)"
10874            | "process exited with no usable output (exit code unavailable)"
10875    ) {
10876        line = "exited with none and no usable output".to_owned();
10877    }
10878    let mut out = Vec::new();
10879    for word in line.split_whitespace() {
10880        if word.contains('/') || word.contains('\\') {
10881            out.push("<path>".to_owned());
10882            continue;
10883        }
10884        let mut w = String::new();
10885        let mut in_digits = false;
10886        for c in word.chars() {
10887            if c.is_ascii_digit() {
10888                if !in_digits {
10889                    w.push('#');
10890                }
10891                in_digits = true;
10892            } else {
10893                in_digits = false;
10894                w.push(c);
10895            }
10896        }
10897        out.push(w);
10898    }
10899    out.join(" ").chars().take(120).collect()
10900}
10901
10902/// Whether a seat that just failed with `cur` may go to the next roster agent.
10903/// A quota or a timeout always may. Any other failure may not when the agent
10904/// before it failed the same way: an error the prompt causes would otherwise
10905/// walk the whole roster. `prev` is the class of the immediately preceding
10906/// agent's failure, so a quota or timeout in between breaks the run of
10907/// identical failures by itself.
10908fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10909    match cur {
10910        FailClass::Quota | FailClass::Timeout => true,
10911        FailClass::Other(_) => prev != Some(cur),
10912    }
10913}
10914
10915/// A short human reason for a failed outcome, for the handover record.
10916fn fail_reason(out: &AgentOutcome) -> String {
10917    match out {
10918        AgentOutcome::Ok(_) => String::new(),
10919        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10920        AgentOutcome::Dropped(o) => format!(
10921            "the CLI dropped the stream ({})",
10922            o.dropped
10923                .as_ref()
10924                .map(|d| d.why.as_str())
10925                .unwrap_or("it ended without delivering its answer")
10926        ),
10927        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10928            e.lines().next().unwrap_or("").chars().take(160).collect()
10929        }
10930    }
10931}
10932
10933/// Note one handover in the run: the structured record and, in the timeline,
10934/// the sentence a person reads. A quota keeps the wording it always had.
10935pub(crate) fn record_handover(
10936    state: &mut RunState,
10937    node: &str,
10938    seat: &str,
10939    from: &str,
10940    to: &str,
10941    class: &FailClass,
10942    reason: &str,
10943) {
10944    let message = if *class == FailClass::Quota {
10945        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10946    } else {
10947        format!("{seat}: handed over {from} -> {to} ({reason})")
10948    };
10949    state.event(node, message);
10950    state.handovers.push(Handover {
10951        at: Timestamp::now(),
10952        node: node.to_owned(),
10953        seat: seat.to_owned(),
10954        from: from.to_owned(),
10955        to: to.to_owned(),
10956        reason: reason.to_owned(),
10957    });
10958}
10959
10960/// Did this reply report running a command whose own CLI never confirmed an
10961/// exit status?
10962///
10963/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10964/// command *finished* (see that type's own doc), so this can only be `true`
10965/// for a command whose completion event carried no readable exit code — not
10966/// for one that simply is not mentioned at all. That is the one signal this
10967/// crate can read, from the same record `state.jobs` renders, about a reply
10968/// standing next to work its own CLI cannot vouch for finishing; it is
10969/// deliberately not a check on the exit code's *value* (a fixer legitimately
10970/// runs a command that fails mid-iteration before it succeeds) and not a
10971/// guess at a command still running in the background (which emits no event
10972/// at all, and so leaves no evidence here to find).
10973fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10974    commands.iter().any(|c| c.exit_code.is_none())
10975}
10976
10977/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10978/// trusted as a verified no-op — the adoption guard's own text-level half.
10979///
10980/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10981/// timed out): a marker only earns the benefit of the doubt from a turn the
10982/// CLI itself vouches for finishing properly, the same house style
10983/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10984/// *fix* report to for `commands`. A candidate that timed out, exited
10985/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10986/// is, whatever prose it wrote — this returns `None` before it ever looks at
10987/// `text`. The remaining guards (the tree really is empty, the evidence is
10988/// non-empty) are the caller's: this only reads what the reply *claimed*.
10989fn verified_noop_claim(
10990    usable: bool,
10991    commands: &[agent::CommandEvidence],
10992    text: &str,
10993) -> Option<String> {
10994    (usable && !has_unconfirmed_command(commands))
10995        .then(|| verdict::verified_noop(text))
10996        .flatten()
10997}
10998
10999fn short(commit: &str) -> String {
11000    commit.chars().take(7).collect()
11001}
11002
11003fn make_executable(path: &Path) -> Result<()> {
11004    #[cfg(unix)]
11005    {
11006        use std::os::unix::fs::PermissionsExt as _;
11007        let mut perms = std::fs::metadata(path)?.permissions();
11008        perms.set_mode(0o755);
11009        std::fs::set_permissions(path, perms)?;
11010    }
11011    #[cfg(not(unix))]
11012    {
11013        let _ = path;
11014    }
11015    Ok(())
11016}
11017
11018/// What every seat in one batch shares: where the answers are attributed, the
11019/// prompt overlay they inherit, and the build cache they are told to use.
11020///
11021/// A struct rather than four more parameters: `wave` also needs the run's
11022/// state (to record who is answering right now) and the attempt number, and
11023/// eight positional arguments is both unreadable and a clippy error.
11024struct WaveCtx<'a> {
11025    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11026    /// paid for it.
11027    run: &'a str,
11028    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11029    node: &'a str,
11030    prompts: &'a Prompts,
11031    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11032    cache: Option<&'a Path>,
11033    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11034    /// `JobRecord::round`. `None` for every other node.
11035    round: Option<usize>,
11036    /// Carry each seat's failed-agent history across waves (the review loop
11037    /// only): start-of-round priority and handover choice read
11038    /// [`RunState::seat_history`], and every answer or failure writes it.
11039    carry_seats: bool,
11040    /// The run's park / interrupt requests, so a wait for a shared resource
11041    /// can be abandoned the moment the operator asks to park.
11042    pauses: Option<(&'a Pause, &'a Pause)>,
11043}
11044
11045/// Shared scheduling policy for operations and spawned seat invocations.
11046fn repository_wait(
11047    state: &RunState,
11048    pauses: Option<(&Pause, &Pause)>,
11049) -> crate::repo_lock::WaitPolicy {
11050    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11051    let inherited = crate::repo_lock::WaitPolicy::current();
11052    crate::repo_lock::WaitPolicy::new(
11053        Duration::from_secs(state.config.graph.timeout_resource_wait),
11054        move || {
11055            inherited.cancelled()
11056                || pauses
11057                    .as_ref()
11058                    .is_some_and(|(a, b)| a.parked() || b.parked())
11059        },
11060    )
11061}
11062
11063fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11064    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11065        state.event("resource", timeout.0.description());
11066        state.resource_block = Some(timeout.0.clone());
11067        return;
11068    }
11069    if error.is::<crate::repo_lock::ResourceBlocked>() {
11070        state.resource_block = Some(crate::run::ResourceBlock {
11071            cause: crate::run::ResourceBlockCause::Other,
11072            node: "repository".into(),
11073            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11074                "disk admission"
11075            } else if error.to_string().contains("disk pressure") {
11076                "disk pressure"
11077            } else if error.to_string().contains("disk admission") {
11078                "disk admission"
11079            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11080                "incremental cache admission"
11081            } else {
11082                "repository coordination"
11083            }
11084            .into(),
11085            detail: format!("{error:#}"),
11086            at: Timestamp::now(),
11087        });
11088        state.event("resource", error.to_string());
11089    }
11090}
11091
11092async fn coordinate_operation(
11093    state: &mut RunState,
11094    cwd: &Path,
11095    wait: &crate::repo_lock::WaitPolicy,
11096) -> Result<Option<crate::repo_lock::SeatLease>> {
11097    let result =
11098        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11099            .await;
11100    if let Err(e) = &result {
11101        record_repository_block(state, e);
11102    }
11103    result
11104}
11105
11106/// Run one job, honouring the parallelism budget.
11107async fn run_one(
11108    job: SeatJob,
11109    sem: Arc<Semaphore>,
11110    ctx: &WaveCtx<'_>,
11111    state: &mut RunState,
11112    attempt: usize,
11113) -> (SeatState, AgentOutcome) {
11114    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11115        .await
11116        .pop()
11117        .expect("one job in, one result out");
11118    (seat, out)
11119}
11120
11121/// Run every job concurrently, capped by the semaphore, preserving order.
11122///
11123/// Every seat in the batch is recorded into [`RunState::active`] before the
11124/// wave starts and cleared as each answer lands, so the run's own record says
11125/// who is still being waited on rather than only who finished.
11126async fn wave(
11127    jobs: Vec<SeatJob>,
11128    sem: Arc<Semaphore>,
11129    ctx: &WaveCtx<'_>,
11130    state: &mut RunState,
11131    attempt: usize,
11132) -> Vec<(usize, SeatState, AgentOutcome)> {
11133    let WaveCtx {
11134        run,
11135        node,
11136        prompts,
11137        cache,
11138        round,
11139        carry_seats: _,
11140        pauses,
11141    } = *ctx;
11142    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11143    for job in &jobs {
11144        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11145    }
11146    if let Err(e) = state.save() {
11147        // A failed persist of "who is answering right now" must not abort the
11148        // wave: the seats are already being asked, and the alternative is
11149        // losing the answers to save a status line nobody may even be
11150        // watching.
11151        tracing::warn!("could not persist in-progress seats: {e:#}");
11152    }
11153    // Shared-mode waves keep their existing single lease. Isolated writers
11154    // acquire their own checkout's target at seat admission.
11155    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11156    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11157    // never borrowed from a job's agent budget (and never charged to it either,
11158    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11159    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11160    let cache_guard = if let Some(cache_dir) = cache {
11161        if jobs_had_a_writer {
11162            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11163            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11164            match acquire_cache_lease(
11165                state,
11166                cache_dir,
11167                &owner,
11168                resource_limit,
11169                node,
11170                node,
11171                &cancel,
11172            )
11173            .await
11174            {
11175                Ok(Some(g)) => Some(g),
11176                // Parking: leave without spawning anything. The run parks at
11177                // the next boundary and the seats are asked afresh on resume.
11178                Ok(None) => {
11179                    if let Some(block) = &mut state.resource_block {
11180                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11181                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11182                        };
11183                    }
11184                    return block_wave(
11185                        jobs,
11186                        state,
11187                        node,
11188                        attempt,
11189                        "parked while waiting for the shared build cache",
11190                    );
11191                }
11192                // An unreadable lease is not contention: keep the old
11193                // fallback (no shared cache for this wave's seats).
11194                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11195                Err(e) => {
11196                    // Writing seats may not build into a cache this run does
11197                    // not hold, and an agent that cannot be given one is not
11198                    // asked at all: the run stops resumably instead.
11199                    let why = format!("{e:#}");
11200                    state.event(
11201                        "resource",
11202                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11203                    );
11204                    return block_wave(jobs, state, node, attempt, &why);
11205                }
11206            }
11207        } else {
11208            None
11209        }
11210    } else {
11211        None
11212    };
11213    // Every job keeps its whole budget: the wait above was not the agent's.
11214    // Restart the seats' clocks so "started" means "being spawned now".
11215    state.seats_spawning(node, attempt);
11216    if let Err(e) = state.save() {
11217        tracing::warn!("could not persist the start of a wave: {e:#}");
11218    }
11219    // Queueing behind this wave's own seats for a parallelism slot is normal
11220    // (each of them is bounded by its own agent timeout); only a wait beyond
11221    // all of them plus the resource limit means the slots never came back.
11222    let slot_limit = resource_limit
11223        + jobs
11224            .iter()
11225            .map(|j| j.timeout)
11226            .max()
11227            .unwrap_or_default()
11228            .saturating_mul(jobs.len() as u32);
11229    let mut set = tokio::task::JoinSet::new();
11230    // Seats announce themselves here the moment they hold a parallelism
11231    // permit, i.e. just before their CLI is spawned.
11232    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11233    let overlay = prompts.overlay(node);
11234    let repository_wait = repository_wait(state, pauses);
11235    for (i, mut job) in jobs.into_iter().enumerate() {
11236        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11237        if cache.is_some() {
11238            job.prompt.push('\n');
11239            job.prompt
11240                .push_str(&prompt::build_cache_note(node, job.allow_write));
11241        }
11242        let sem = Arc::clone(&sem);
11243        let run = run.to_owned();
11244        let node = node.to_owned();
11245        // Only implementers were told about the task's attachments, so only
11246        // their seats get the directory widened for reading.
11247        let attachments = if node == "implement" {
11248            state.attachments.clone()
11249        } else {
11250            Vec::new()
11251        };
11252        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11253        // `prompt::build_cache_note`'s doc for why setting it anyway is
11254        // exactly how a sandboxed reviewer's write refusal got reported as a
11255        // defect in the patch, not a property of its own seat. And a
11256        // write-allowed one is handed it only when the lease above was
11257        // actually acquired: a wave that could not get it (`cache_guard` is
11258        // `None`, see its own comment) must not send seats to build into a
11259        // directory this run does not hold - that is the exact concurrent,
11260        // unmanaged-write race this module exists to prevent, not something
11261        // "proceeding anyway" is allowed to reintroduce.
11262        let cache = cache
11263            .filter(|_| job.allow_write && cache_guard.is_some())
11264            .map(Path::to_path_buf);
11265        let spawned_tx = spawned_tx.clone();
11266        let repository_wait = repository_wait.clone();
11267        let coordination = state.config.coordination.clone();
11268        let fetched_base = state.fetched_base.clone();
11269        set.spawn(async move {
11270            // A wait for a parallelism slot is scheduling, not the agent: it
11271            // is bounded by its own limit and ends as a resource block, never
11272            // as a timeout of the agent that was not started.
11273            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11274                Ok(p) => p,
11275                Err(_) => {
11276                    return (
11277                        i,
11278                        job.seat,
11279                        AgentOutcome::ResourceBlocked(format!(
11280                            "no parallel slot became free within {}s",
11281                            slot_limit.as_secs()
11282                        )),
11283                        None,
11284                        false,
11285                    );
11286                }
11287            };
11288            spawned_tx.send(job.seat.key.clone()).ok();
11289            let mut seat = job.seat;
11290            let out = repository_wait
11291                .scope(agent::invoke(
11292                    &job.spec,
11293                    &mut seat,
11294                    &Invocation {
11295                        coordination: coordination.as_ref(),
11296                        fetched_base: fetched_base.as_ref(),
11297                        cwd: &job.cwd,
11298                        prompt: &job.prompt,
11299                        timeout: job.timeout,
11300                        allow_write: job.allow_write,
11301                        sessions: job.sessions,
11302                        artifacts: &job.artifacts,
11303                        stem: &job.stem,
11304                        run: &run,
11305                        node: &node,
11306                        cache_dir: cache.as_deref(),
11307                        attachments: &attachments,
11308                        writable: &[],
11309                    },
11310                ))
11311                .await;
11312            let cache_block = out
11313                .as_ref()
11314                .err()
11315                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11316                .map(|timeout| timeout.0.clone());
11317            let interrupted = out
11318                .as_ref()
11319                .err()
11320                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11321            let out = match out {
11322                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11323                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11324                // Billed work the CLI failed to hand over is not an ordinary
11325                // failure, but its text is the CLI's raw error JSON, not an
11326                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11327                // read it as one by forgetting to check. `usable()` is always
11328                // false here (dropped implies an empty response), so this has
11329                // to be checked before the catch-all `Failed` below or the
11330                // one shape this exists for is lost with the rest.
11331                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11332                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11333                Ok(o) => AgentOutcome::Failed(format!(
11334                    "process exited with no usable output ({})",
11335                    crate::notices::exit_status(o.exit_code)
11336                )),
11337                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11338                    AgentOutcome::ResourceBlocked(e.to_string())
11339                }
11340                Err(e) => AgentOutcome::Failed(e.to_string()),
11341            };
11342            (i, seat, out, cache_block, interrupted)
11343        });
11344    }
11345    drop(spawned_tx);
11346    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11347    loop {
11348        let joined = tokio::select! {
11349            Some(key) = spawned_rx.recv() => {
11350                // The clock of this seat starts now, not when it queued.
11351                state.seat_spawned(&key);
11352                if let Err(e) = state.save() {
11353                    tracing::warn!("could not persist a seat's start: {e:#}");
11354                }
11355                continue;
11356            }
11357            joined = set.join_next() => joined,
11358        };
11359        let Some(joined) = joined else {
11360            break;
11361        };
11362        let (i, seat, out, cache_block, interrupted) = match joined {
11363            Ok(v) => v,
11364            // No seat to clear: a panicked task never reported which one it
11365            // was. The defensive sweep below this loop is what stops that
11366            // seat's `active` entry from surviving forever.
11367            Err(e) => {
11368                tracing::error!("agent task panicked: {e}");
11369                continue;
11370            }
11371        };
11372        state.seat_finished(&seat.key);
11373        if interrupted
11374            && node == "implement"
11375            && let Some(label) = state
11376                .candidates
11377                .iter()
11378                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11379                .map(|candidate| candidate.label)
11380        {
11381            state.candidate_preservation.insert(
11382                label,
11383                "interrupted implementation awaiting persistence".into(),
11384            );
11385            state.interrupted_implementations.insert(label);
11386        }
11387        if let Some(block) = cache_block
11388            && state.resource_block.is_none()
11389        {
11390            state.event("resource", block.description());
11391            state.resource_block = Some(block);
11392        }
11393        if let AgentOutcome::ResourceBlocked(why) = &out
11394            && state.resource_block.is_none()
11395        {
11396            state.resource_block = Some(crate::run::ResourceBlock {
11397                cause: crate::run::ResourceBlockCause::Other,
11398                node: node.to_owned(),
11399                kind: if why.contains("disk pressure") {
11400                    "disk pressure"
11401                } else if why.contains("disk admission") {
11402                    "disk admission"
11403                } else if why.contains(crate::incremental::BLOCKED) {
11404                    "incremental cache admission"
11405                } else if why.contains(crate::build_target::KIND) {
11406                    crate::build_target::KIND
11407                } else if why.contains("repository coordination") {
11408                    "repository coordination"
11409                } else {
11410                    "parallel slot"
11411                }
11412                .to_owned(),
11413                detail: why.clone(),
11414                at: Timestamp::now(),
11415            });
11416            let activity = if interrupted {
11417                "agent execution interrupted"
11418            } else {
11419                "no agent was started"
11420            };
11421            state.event("resource", format!("{node}: {activity} - {why}"));
11422        }
11423        record_jobs(state, node, round, &seat.key, &out);
11424        if let Err(e) = state.save() {
11425            tracing::warn!("could not persist a seat's completion: {e:#}");
11426        }
11427        if collected.len() <= i {
11428            collected.resize_with(i + 1, || None);
11429        }
11430        collected[i] = Some((i, seat, out));
11431    }
11432    // Belt-and-braces for the panic branch above: every seat this exact batch
11433    // started shares this `(node, attempt)` pair, and every seat that finished
11434    // normally already cleared itself, so anything left tagged with it here
11435    // can only be a panicked task's leftover. Cleared unconditionally rather
11436    // than left to read as still answering forever.
11437    if state
11438        .active
11439        .values()
11440        .any(|a| a.node == node && a.attempt == attempt)
11441    {
11442        state
11443            .active
11444            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11445        if let Err(e) = state.save() {
11446            tracing::warn!("could not persist the end of a wave: {e:#}");
11447        }
11448    }
11449    // Whether or not the lease above was actually held, several worktrees
11450    // may just have built into the cache with nothing here able to name one
11451    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11452    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11453    // clean it might not have strictly needed; trusting a stale match would
11454    // cost it a wrong answer.
11455    if let Some(cache_dir) = cache
11456        && jobs_had_a_writer
11457    {
11458        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11459    }
11460    if let Some(guard) = cache_guard {
11461        guard.release();
11462    }
11463    collected.into_iter().flatten().collect()
11464}
11465
11466/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11467/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11468/// this is data collection, not the fix-specific completion contract in
11469/// [`Runner::continue_fix_report`], and applies regardless of which node
11470/// asked.
11471///
11472/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11473/// evidence from; `Failed` does not, and correctly contributes nothing — a
11474/// timeout or crash is not itself evidence about a command the seat may have
11475/// started.
11476fn record_jobs(
11477    state: &mut RunState,
11478    node: &str,
11479    round: Option<usize>,
11480    seat: &str,
11481    out: &AgentOutcome,
11482) {
11483    let commands: &[agent::CommandEvidence] = match out {
11484        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11485        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11486    };
11487    let checked_at = Timestamp::now();
11488    for c in commands {
11489        state.jobs.push(JobRecord {
11490            node: node.to_owned(),
11491            round,
11492            seat: seat.to_owned(),
11493            id: c.id.clone(),
11494            description: c.description.clone(),
11495            checked_at,
11496            status: match c.exit_code {
11497                Some(0) => JobStatus::Completed,
11498                Some(_) => JobStatus::Failed,
11499                None => JobStatus::Unknown,
11500            },
11501            exit_code: c.exit_code,
11502            result_summary: c.result_summary.clone(),
11503            source: c.source.clone(),
11504        });
11505    }
11506}
11507
11508/// Is a review round clean, given how many reviewer seats answered against
11509/// how many the round expected?
11510///
11511/// A seat that never answered (timeout, crash, unparsable output) is not a
11512/// seat that read the patch and found nothing — treating it as such is
11513/// exactly the bug this function exists to close. Under the default `block`
11514/// policy a missing seat can never be clean; `warn` still requires the seats
11515/// that *did* answer to have found nothing blocking and verification to be
11516/// green.
11517///
11518/// `quota_missing` narrows that `block` default for exactly one cause of
11519/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11520/// a session limit lifts by the very next round buys nothing — the seat is
11521/// asked again with the same quota — so once every missing seat is accounted
11522/// for by a quota loss (and at least one seat *did* answer, so a decision has
11523/// something to rest on) the round is decided on the panel that could answer,
11524/// same as `warn` would. A panel that lost every seat to quota is not
11525/// decided here: `answered == 0` falls through to the existing `block`
11526/// fallback so a fully collapsed panel still waits rather than landing on no
11527/// review at all.
11528fn round_is_clean(
11529    blocking: usize,
11530    e2e_ok: bool,
11531    answered: usize,
11532    expected: usize,
11533    quota_missing: usize,
11534    policy: IncompleteReviewPolicy,
11535) -> bool {
11536    if blocking != 0 || !e2e_ok {
11537        return false;
11538    }
11539    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11540        return true;
11541    }
11542    answered > 0 && expected - answered <= quota_missing
11543}
11544
11545/// The review loop's own conclusion, derived entirely from its persisted
11546/// round records and the round budget that produced them — never from
11547/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11548/// recomputes the identical answer regardless of what an earlier node in the
11549/// same walk, or a previous walk, did to `status`.
11550///
11551/// `None` while more rounds remain to try, including when review never ran
11552/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11553/// gone clean, or the budget is spent, or the tree has stopped moving (see
11554/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11555///
11556/// - An incomplete panel that raised nothing is missing input, not a
11557///   verified tree — never a hand-off candidate, whatever verification said
11558///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11559/// - Otherwise, green e2e on the last round hands off (see
11560///   [`Runner::stop_reviewing`]); red e2e blocks.
11561///
11562/// A last round whose own verification is still `ResourceBlocked` — magi
11563/// itself never got a command to run, not evidence the patch is broken —
11564/// is neither: this returns `None` for it too, the same as "more rounds
11565/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11566/// handling of that shape) instead of this cheap recomputation guessing a
11567/// verdict a real attempt never produced.
11568pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11569    if max_rounds == 0
11570        || reviews.last().is_some_and(|r| {
11571            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11572        })
11573    {
11574        return Some(RunStatus::Gating);
11575    }
11576    let last = reviews.last()?;
11577    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11578    if reviews.len() < max_rounds && !stagnant {
11579        return None;
11580    }
11581    if last.incomplete() && last.blocking == 0 {
11582        return Some(RunStatus::Blocked);
11583    }
11584    if last.e2e_status() == E2eStatus::ResourceBlocked
11585        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11586    {
11587        return None;
11588    }
11589    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11590        RunStatus::Gating
11591    } else {
11592        RunStatus::Blocked
11593    })
11594}
11595
11596/// How long a re-ask may take, given the budget the first attempt had.
11597///
11598/// A `nudged` retry is a request to restate an answer the seat has already
11599/// worked out: it carries no new work, so it does not deserve the original
11600/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11601/// 133 seconds while a third sat for over ten minutes on a resumed session
11602/// holding 410 KB of prior output - and because the retry had inherited the
11603/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11604/// judging round whose other seats were long finished.
11605///
11606/// A quarter of the budget, with a floor so that a deliberately short timeout
11607/// does not collapse to nothing. A retry that re-sends the whole prompt
11608/// (because the seat kept no context) is the original job again, and keeps the
11609/// original budget.
11610pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11611    if nudged {
11612        (full / 4).max(Duration::from_secs(120)).min(full)
11613    } else {
11614        full
11615    }
11616}
11617
11618/// Run a wave and parse each reply, re-asking the seats whose reply was
11619/// unusable.
11620///
11621/// The re-ask is a nudge rather than the whole prompt again when the seat still
11622/// holds its conversation, which is the difference between a cheap retry and
11623/// paying for the entire candidate set twice.
11624///
11625/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11626/// successor in `roster` is handed to it instead of being re-asked: the
11627/// handover is the retry. A seat with no successor left (a single-agent
11628/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11629/// the asks to one seat in one node number at most
11630/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11631/// is asked once (a dropped stream is nudged first), and only the last agent
11632/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11633/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11634/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11635/// other failure stops the chain when the previous agent failed the same way
11636/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11637/// [`has_context`] is false and the job's own full prompt and full budget are
11638/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11639/// intermediate ones are not losses) and is returned as a failure like any
11640/// other absent seat — the caller decides whether the panel still has a
11641/// quorum. An empty `roster` disables handover: failures are nudged as they
11642/// always were, and a quota is simply lost. A reply that fails to parse or
11643/// validate is the prompt's doing and is only ever nudged, never handed over.
11644///
11645/// The returned [`SeatState`] names the agent that answered (or tried last).
11646#[allow(clippy::too_many_arguments)]
11647async fn ask_json_wave<T>(
11648    jobs: Vec<SeatJob>,
11649    sem: Arc<Semaphore>,
11650    retries: usize,
11651    roster: &[AgentSpec],
11652    ctx: &WaveCtx<'_>,
11653    losses: &mut Vec<QuotaLoss>,
11654    state: &mut RunState,
11655    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11656) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11657where
11658    T: serde::de::DeserializeOwned + Send + 'static,
11659{
11660    ask_wave_with(
11661        jobs,
11662        sem,
11663        retries,
11664        roster,
11665        ctx,
11666        losses,
11667        state,
11668        &|text: &str| {
11669            let v = verdict::extract_json::<T>(text)?;
11670            validate(&v)?;
11671            Ok(v)
11672        },
11673    )
11674    .await
11675}
11676
11677/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11678/// a node whose answer is prose (deliberation) shares the same handover,
11679/// failure classification, quota bookkeeping and bounds instead of a copy.
11680///
11681/// A seat handed to another roster agent is sent the job's `handover` prompt
11682/// (when it has one) rather than `prompt`: the new agent has no session, so a
11683/// resume-style prompt would be incomplete. That holds for the handover ask
11684/// and for every nudge to that agent whose `has_context` is false.
11685#[allow(clippy::too_many_arguments)]
11686async fn ask_wave_with<T>(
11687    jobs: Vec<SeatJob>,
11688    sem: Arc<Semaphore>,
11689    retries: usize,
11690    roster: &[AgentSpec],
11691    ctx: &WaveCtx<'_>,
11692    losses: &mut Vec<QuotaLoss>,
11693    state: &mut RunState,
11694    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11695) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11696where
11697    T: Send + 'static,
11698{
11699    let n = jobs.len();
11700    let originals: Vec<SeatJob> = jobs;
11701    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11702    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11703    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11704    // answer, N once it has gone through N nudges. Read back once this
11705    // returns, so a caller building a history record (`ReviewRecord`) can
11706    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11707    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11708    // field's own doc.
11709    let mut nudges: Vec<usize> = vec![0; n];
11710    // The agent now occupying each seat, the ids it has already been through,
11711    // where in the roster the walk began, the class of the last failure, and
11712    // the stem word of a handover not yet asked (full prompt, full budget).
11713    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11714    let mut tried: Vec<BTreeSet<String>> = specs
11715        .iter()
11716        .map(|s| BTreeSet::from([s.id.clone()]))
11717        .collect();
11718    let starts: Vec<usize> = specs
11719        .iter()
11720        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11721        .collect();
11722    let carry = ctx.carry_seats && !roster.is_empty();
11723    // Carried across rounds: ids that failed the seat earlier, and how the
11724    // last failure went (so a repeat of it is not handed over again).
11725    let carried: Vec<BTreeSet<String>> = originals
11726        .iter()
11727        .map(|j| {
11728            state
11729                .seat_history
11730                .get(&j.seat.key)
11731                .filter(|_| carry)
11732                .map(|h| h.failed.clone())
11733                .unwrap_or_default()
11734        })
11735        .collect();
11736    let mut prev: Vec<Option<FailClass>> = originals
11737        .iter()
11738        .map(|j| {
11739            state
11740                .seat_history
11741                .get(&j.seat.key)
11742                .filter(|_| carry)
11743                .and_then(|h| h.last_fail.clone())
11744        })
11745        .collect();
11746    let next_agent =
11747        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11748            let others: BTreeSet<String> = specs
11749                .iter()
11750                .enumerate()
11751                .filter(|(j, _)| *j != i)
11752                .map(|(_, s)| s.id.clone())
11753                .collect();
11754            pick_successor(
11755                roster,
11756                starts[i],
11757                tried,
11758                carry.then(|| &carried[i]),
11759                &others,
11760            )
11761            .cloned()
11762        };
11763    let mut fresh: Vec<Option<String>> = vec![None; n];
11764    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11765    let mut pending: Vec<usize> = (0..n).collect();
11766
11767    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11768    // asks: an agent with a successor is asked once and handed over, and only
11769    // a seat with no successor spends `retries` nudges on the same agent. This
11770    // only guarantees the loop's own termination whatever those say.
11771    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11772    for round in 0..max_rounds {
11773        if pending.is_empty() {
11774            break;
11775        }
11776        let mut batch = Vec::with_capacity(pending.len());
11777        let mut renudged: Vec<&str> = Vec::new();
11778        for &i in &pending {
11779            let src = &originals[i];
11780            // A seat now held by another agent than the job named has no
11781            // session of its own: it gets the full-context prompt whenever
11782            // it is asked in full (the handover ask, a nudge it cannot
11783            // resume).
11784            let full: &str = match &src.handover {
11785                Some(h) if specs[i].id != src.spec.id => h,
11786                _ => &src.prompt,
11787            };
11788            // The prompt and the budget are one decision: a nudge restates
11789            // finished work, a re-sent prompt redoes it.
11790            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11791                (
11792                    full.to_owned(),
11793                    src.timeout,
11794                    format!("{}-{word}-{}", src.stem, specs[i].id),
11795                )
11796            } else if nudges[i] == 0 {
11797                (full.to_owned(), src.timeout, src.stem.clone())
11798            } else {
11799                renudged.push(src.seat.key.as_str());
11800                let why = done[i]
11801                    .as_ref()
11802                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11803                    .unwrap_or_else(|| "no parsable answer".to_owned());
11804                let nudge = prompt::nudge(&why);
11805                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11806                let prompt = if nudged {
11807                    nudge
11808                } else {
11809                    format!("{full}\n\n---\n\n{nudge}")
11810                };
11811                (
11812                    prompt,
11813                    retry_budget(src.timeout, nudged),
11814                    format!("{}-retry{}", src.stem, nudges[i]),
11815                )
11816            };
11817            batch.push(SeatJob {
11818                spec: specs[i].clone(),
11819                seat: seats[i].clone(),
11820                cwd: src.cwd.clone(),
11821                prompt,
11822                timeout,
11823                allow_write: src.allow_write,
11824                sessions: src.sessions,
11825                artifacts: src.artifacts.clone(),
11826                stem,
11827                handover: None,
11828            });
11829        }
11830
11831        if !renudged.is_empty() {
11832            state.event(
11833                ctx.node,
11834                format!("retry {round}: re-asking {}", renudged.join(", ")),
11835            );
11836        }
11837        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11838        let mut still = Vec::new();
11839        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11840            seats[i] = seat;
11841            // No agent was asked: nothing to hand over, nudge, remember or
11842            // charge. The caller sees `resource_block` and stops the node.
11843            if let AgentOutcome::ResourceBlocked(why) = &out {
11844                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11845                continue;
11846            }
11847            let class = FailClass::of(&out);
11848            // A dropped stream is nudged first (the conversation is still
11849            // there to pick up); only a seat whose nudges are spent hands over.
11850            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11851                && nudges[i] < retries
11852                && !roster.is_empty();
11853            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11854                let next = should_hand_over(prev[i].as_ref(), &cur)
11855                    .then(|| next_agent(i, &tried[i], &specs))
11856                    .flatten();
11857                if carry {
11858                    let h = state
11859                        .seat_history
11860                        .entry(originals[i].seat.key.clone())
11861                        .or_default();
11862                    h.failed.insert(specs[i].id.clone());
11863                    h.last_fail = Some(cur.clone());
11864                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11865                        h.last_ok = None;
11866                    }
11867                    // Saved before the next agent is asked, so a restart in
11868                    // between does not forget who failed.
11869                    if let Err(e) = state.save() {
11870                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11871                    }
11872                }
11873                if let Some(next) = next {
11874                    record_handover(
11875                        state,
11876                        ctx.node,
11877                        &originals[i].seat.key,
11878                        &specs[i].id,
11879                        &next.id,
11880                        &cur,
11881                        &fail_reason(&out),
11882                    );
11883                    tried[i].insert(next.id.clone());
11884                    prev[i] = Some(cur.clone());
11885                    seats[i] =
11886                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11887                    specs[i] = next;
11888                    fresh[i] = Some(cur.stem_word().to_owned());
11889                    nudges[i] = 0;
11890                    done[i] = Some(Err(anyhow::anyhow!(
11891                        "handed over after: {}",
11892                        fail_reason(&out)
11893                    )));
11894                    still.push(i);
11895                    continue;
11896                }
11897            }
11898            if carry
11899                && !nudge_first
11900                && let Some(cur) = class.clone()
11901            {
11902                // The chain ended here (no successor, or a repeated failure).
11903                let h = state
11904                    .seat_history
11905                    .entry(originals[i].seat.key.clone())
11906                    .or_default();
11907                h.failed.insert(specs[i].id.clone());
11908                h.last_fail = Some(cur);
11909            }
11910            let parsed = match out {
11911                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11912                AgentOutcome::Quota(o) => {
11913                    last_quota[i] = o.quota.clone();
11914                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11915                }
11916                // Not a parseable answer: the nudge loop re-asks it, which is
11917                // exactly what a dropped stream needs. Just don't hand its raw
11918                // error JSON to `extract_json`.
11919                AgentOutcome::Dropped(o) => {
11920                    let why = o
11921                        .dropped
11922                        .as_ref()
11923                        .map(|d| d.why.as_str())
11924                        .unwrap_or("the CLI ended the stream without delivering its answer");
11925                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11926                }
11927                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11928                    Err(anyhow::anyhow!(e))
11929                }
11930            };
11931            let quota = class == Some(FailClass::Quota);
11932            let failed = parsed.is_err();
11933            if !failed && matches!(ctx.node, "judge" | "vote") {
11934                // A validated answer restores this seat's quorum presence,
11935                // including on the normal path after an all-seat block.
11936                state
11937                    .quota
11938                    .retain(|loss| loss.seat != originals[i].seat.key);
11939            }
11940            done[i] = Some(parsed);
11941            if carry && !failed {
11942                let h = state
11943                    .seat_history
11944                    .entry(originals[i].seat.key.clone())
11945                    .or_default();
11946                h.failed.remove(&specs[i].id);
11947                h.last_ok = Some(specs[i].id.clone());
11948                h.last_fail = None;
11949            }
11950            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11951            // fail the same way; and never re-ask a seat that already parsed.
11952            // A failed agent that still has a successor is not re-asked
11953            // either: the handover was its remedy and has just been refused
11954            // (the chain stops on a repeated failure class). A seat with no
11955            // successor left (a single-agent roster, the roster's tail, or an
11956            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11957            let agent_failure = class.is_some()
11958                && !nudge_first
11959                && !roster.is_empty()
11960                && next_agent(i, &tried[i], &specs).is_some();
11961            if failed && !quota && !agent_failure && nudges[i] < retries {
11962                nudges[i] += 1;
11963                still.push(i);
11964            }
11965        }
11966        pending = still;
11967    }
11968
11969    // One loss per seat whose chain ended on a quota: the intermediate ones
11970    // were absorbed by a handover and are not losses.
11971    for (i, q) in last_quota.into_iter().enumerate() {
11972        if let Some(quota) = q {
11973            losses.push(QuotaLoss::from_report(
11974                originals[i].seat.key.clone(),
11975                ctx.node,
11976                Some(&quota),
11977            ));
11978        }
11979    }
11980
11981    // A stalled quorum already has its own recovery checkpoint. Refresh
11982    // its missing seats before deciding whether it can resume.
11983    if state.status != RunStatus::Stalled
11984        && ctx.node != "deliberate"
11985        && n > 0
11986        && losses.len() == n
11987        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11988    {
11989        block_machine_outage(state, ctx.node, losses);
11990        state.quota.append(losses);
11991    }
11992
11993    seats
11994        .into_iter()
11995        .zip(done)
11996        .zip(nudges)
11997        .map(|((seat, res), attempts)| {
11998            (
11999                seat,
12000                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12001                attempts,
12002            )
12003        })
12004        .collect()
12005}
12006
12007/// A node with no available agent has no task verdict. Preserve the node
12008/// checkpoint and record why a subsequent explicit resume is needed.
12009pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12010    let mut auth: Vec<_> = losses
12011        .iter()
12012        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12013        .map(|loss| loss.agent.clone())
12014        .collect();
12015    auth.sort();
12016    auth.dedup();
12017    let (kind, detail) = if auth.is_empty() {
12018        (
12019            "agent usage limit",
12020            "All seats reached their agent usage limits; resume after usage is available"
12021                .to_owned(),
12022        )
12023    } else {
12024        (
12025            "agent authentication",
12026            format!(
12027                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12028                auth.join(", ")
12029            ),
12030        )
12031    };
12032    state.resource_block = Some(crate::run::ResourceBlock {
12033        node: node.to_owned(),
12034        kind: kind.to_owned(),
12035        cause: crate::run::ResourceBlockCause::Other,
12036        detail: detail.clone(),
12037        at: Timestamp::now(),
12038    });
12039    state.event(node, detail);
12040}
12041
12042/// Did the wave end without asking any agent (see [`block_wave`])?
12043fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12044    results
12045        .iter()
12046        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12047}
12048
12049/// Settle a wave that never spawned anything: every job answers
12050/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12051/// else about the seat (session, history, quota) is touched.
12052fn block_wave(
12053    jobs: Vec<SeatJob>,
12054    state: &mut RunState,
12055    node: &str,
12056    attempt: usize,
12057    why: &str,
12058) -> Vec<(usize, SeatState, AgentOutcome)> {
12059    state.resource_wait = None;
12060    state
12061        .active
12062        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12063    if let Err(e) = state.save() {
12064        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12065    }
12066    jobs.into_iter()
12067        .enumerate()
12068        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12069        .collect()
12070}
12071
12072/// Acquire the shared build cache's lease, waiting out contention within
12073/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12074/// unbounded wait is never acceptable).
12075///
12076/// A first, non-blocking check happens before ever waiting; if it finds the
12077/// lease busy, that fact is logged as a `verify` event *and* flushed with
12078/// [`RunState::save`] immediately — not only once the wait finally succeeds
12079/// or gives up — so a `magi show` run by a different process while this one
12080/// is still waiting reads a `run.json` that says so, rather than whatever it
12081/// looked like before the wait started. The same applies to the terminal
12082/// failure: logged and saved before this returns `Err`, so a caller that
12083/// could not get the lease at all still leaves a legible record of why.
12084async fn acquire_cache_lease(
12085    state: &mut RunState,
12086    cache_dir: &Path,
12087    owner: &crate::cache::Owner,
12088    budget: Duration,
12089    node: &str,
12090    context: &str,
12091    cancel: &(dyn Fn() -> bool + Sync),
12092) -> Result<Option<crate::cache::Guard>> {
12093    let home = crate::run::home();
12094    let kind = if crate::build_target::isolated(&state.config) {
12095        crate::build_target::KIND
12096    } else {
12097        "shared build cache"
12098    };
12099    let started = Instant::now();
12100    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12101        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12102        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12103        Err(e) => {
12104            state.event(
12105                "verify",
12106                format!(
12107                    "{context}: could not check the {kind} at {}: {e:#}",
12108                    cache_dir.display()
12109                ),
12110            );
12111            if let Err(e2) = state.save() {
12112                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12113            }
12114            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12115        }
12116    };
12117    state.event(
12118        "verify",
12119        format!(
12120            "{context}: waiting for the {kind} at {} ({})",
12121            cache_dir.display(),
12122            busy.describe()
12123        ),
12124    );
12125    // Seats of this node are waiting, not running: say so, so the countdown a
12126    // reader sees only ever measures an agent that has been spawned.
12127    state.resource_wait = Some(crate::run::ResourceWait {
12128        node: context.to_owned(),
12129        kind: kind.to_owned(),
12130        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12131        since: Timestamp::now(),
12132        limit_secs: budget.as_secs(),
12133    });
12134    if let Err(e) = state.save() {
12135        tracing::warn!("could not persist a cache wait: {e:#}");
12136    }
12137    let remaining = budget.saturating_sub(started.elapsed());
12138    let waited = crate::cache::wait_for_unless(
12139        &home,
12140        cache_dir,
12141        owner,
12142        remaining,
12143        Duration::from_secs(5),
12144        cancel,
12145    )
12146    .await;
12147    state.resource_wait = None;
12148    let cause = match &waited {
12149        Ok(Some(_)) => None,
12150        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12151        Err(error)
12152            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12153        {
12154            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12155                target: cache_dir.to_owned(),
12156                waited_secs: started.elapsed().as_secs(),
12157                limit_secs: budget.as_secs(),
12158            })
12159        }
12160        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12161            Some(crate::run::ResourceBlockCause::Timeout {
12162                waited_secs: started.elapsed().as_secs(),
12163                limit_secs: budget.as_secs(),
12164            })
12165        }
12166        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12167    };
12168    if let Some(cause) = cause {
12169        let detail = match &waited {
12170            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12171            Err(error) => format!("{error:#}"),
12172        };
12173        state.resource_block = Some(crate::run::ResourceBlock {
12174            cause,
12175            node: node.to_owned(),
12176            kind: kind.into(),
12177            detail: format!("{}: {detail}", cache_dir.display()),
12178            at: Timestamp::now(),
12179        });
12180        state.event(
12181            "resource",
12182            state.resource_block.as_ref().unwrap().description(),
12183        );
12184    }
12185    if let Err(error) = state.save() {
12186        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12187    }
12188    waited
12189}
12190
12191/// The lease state could not be read at all (unreadable lease file, a
12192/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12193/// known to be contended, so a wave degrades to running without a shared cache
12194/// instead of stopping on a hold that [`crate::triage`] could never release.
12195#[derive(Debug)]
12196struct CacheCheckError(String);
12197
12198impl std::fmt::Display for CacheCheckError {
12199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12200        f.write_str(&self.0)
12201    }
12202}
12203
12204impl std::error::Error for CacheCheckError {}
12205
12206/// Keep a specific acquisition outcome when the caller adds command evidence.
12207fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12208    let kind = if crate::build_target::isolated(&state.config) {
12209        crate::build_target::KIND
12210    } else {
12211        "shared build cache"
12212    };
12213    state
12214        .resource_block
12215        .get_or_insert_with(|| crate::run::ResourceBlock {
12216            cause: crate::run::ResourceBlockCause::Other,
12217            node: node.to_owned(),
12218            kind: kind.into(),
12219            detail: format!("{error:#}"),
12220            at: Timestamp::now(),
12221        });
12222    if let Err(error) = state.save() {
12223        tracing::warn!("could not persist cache resource block: {error:#}");
12224    }
12225}
12226
12227tokio::task_local! {
12228    static VERIFY_TARGET: PathBuf;
12229}
12230
12231/// Run `body` — a verify command batch — while holding the shared build
12232/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12233/// never interleave with another borrower's build against the same
12234/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12235/// timeout, or a human's own `magi review`. See the `cache` module doc for
12236/// why this matters more than Cargo's own per-target locking covers — two
12237/// *different* worktrees building the same package name/version into one
12238/// cache directory is a staleness bug, not a lock contention one.
12239///
12240/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12241/// agent waves do. Repository scheduling also has its own bounded,
12242/// cancellable resource-wait policy. Contention must not consume the
12243/// verification budget: `body` receives the full `budget` after both leases
12244/// are acquired and the cache is fresh. Without a shared cache, only
12245/// repository coordination is acquired before handing over the full budget.
12246///
12247/// A lease that cannot be acquired within the resource wait is reported as a single
12248/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12249/// verification — the same shape a spawn failure already takes in
12250/// [`run_commands`], so a caller need not special-case it.
12251#[allow(clippy::too_many_arguments)]
12252async fn with_cache_lease<'s, F, Fut>(
12253    state: &'s mut RunState,
12254    cache_dir: Option<&Path>,
12255    node: &str,
12256    seat: &str,
12257    worktree: &Path,
12258    head: &str,
12259    budget: Duration,
12260    context: &str,
12261    wait: &crate::repo_lock::WaitPolicy,
12262    body: F,
12263) -> Result<(Vec<CommandOutcome>, bool)>
12264where
12265    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12266    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12267{
12268    // Match editing waves: cache first, repository second. In particular,
12269    // pre_gate must never hold the repository while waiting for a wave's cache.
12270    let started = Instant::now();
12271    let home = crate::run::home();
12272    let isolated = crate::build_target::isolated(&state.config);
12273    let planned_target = if isolated {
12274        let plan = (|| -> Result<PathBuf> {
12275            crate::build_target::supports(&state.config)?;
12276            crate::build_target::resolve(&home, worktree)
12277        })();
12278        match plan {
12279            Ok(path) => Some(path),
12280            Err(error) => {
12281                record_cache_error(state, node, &error);
12282                return Ok((
12283                    vec![CommandOutcome {
12284                        command: "(planning isolated build cache)".into(),
12285                        code: None,
12286                        output_tail: format!("{error:#}"),
12287                        duration_ms: 0,
12288                        resource_blocked: true,
12289                        ..Default::default()
12290                    }],
12291                    false,
12292                ));
12293            }
12294        }
12295    } else {
12296        None
12297    };
12298    let cache_dir = planned_target.as_deref().or(cache_dir);
12299    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12300    let guard = if let Some(cache_dir) = cache_dir {
12301        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12302        match acquire_cache_lease(
12303            state,
12304            cache_dir,
12305            &owner,
12306            resource_limit,
12307            node,
12308            context,
12309            &|| wait.cancelled(),
12310        )
12311        .await
12312        .and_then(|g| {
12313            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12314        }) {
12315            Ok(g) => Some(g),
12316            Err(e) => {
12317                record_cache_error(state, node, &e);
12318                return Ok((
12319                    vec![CommandOutcome {
12320                        command: if isolated {
12321                            "(waiting for the isolated build cache)"
12322                        } else {
12323                            "(waiting for the shared build cache)"
12324                        }
12325                        .into(),
12326                        code: None,
12327                        output_tail: e.to_string(),
12328                        duration_ms: started.elapsed().as_millis() as u64,
12329                        resource_blocked: true,
12330                        ..Default::default()
12331                    }],
12332                    false,
12333                ));
12334            }
12335        }
12336    } else {
12337        None
12338    };
12339    let _coordination = coordinate_operation(state, worktree, wait).await?;
12340    if let Some(path) = &planned_target {
12341        state.event(node, format!("isolated build target: {}", path.display()));
12342    }
12343    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12344        let identity = crate::cache::Identity::new(worktree, head);
12345        let fresh = crate::cache::ensure_fresh(
12346            &home,
12347            cache_dir,
12348            &identity,
12349            &state.config.verify.cargo_manifests(),
12350        );
12351        if let Err(e) = fresh {
12352            record_cache_error(state, node, &e);
12353            state.event(
12354                "verify",
12355                format!(
12356                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12357                    worktree.display(),
12358                    short(head)
12359                ),
12360            );
12361            if let Some(guard) = guard {
12362                guard.release();
12363            }
12364            return Ok((
12365                vec![CommandOutcome {
12366                    command: "(confirming the build cache is fresh)".into(),
12367                    code: None,
12368                    output_tail: e.to_string(),
12369                    duration_ms: started.elapsed().as_millis() as u64,
12370                    resource_blocked: true,
12371                    ..Default::default()
12372                }],
12373                false,
12374            ));
12375        }
12376    }
12377    let future = body(state, budget);
12378    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12379        VERIFY_TARGET.scope(target, future).await
12380    } else {
12381        future.await
12382    };
12383    if !timed_out_pids.is_empty() {
12384        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12385    }
12386    // Drop repository coordination before releasing the cache, reversing the
12387    // acquisition order. A cancelled/error future also drops both guards.
12388    drop(_coordination);
12389    if let Some(guard) = guard {
12390        guard.release();
12391    }
12392    Ok((outcomes, retried))
12393}
12394
12395/// Poll `pids` — commands [`run_commands`] reports as still running when its
12396/// own timeout elapsed — until every one is confirmed gone, or
12397/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12398///
12399/// Real confirmation where confirmation is possible, not a substitute for
12400/// full process-tree observation: a grandchild the timed-out process spawned
12401/// and that survives independently of it is invisible to a pid check the
12402/// same way it always was, and continuing to observe and collect *that*
12403/// stays a different piece of work with its own owner. This only narrows a
12404/// fixed blind wait into an actual check of the pids this process does know
12405/// about.
12406async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12407    wait_for_pids_with(
12408        pids,
12409        crate::proc::pid_alive,
12410        LEASE_RELEASE_POLL,
12411        LEASE_RELEASE_MAX_WAIT,
12412    )
12413    .await;
12414}
12415
12416/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12417/// interval and ceiling supplied by the caller, so the polling *logic* -
12418/// returns as soon as every pid reports dead, gives up at the ceiling
12419/// otherwise - is testable on millisecond durations without asking the real
12420/// OS about a pid at all.
12421async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12422    pids: &[u32],
12423    alive: F,
12424    poll: Duration,
12425    max_wait: Duration,
12426) {
12427    let deadline = Instant::now() + max_wait;
12428    loop {
12429        if pids.iter().all(|&pid| !alive(pid)) {
12430            return;
12431        }
12432        if Instant::now() >= deadline {
12433            return;
12434        }
12435        tokio::time::sleep(poll).await;
12436    }
12437}
12438
12439/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12440/// admission that it could not even get a verify command to run, as opposed
12441/// to evidence the command actually produced? A caller that would otherwise
12442/// read a resource-blocked outcome as a red command must check this first:
12443/// see [`Runner::gate`], which retries rather than records `Blocked` when
12444/// this is true.
12445fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12446    outcomes.iter().any(|o| o.resource_blocked)
12447}
12448
12449/// What [`Runner::gate_fix_round`] decided.
12450pub(crate) enum GateFix {
12451    /// The tree changed and `verify.e2e` is still green: run the gate again.
12452    Retry,
12453    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12454    /// last failure stands and the run ends blocked.
12455    Stop,
12456    /// `verify.e2e` could not run after the fix (magi's own contention):
12457    /// decide nothing now, a later reentry retries.
12458    Defer,
12459}
12460
12461/// Is every red command in `outcomes` an ordinary failure the code could
12462/// explain: it ran, exited non-zero, and said something?
12463///
12464/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12465/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12466/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12467/// what the command is stays the gate's business.
12468pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12469    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12470    red.peek().is_some()
12471        && red.all(|o| {
12472            !o.resource_blocked
12473                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12474                && !o.output_tail.trim().is_empty()
12475        })
12476}
12477
12478/// Describe one verify command's outcome for the event log, distinguishing a
12479/// build/link failure — the toolchain never produced a binary to run — from
12480/// an actual test failure, since only the latter is a verdict on the patch.
12481fn e2e_outcome_label(o: &CommandOutcome) -> String {
12482    if o.ok() {
12483        return "pass".to_owned();
12484    }
12485    let reason = if o.build_failed() {
12486        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12487    } else {
12488        format!("FAIL ({:?})", o.code)
12489    };
12490    format!(
12491        "{reason}\n{}",
12492        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12493    )
12494}
12495
12496/// Does `outcomes` hold a failure worth one more run on the same commit?
12497///
12498/// Only an ordinary test result qualifies: every red command ran, exited
12499/// non-zero and said which way (not a build/link failure, a timeout or kill,
12500/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12501/// evidence about the machine or the toolchain, never about a flaky test.
12502fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12503    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12504    red.peek().is_some()
12505        && !verify_inconclusive(outcomes)
12506        && red.all(|o| {
12507            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12508        })
12509}
12510
12511/// Run `verify.e2e`, retrying once if the first attempt could not build or
12512/// link — a build/link failure is frequently a race against a shared
12513/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12514/// `verify` event per command, tagged with `context` (normally `"round N"`)
12515/// so the call sites that need this — the ordinary per-round leg in
12516/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12517/// will ever call a round green, `verify_current_head` and the gate-repair
12518/// check — read identically in the event log.
12519///
12520/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12521/// only after the failed commands have run once more on the same commit, in
12522/// the same worktree and — because the caller holds it around this whole
12523/// function — under the same cache lease, with a full `timeout` of their own
12524/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12525/// flake: the head is verified, the first failure is recorded and filed
12526/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12527/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12528/// preserving bounded evidence and artifact references for both attempts;
12529/// it claims a matching reproduction only when both attempts yield identical
12530/// confirmed terminal test failures. One verification is therefore run at most
12531/// three times: the build/link retry, then this one rerun. `round` is the
12532/// review round the verification belongs to, if any.
12533async fn run_e2e_with_retry(
12534    state: &mut RunState,
12535    shell: &[String],
12536    commands: &[String],
12537    worktree: &Path,
12538    timeout: Duration,
12539    context: &str,
12540    round: Option<usize>,
12541) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12542    let (mut e2e, mut timed_out_pids) = run_commands(
12543        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12544    )
12545    .await;
12546    for o in &e2e {
12547        state.event(
12548            "verify",
12549            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12550        );
12551    }
12552    // A build/link failure is not a verdict on the patch — it is frequently a
12553    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12554    // one retry before letting a red like that decide the round.
12555    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12556    if verify_retried {
12557        state.event(
12558            "verify",
12559            format!(
12560                "{context}: verify could not build/link, not a test result — retrying once \
12561                 before concluding"
12562            ),
12563        );
12564        let retried = run_commands(
12565            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12566        )
12567        .await;
12568        e2e = retried.0;
12569        // Both attempts' timeouts matter, not just the last one: the first
12570        // attempt's descendants may still be alive alongside the retry's.
12571        timed_out_pids.extend(retried.1);
12572        for o in &e2e {
12573            state.event(
12574                "verify",
12575                format!(
12576                    "{context}: retry `{}` -> {}",
12577                    o.command,
12578                    e2e_outcome_label(o)
12579                ),
12580            );
12581        }
12582    }
12583    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12584        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12585        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12586        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12587        state.event(
12588            "verify",
12589            format!(
12590                "{context}: {} failed with a test result — running it once more on the same \
12591                 commit {} before deciding",
12592                rerun_commands
12593                    .iter()
12594                    .map(|c| format!("`{c}`"))
12595                    .collect::<Vec<_>>()
12596                    .join(", "),
12597                short(&head)
12598            ),
12599        );
12600        let (second, pids) = run_commands(
12601            state,
12602            "verify",
12603            "e2e",
12604            1 + usize::from(verify_retried),
12605            shell,
12606            &rerun_commands,
12607            worktree,
12608            timeout,
12609        )
12610        .await;
12611        timed_out_pids.extend(pids);
12612        for o in &second {
12613            state.event(
12614                "verify",
12615                format!(
12616                    "{context}: rerun `{}` -> {}",
12617                    o.command,
12618                    e2e_outcome_label(o)
12619                ),
12620            );
12621        }
12622        for (slot, &i) in failed.iter().enumerate() {
12623            let Some(again) = second.get(slot) else {
12624                break;
12625            };
12626            let first = std::mem::replace(&mut e2e[i], again.clone());
12627            if again.ok() {
12628                let signature = crate::flake::signature(&first.output_tail, first.code);
12629                let flake = crate::run::VerifyFlake {
12630                    round,
12631                    context: context.to_owned(),
12632                    head: head.clone(),
12633                    command: first.command.clone(),
12634                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12635                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12636                    at: Timestamp::now(),
12637                    task: None,
12638                    filed: false,
12639                    filing_error: None,
12640                };
12641                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12642            } else if !again.resource_blocked {
12643                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
12644                let message = crate::verify_evidence::rerun_event_message(
12645                    context,
12646                    &e2e[i].command,
12647                    &comparison,
12648                );
12649                e2e[i].rerun_comparison = Some(comparison);
12650                state.event("verify", message);
12651            }
12652        }
12653    }
12654    (e2e, verify_retried, timed_out_pids)
12655}
12656
12657/// Run configured shell commands in `cwd`, in order. The second element is
12658/// the pid of every command that hit `timeout` and was still running when
12659/// this stopped waiting on it (best-effort: `None` when the platform did not
12660/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12661/// that releases a shared resource afterward needs to know.
12662///
12663/// Records `task` into [`RunState::active`] at every command boundary
12664/// (`RunState::task_command`) and clears it once the whole list has run
12665/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12666/// for minutes with no seat and no output of its own to show for it (see
12667/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12668/// apart from "not yet run" without this), and this is the only place that
12669/// knows which command is running right now and how many are left. Three
12670/// saves per command — start, not per second — matching the same "only at a
12671/// boundary" rule [`wave`] already follows for seats.
12672#[allow(clippy::too_many_arguments)]
12673async fn run_commands(
12674    state: &mut RunState,
12675    node: &str,
12676    task: &str,
12677    attempt: usize,
12678    shell: &[String],
12679    commands: &[String],
12680    cwd: &Path,
12681    timeout: Duration,
12682) -> (Vec<CommandOutcome>, Vec<u32>) {
12683    let isolated = crate::build_target::isolated(&state.config);
12684    if isolated && let Some(block) = &state.resource_block {
12685        return (
12686            vec![CommandOutcome {
12687                command: "(isolated build admission)".into(),
12688                code: None,
12689                output_tail: block.description(),
12690                duration_ms: 0,
12691                resource_blocked: true,
12692                ..Default::default()
12693            }],
12694            Vec::new(),
12695        );
12696    }
12697    if commands.is_empty() {
12698        // Nothing to mark as running and nothing to clear — an empty list
12699        // means "not configured", and touching `active` (or the disk) over
12700        // that would be a write for every round of a repo with no
12701        // `verify.e2e` / `verify.gate` commands at all.
12702        return (Vec::new(), Vec::new());
12703    }
12704    let mut out = Vec::new();
12705    let mut timed_out_pids = Vec::new();
12706    let total = commands.len();
12707    for (idx, command) in commands.iter().enumerate() {
12708        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12709        if let Err(e) = state.save() {
12710            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12711        }
12712        let started = Instant::now();
12713        let mut cmd = tokio::process::Command::new(&shell[0]);
12714        cmd.quiet();
12715        // Verify the checkout as a standalone caller. Worker ownership and
12716        // pinned executable selection belong to this driver, not to tests or
12717        // tools it runs. Preserve home/seat context and Running's containment.
12718        for key in crate::worker::INVOCATION_ENV {
12719            cmd.env_remove(key);
12720        }
12721        cmd.env_remove(crate::build_id::EXPECT_ENV);
12722        cmd.args(&shell[1..])
12723            .current_dir(cwd)
12724            .stdin(std::process::Stdio::null())
12725            .stdout(std::process::Stdio::piped())
12726            .stderr(std::process::Stdio::piped())
12727            .kill_on_drop(true);
12728        let mut outputs = Vec::new();
12729        let mut cache = None;
12730        let home = crate::run::home();
12731        let head = if isolated {
12732            Some(git::rev_parse(cwd, "HEAD").await)
12733        } else {
12734            None
12735        };
12736        let protected = (|| -> Result<()> {
12737            crate::incremental::configure(&mut cmd, cwd)?;
12738            cache = if isolated {
12739                let target = VERIFY_TARGET
12740                    .try_with(Clone::clone)
12741                    .context("isolated verification has no target lease")?;
12742                cmd.arg(crate::build_target::command::normalize(command)?);
12743                crate::build_target::command::configure(&mut cmd, &target)?;
12744                Some(target)
12745            } else {
12746                crate::build_target::command::clear(&mut cmd)?;
12747                cmd.arg(command);
12748                state.config.cache_dir()
12749            };
12750            let mut paths = vec![cwd.to_owned()];
12751            if let Some(cache) = &cache {
12752                paths.push(cache.clone());
12753            }
12754            let admit = if isolated {
12755                crate::retention::OutputLease::admit_isolated
12756            } else {
12757                crate::retention::OutputLease::admit
12758            };
12759            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12760            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12761                outputs.push(guard);
12762            }
12763            if let Some(cache) = &cache {
12764                outputs.push(crate::retention::OutputLease::cache(
12765                    &crate::run::home(),
12766                    cache,
12767                    false,
12768                )?);
12769                if let Some(head) = head {
12770                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12771                    if task == "pre_gate" {
12772                        crate::cache::invalidate_identity(&home, cache);
12773                    }
12774                }
12775            }
12776            Ok(())
12777        })();
12778        if let Err(e) = protected {
12779            let detail = format!("execution admission unavailable: {e:#}");
12780            state.resource_block = Some(crate::run::ResourceBlock {
12781                cause: crate::run::ResourceBlockCause::Other,
12782                node: node.to_owned(),
12783                kind: if detail.contains("disk admission") {
12784                    "disk admission"
12785                } else {
12786                    "output ownership"
12787                }
12788                .to_owned(),
12789                detail: detail.clone(),
12790                at: Timestamp::now(),
12791            });
12792            out.push(CommandOutcome {
12793                command: command.clone(),
12794                code: None,
12795                output_tail: detail,
12796                duration_ms: 0,
12797                resource_blocked: true,
12798                ..Default::default()
12799            });
12800            break;
12801        }
12802        let spawned = if isolated {
12803            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12804        } else {
12805            crate::seat_process::Running::spawn(cmd, None, outputs)
12806        };
12807        let (code, out_text, err_text, body) = match spawned {
12808            Ok(mut running) => {
12809                let pid = running.child().id();
12810                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12811                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12812                let mut paths = vec![cwd.to_owned()];
12813                if let Some(cache) = cache {
12814                    paths.push(cache);
12815                }
12816                let mut pressure = None;
12817                let status = tokio::select! {
12818                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12819                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12820                        pressure = Some(reason); None
12821                    }
12822                };
12823                let (code, failure) = match status {
12824                    Some(Ok(Ok(status))) => (
12825                        status.code(),
12826                        status
12827                            .code()
12828                            .is_none()
12829                            .then(|| format!("command terminated: {status}")),
12830                    ),
12831                    Some(Ok(Err(error))) => {
12832                        (None, Some(format!("failed waiting for command: {error}")))
12833                    }
12834                    Some(Err(_)) => {
12835                        // Leased cleanup confirms process-tree death itself.
12836                        // Unleased commands still need the caller's PID check
12837                        // after kill-on-drop, before releasing cache ownership.
12838                        if !running.coordinated()
12839                            && let Some(pid) = pid
12840                        {
12841                            timed_out_pids.push(pid);
12842                        }
12843                        (
12844                            None,
12845                            Some(format!("timed out after {}s", timeout.as_secs())),
12846                        )
12847                    }
12848                    None => (None, None),
12849                };
12850                running.finish().await;
12851                if let Some(reason) = pressure {
12852                    state.resource_block = Some(crate::run::ResourceBlock {
12853                        cause: crate::run::ResourceBlockCause::Other,
12854                        node: node.to_owned(),
12855                        kind: "disk pressure".to_owned(),
12856                        detail: reason.clone(),
12857                        at: Timestamp::now(),
12858                    });
12859                    out.push(CommandOutcome {
12860                        command: command.clone(),
12861                        code: None,
12862                        output_tail: reason,
12863                        duration_ms: started.elapsed().as_millis() as u64,
12864                        resource_blocked: true,
12865                        ..Default::default()
12866                    });
12867                    break;
12868                }
12869                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12870                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
12871                let mut body = out_text.clone();
12872                body.push_str(&err_text);
12873                if let Some(failure) = failure {
12874                    body.push('\n');
12875                    body.push_str(&failure);
12876                }
12877                (code, out_text, err_text, body)
12878            }
12879            Err(e) if isolated => {
12880                let e = anyhow::Error::new(e)
12881                    .context(format!("could not start managed build `{}`", shell[0]));
12882                record_cache_error(state, node, &e);
12883                out.push(CommandOutcome {
12884                    command: command.clone(),
12885                    code: None,
12886                    output_tail: format!("{e:#}"),
12887                    duration_ms: 0,
12888                    resource_blocked: true,
12889                    ..Default::default()
12890                });
12891                break;
12892            }
12893            Err(e) => (
12894                None,
12895                String::new(),
12896                String::new(),
12897                format!("failed to spawn `{}`: {e}", shell[0]),
12898            ),
12899        };
12900        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12901        let mut artifact = None;
12902        if !body.is_empty() {
12903            // The full text is kept whatever the summary dropped. A fresh
12904            // name per command so a resume or retry never overwrites an
12905            // earlier run's output. A failed write changes no verdict.
12906            match crate::run::write_verification_artifact(state, task, &body) {
12907                Ok(name) => {
12908                    let rel = format!("artifacts/{name}");
12909                    if summary != body {
12910                        summary = format!("[full output: {rel}]\n{summary}");
12911                    }
12912                    artifact = Some(rel);
12913                }
12914                Err(e) => {
12915                    let warning = format!("could not save the full {task} output: {e:#}");
12916                    tracing::warn!("{warning}");
12917                    state.event(node, warning);
12918                    if summary != body {
12919                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12920                    }
12921                }
12922            }
12923        }
12924        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12925        let mut outcome = CommandOutcome {
12926            command: command.clone(),
12927            code,
12928            output_tail: summary,
12929            duration_ms: started.elapsed().as_millis() as u64,
12930            resource_blocked,
12931            artifact,
12932            failure_evidence: None,
12933            rerun_comparison: None,
12934        };
12935        if !outcome.ok() && !outcome.resource_blocked {
12936            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
12937                code,
12938                outcome.build_failed(),
12939                &out_text,
12940                &err_text,
12941            ));
12942        }
12943        out.push(outcome);
12944        if resource_blocked {
12945            state.resource_block = Some(crate::run::ResourceBlock {
12946                cause: crate::run::ResourceBlockCause::Other,
12947                node: node.to_owned(),
12948                kind: "incremental cache admission".into(),
12949                detail: body,
12950                at: Timestamp::now(),
12951            });
12952            break;
12953        }
12954    }
12955    state.task_finished(task);
12956    if let Err(e) = state.save() {
12957        tracing::warn!("could not persist the end of {task}: {e:#}");
12958    }
12959    (out, timed_out_pids)
12960}
12961
12962/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12963/// section (`report::run`) and in the `merge` event this node records — for
12964/// the operator to run by hand.
12965///
12966/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12967/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12968/// merge commits", or "require linear history") rejects the push a `--no-ff`
12969/// merge would produce, which is exactly the guidance this function replaces.
12970/// `message`'s first line becomes the squash commit's subject, matching the
12971/// note `report::run` prints alongside this command — see that function for
12972/// why an explicit subject is not optional there.
12973fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12974    let repo = repo.display();
12975    match style {
12976        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12977        MergeStyle::Squash => {
12978            // The subject sits inside double quotes, and a title an agent
12979            // wrote may carry the characters that break out of them.
12980            let subject = message
12981                .lines()
12982                .next()
12983                .unwrap_or(branch)
12984                .replace(['\\', '"', '$', '`'], "");
12985            format!(
12986                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12987            )
12988        }
12989        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12990    }
12991}
12992
12993/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12994/// under the hood, rejects a `title` over 256 characters and the whole
12995/// command fails — no PR at all, for a run whose body was otherwise fine
12996/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12997/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12998/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12999/// this bound. It is a margin, not a guarantee — a title packed
13000/// with multi-unit characters could still in principle land close to the
13001/// edge, but a real task title's occasional emoji or accented letter fits
13002/// comfortably inside it.
13003const PR_TITLE_MAX: usize = 240;
13004
13005/// A pull request title from the opening line of `text`, or `None` when that
13006/// line is not English (GitHub text is) or has no letters.
13007///
13008/// A line within `max` is kept as is. A longer one is cut at the end of its
13009/// first sentence when that falls inside `max`, else at a word boundary with a
13010/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13011/// make every merely-truncated title look non-English). The language check
13012/// runs on the kept text before any mark is added, so only what GitHub will
13013/// show is judged: an English opening followed by non-ASCII far past the cut
13014/// still passes.
13015fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13016    let line = queue::first_line(text)?;
13017    let chars: Vec<char> = line.chars().collect();
13018    let (kept, mark) = if chars.len() <= max {
13019        (line.to_owned(), "")
13020    } else if let Some(end) = sentence_end(&chars, max) {
13021        (chars[..end].iter().collect::<String>(), "")
13022    } else {
13023        let room = max.saturating_sub(3);
13024        // Cut at the last space inside the room; when the char just past the
13025        // room is a space the room already ends on a word.
13026        let cut = if chars[room].is_whitespace() {
13027            room
13028        } else {
13029            chars[..room]
13030                .iter()
13031                .rposition(|c| c.is_whitespace())
13032                .unwrap_or(room)
13033        };
13034        let head: String = chars[..cut].iter().collect();
13035        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13036        (head.to_owned(), "...")
13037    };
13038    if kept.is_empty() {
13039        return None;
13040    }
13041    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13042        return None;
13043    }
13044    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13045        return None;
13046    }
13047    Some(format!("{kept}{mark}"))
13048}
13049
13050/// The char length of the first sentence of `chars` when it ends within `max`
13051/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13052/// abbreviations so `e.g. foo` does not end a title early.
13053fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13054    const MIN: usize = 20;
13055    for i in MIN..max.min(chars.len()) {
13056        if !matches!(chars[i], '.' | '!' | '?') {
13057            continue;
13058        }
13059        let Some(&next) = chars.get(i + 1) else {
13060            continue;
13061        };
13062        if !next.is_whitespace() {
13063            continue;
13064        }
13065        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13066        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13067            continue;
13068        }
13069        let word: String = chars[..i]
13070            .iter()
13071            .rev()
13072            .take_while(|c| !c.is_whitespace())
13073            .collect::<Vec<_>>()
13074            .into_iter()
13075            .rev()
13076            .collect();
13077        let word = word.to_ascii_lowercase();
13078        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13079            continue;
13080        }
13081        let end = chars[..i]
13082            .iter()
13083            .rposition(|c| !c.is_whitespace())
13084            .map_or(i, |p| p + 1);
13085        return Some(end);
13086    }
13087    None
13088}
13089
13090/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13091/// change: a title and a body describing what was *implemented*, not the task
13092/// that asked for it. A task reads as a request; a reader of the merged
13093/// history wants the change.
13094struct PrMessage {
13095    title: String,
13096    body: String,
13097}
13098
13099impl PrMessage {
13100    /// Title, blank line, body. The first line is the squash/merge commit
13101    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13102    /// has to stay one sensible line.
13103    fn commit_message(&self) -> String {
13104        format!("{}\n\n{}", self.title, self.body)
13105    }
13106}
13107
13108/// The text after a leading `TITLE:` (any case) on `line`.
13109fn title_marker(line: &str) -> Option<&str> {
13110    let line = line.trim();
13111    let head = line.get(..6)?;
13112    head.eq_ignore_ascii_case("title:")
13113        .then(|| line[6..].trim())
13114}
13115
13116/// The implementer's own one-line title: the `TITLE:` line the implement
13117/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13118/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13119/// source, and a title that says as much is refused here too.
13120fn summary_title(summary: &str) -> Option<String> {
13121    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13122    let raw = title_marker(first)?;
13123    if raw.is_empty() {
13124        return None;
13125    }
13126    let title = queue::title_from(raw, PR_TITLE_MAX);
13127    let lower = title.to_ascii_lowercase();
13128    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13129        return None;
13130    }
13131    Some(title)
13132}
13133
13134/// How `open_review`'s instruction begins; see [`landing_title`].
13135const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13136
13137/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13138pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13139
13140/// Does this run review work that already existed, rather than implement a
13141/// task? Runs recorded before `reviewed_commits` existed carry only the
13142/// candidate marker.
13143pub(crate) fn is_review_run(state: &RunState) -> bool {
13144    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13145}
13146
13147/// The title of a review-only run: the subject of the oldest commit under
13148/// review. Later commits are usually fixups, and `instruction` is the review
13149/// prompt, which says nothing about the change. GitHub text is English, so a
13150/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13151fn review_title(state: &RunState) -> Option<String> {
13152    english_subject(
13153        state.reviewed_commits.as_ref()?.first()?,
13154        state.config.graph.github_english(),
13155    )
13156}
13157
13158/// `raw` as a pull request title, or `None` when it is blank, not English
13159/// (GitHub text is), or one of magi's own candidate commit subjects.
13160fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13161    let raw = raw.trim();
13162    if raw.is_empty() {
13163        return None;
13164    }
13165    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13166        return None;
13167    }
13168    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13169        return None;
13170    }
13171    let title = queue::title_from(raw, PR_TITLE_MAX);
13172    let lower = title.to_ascii_lowercase();
13173    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13174        return None;
13175    }
13176    Some(title)
13177}
13178
13179/// What a review-only run's branch says about itself, read at the moment the
13180/// pull request is opened.
13181#[derive(Debug, Clone, PartialEq, Eq)]
13182struct BranchFacts {
13183    /// `(subject, body)` of each commit, oldest first.
13184    commits: Vec<(String, String)>,
13185    /// Trimmed `git diff --stat`.
13186    stat: String,
13187}
13188
13189/// Longest diff stat shown: this many file lines plus the summary line.
13190const STAT_FILE_LINES: usize = 25;
13191/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13192const COMMITS_MAX_CHARS: usize = 20_000;
13193
13194/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13195/// say or finds nothing, so the caller falls back to what the run recorded.
13196async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13197    let commits = git::commit_log(repo, base, branch).await.ok()?;
13198    if commits.is_empty() {
13199        return None;
13200    }
13201    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13202    let lines: Vec<&str> = stat.lines().collect();
13203    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13204        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13205        let more = format!(" ... {omitted} more file(s)");
13206        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13207        kept.push(&more);
13208        kept.push(lines[lines.len() - 1]);
13209        kept.join("\n")
13210    } else {
13211        lines.join("\n")
13212    };
13213    Some(BranchFacts { commits, stat })
13214}
13215
13216/// Defang what would break the surrounding markdown: a closing `</details>`
13217/// and a code fence.
13218fn markdown_safe(text: &str) -> String {
13219    text.replace("</details>", "&lt;/details&gt;")
13220        .replace("\x60\x60\x60", "~~~")
13221}
13222
13223fn neutral_title(state: &RunState, winner: char) -> String {
13224    format!(
13225        "chore: land candidate {} of run {}",
13226        winner.to_ascii_uppercase(),
13227        state.id
13228    )
13229}
13230
13231/// Reuse the graph's bounded fixer without starting another graph or driver.
13232/// Copy the working state back even on errors so spent rounds remain visible.
13233pub(crate) async fn repair_landing_gate(
13234    state: &mut RunState,
13235    winner: &Candidate,
13236    outcomes: &[CommandOutcome],
13237) -> Result<GateFix> {
13238    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13239        return Ok(GateFix::Stop);
13240    }
13241    let mut runner = Runner {
13242        roles: state.config.resolve_roles()?,
13243        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13244        state: state.clone(),
13245        pause: Pause::new(),
13246        interrupt: Pause::new(),
13247    };
13248    let result = runner.gate_fix_round(winner, outcomes).await;
13249    *state = runner.state;
13250    result
13251}
13252
13253/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13254/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13255pub(crate) async fn verify_current_head(
13256    state: &mut RunState,
13257    winner: &Candidate,
13258    wait: &crate::repo_lock::WaitPolicy,
13259) -> Result<bool> {
13260    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13261    // Preserve the previous record before replacing it, including on crash recovery.
13262    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13263        state
13264            .verification_history
13265            .push(crate::run::VerificationEvidence {
13266                superseded_by: Some(head.clone()),
13267                archived_at: Some(Timestamp::now()),
13268                fixes_spent: Some(state.gate_fixes.len()),
13269                gate_head: None,
13270                gate_ran: false,
13271                gate: Vec::new(),
13272                e2e: state.head_e2e.take(),
13273            });
13274    }
13275    if let Some(e) = &state.head_e2e
13276        && e.head == head
13277    {
13278        if e.passed {
13279            return Ok(true);
13280        }
13281        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13282            state.status = RunStatus::Blocked;
13283            state.save()?;
13284            return Ok(false);
13285        }
13286    } else if state.reviews.last().is_some_and(|r| {
13287        r.verified_head.as_deref() == Some(head.as_str())
13288            && (r.e2e_status() == E2eStatus::Passed
13289                || (r.e2e_status() == E2eStatus::NotConfigured
13290                    && state.config.verify.e2e.is_empty()))
13291    }) || state
13292        .gate_repair_e2e
13293        .as_ref()
13294        .is_some_and(|e| e.head == head && e.passed)
13295    {
13296        return Ok(true);
13297    }
13298    if let Some(e) = &state.gate_repair_e2e
13299        && e.head == head
13300        && !e.passed
13301        && !e.outcomes.is_empty()
13302        && !verify_inconclusive(&e.outcomes)
13303    {
13304        state.status = RunStatus::Blocked;
13305        state.save()?;
13306        return Ok(false);
13307    }
13308    // Bind the result to the base used by the candidate, not a tracking ref
13309    // that the background fetch can advance independently of verification.
13310    let base_commit = state
13311        .base_sync
13312        .as_ref()
13313        .map(|s| s.tip.clone())
13314        .filter(|tip| !tip.is_empty())
13315        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13316    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13317        head.clone(),
13318        false,
13319        Vec::new(),
13320    ));
13321    state.save()?;
13322    let commands = state.config.verify.e2e.clone();
13323    let shell = state.config.shell();
13324    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13325    let cache_dir = state.config.cache_dir();
13326    let outcomes = if commands.is_empty() {
13327        Vec::new()
13328    } else {
13329        let (outcomes, _) = with_cache_lease(
13330            state,
13331            cache_dir.as_deref(),
13332            "e2e",
13333            "e2e",
13334            &winner.worktree,
13335            &head,
13336            timeout,
13337            "current head e2e",
13338            wait,
13339            |state, budget| async move {
13340                run_e2e_with_retry(
13341                    state,
13342                    &shell,
13343                    &commands,
13344                    &winner.worktree,
13345                    budget,
13346                    "current head e2e",
13347                    None,
13348                )
13349                .await
13350            },
13351        )
13352        .await?;
13353        outcomes
13354    };
13355    let unresolved = verify_inconclusive(&outcomes);
13356    let passed = !unresolved
13357        && outcomes.iter().all(CommandOutcome::ok)
13358        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13359    if !outcomes.is_empty() && !unresolved {
13360        state.record_base_progress(&head);
13361    }
13362    let generation = Some(state.verification_history.len());
13363    let pass = state.passes.last().map(|p| p.index);
13364    let recorded_at = Some(Timestamp::now());
13365    let resumption_generation = state.entry_resumption_generation;
13366    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13367    record.base_commit = base_commit;
13368    record.generation = generation;
13369    record.pass = pass;
13370    record.recorded_at = recorded_at;
13371    record.resumption_generation = resumption_generation;
13372    if !passed && !unresolved {
13373        let detail = state
13374            .head_e2e
13375            .as_ref()
13376            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13377            .map(|d| format!(" ({d})"))
13378            .unwrap_or_default();
13379        state.status = RunStatus::Blocked;
13380        state.event(
13381            "e2e",
13382            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13383        );
13384        record.recorded_events = Some(state.events.len());
13385    }
13386    state.head_e2e = Some(record);
13387    state.save()?;
13388    Ok(passed)
13389}
13390
13391/// Recheck a repair's e2e requirement across failures, resource deferrals and
13392/// process interruptions. A successful result only applies to its exact SHA.
13393pub(crate) async fn check_gate_repair_e2e(
13394    state: &mut RunState,
13395    winner: &Candidate,
13396    wait: &crate::repo_lock::WaitPolicy,
13397) -> Result<GateFix> {
13398    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13399        return Ok(GateFix::Retry);
13400    }
13401    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13402    if let Some(record) = &state.gate_repair_e2e
13403        && record.head == head
13404    {
13405        if record.passed {
13406            return Ok(GateFix::Retry);
13407        }
13408        if !record.outcomes.is_empty()
13409            && record.outcomes.iter().all(|o| {
13410                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13411            })
13412        {
13413            return Ok(GateFix::Stop);
13414        }
13415    }
13416    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13417        head.clone(),
13418        false,
13419        Vec::new(),
13420    ));
13421    state.save()?;
13422    let commands = state.config.verify.e2e.clone();
13423    let outcomes = if commands.is_empty() {
13424        Vec::new()
13425    } else {
13426        let shell = state.config.shell();
13427        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13428        let cache_dir = state.config.cache_dir();
13429        let (outcomes, _) = with_cache_lease(
13430            state,
13431            cache_dir.as_deref(),
13432            "e2e",
13433            "e2e",
13434            &winner.worktree,
13435            &head,
13436            timeout,
13437            "gate repair e2e",
13438            wait,
13439            |state, budget| async move {
13440                run_e2e_with_retry(
13441                    state,
13442                    &shell,
13443                    &commands,
13444                    &winner.worktree,
13445                    budget,
13446                    "gate repair e2e",
13447                    None,
13448                )
13449                .await
13450            },
13451        )
13452        .await?;
13453        outcomes
13454    };
13455    let deferred = verify_inconclusive(&outcomes);
13456    let passed = outcomes.iter().all(CommandOutcome::ok)
13457        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13458    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
13459    state.save()?;
13460    if deferred {
13461        Ok(GateFix::Defer)
13462    } else if !passed {
13463        let detail = state
13464            .gate_repair_e2e
13465            .as_ref()
13466            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13467            .map(|d| format!(" ({d})"))
13468            .unwrap_or_default();
13469        state.event(
13470            "gate",
13471            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13472        );
13473        Ok(GateFix::Stop)
13474    } else {
13475        Ok(GateFix::Retry)
13476    }
13477}
13478
13479/// Run the same configured gate for a landing head and a fresh graph.
13480pub(crate) async fn run_landing_gate(
13481    state: &mut RunState,
13482    winner: &Candidate,
13483    wait: &crate::repo_lock::WaitPolicy,
13484) -> Result<Vec<CommandOutcome>> {
13485    let shell = state.config.shell();
13486    let gate_commands = state.config.verify.gate.clone();
13487    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13488    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13489        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13490        Vec::new()
13491    } else {
13492        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13493        let cache_dir = state.config.cache_dir();
13494        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13495        let (outcomes, _) = with_cache_lease(
13496            state,
13497            cache_dir.as_deref(),
13498            "gate",
13499            "gate",
13500            &winner.worktree,
13501            &head,
13502            timeout,
13503            "final gate",
13504            wait,
13505            |state, budget| {
13506                let shell = shell.clone();
13507                let gate_commands = gate_commands.clone();
13508                let winner = winner.clone();
13509                async move {
13510                    Runner::run_pre_gate(state, &winner).await;
13511                    // Bind command evidence after mechanical fixes, before commands start.
13512                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13513                    let (outcomes, timed_out_pids) = run_commands(
13514                        state,
13515                        "gate",
13516                        "gate",
13517                        0,
13518                        &shell,
13519                        &gate_commands,
13520                        &winner.worktree,
13521                        budget,
13522                    )
13523                    .await;
13524                    (outcomes, false, timed_out_pids)
13525                }
13526            },
13527        )
13528        .await?;
13529        outcomes
13530    };
13531    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13532    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13533        let mut outcomes = outcomes;
13534        outcomes.push(CommandOutcome {
13535            command: "gate head stability".into(), code: None,
13536            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13537            duration_ms: 0, resource_blocked: false,
13538            ..Default::default()
13539        });
13540        return Ok(outcomes);
13541    }
13542    if outcomes.is_empty() {
13543        // Nothing configured to check — distinct from every other
13544        // silence in this run's event log, since an empty `gate` alone
13545        // no longer says whether the gate ran at all (see
13546        // `RunState::gate_ran`'s own doc).
13547        state.event("gate", "no gate commands configured; not tested");
13548    }
13549    for o in &outcomes {
13550        state.event(
13551            "gate",
13552            format!(
13553                "`{}` -> {}",
13554                o.command,
13555                if o.ok() {
13556                    "pass".to_owned()
13557                } else {
13558                    format!(
13559                        "FAIL ({:?})\n{}",
13560                        o.code,
13561                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13562                    )
13563                }
13564            ),
13565        );
13566    }
13567    Ok(outcomes)
13568}
13569
13570/// The pull request title to hand to `land::merge_subject`. A review-only run
13571/// opened by an earlier build titled its pull request with the review prompt;
13572/// that title is dropped (empty, so the fallback applies) rather than landed.
13573/// Any other title, including an operator's rename, passes through untouched,
13574/// and so does every title of a run that implements a task.
13575pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13576    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13577        ""
13578    } else {
13579        pr_title
13580    }
13581}
13582
13583/// What the squash subject falls back to when the pull request title is empty
13584/// or candidate-shaped: for a review-only run the derived title, never the
13585/// review prompt held in `instruction`.
13586pub fn landing_subject_source(state: &RunState) -> String {
13587    if is_review_run(state) {
13588        let winner = state.candidates.first().map_or('A', |c| c.label);
13589        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13590    }
13591    state.instruction.clone()
13592}
13593
13594/// `summary` without its `TITLE:` line, which the pull request title already
13595/// carries.
13596fn summary_without_title(summary: &str) -> String {
13597    let mut lines = summary.trim().lines().peekable();
13598    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13599        lines.next();
13600    }
13601    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13602}
13603
13604/// The pull request title and body for the winning candidate.
13605///
13606/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13607/// the task's own opening line via [`queue::title_from`] when there is none.
13608/// `state.instruction` can open with blank lines (`task_text` only rejects a
13609/// body that is blank *entirely*), which `title_from` skips.
13610///
13611/// Publishing uses an independent description generated from the final diff
13612/// and structured evidence. Internal summaries and reports remain local.
13613/// Non-publishing previews may display the original task and candidate summary.
13614/// The footer retains the run and candidate provenance.
13615#[cfg(test)]
13616fn pr_message(state: &RunState, winner: char) -> PrMessage {
13617    pr_message_with(state, winner, None)
13618}
13619
13620/// [`pr_message`] with what the branch of a review-only run says about itself.
13621/// `facts` is ignored for a run that implements a task.
13622#[cfg(test)]
13623fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13624    let raw = pr_message_raw(
13625        state,
13626        winner,
13627        facts,
13628        crate::pr_outcome::FinalHead::Unreported,
13629        ChangeNote::NotAsked,
13630    );
13631    let id = crate::scrub::Identity::current();
13632    PrMessage {
13633        title: crate::scrub::scrub(&raw.title, &id),
13634        body: crate::scrub::scrub(&raw.body, &id),
13635    }
13636}
13637
13638/// What the public description may say about the change itself.
13639#[derive(Debug, Clone, Copy)]
13640enum ChangeNote<'a> {
13641    /// A local preview or non-publishing merge mode: no public generation needed.
13642    NotAsked,
13643    /// A summary written from the final diff.
13644    Summary(&'a crate::run::ChangeSummary),
13645    /// A summary was asked for and could not be produced; the text says why.
13646    Unavailable(&'a str),
13647}
13648
13649fn pr_message_raw(
13650    state: &RunState,
13651    winner: char,
13652    facts: Option<&BranchFacts>,
13653    head: crate::pr_outcome::FinalHead<'_>,
13654    change: ChangeNote<'_>,
13655) -> PrMessage {
13656    if !matches!(change, ChangeNote::NotAsked) {
13657        let (title, mut body) = match change {
13658            ChangeNote::Summary(c) => (
13659                c.title.clone(),
13660                format!("## Summary\n\n{}\n\n", c.body.trim()),
13661            ),
13662            ChangeNote::Unavailable(why) => (
13663                neutral_title(state, winner),
13664                format!(
13665                    "## 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"
13666                ),
13667            ),
13668            ChangeNote::NotAsked => unreachable!(),
13669        };
13670        body.push_str(&public_pr_evidence(state, head));
13671        body.push_str(&format!(
13672            "\n---\nmagi:run/{} magi:candidate-{}\n",
13673            state.id,
13674            winner.to_ascii_lowercase()
13675        ));
13676        return PrMessage { title, body };
13677    }
13678    pr_preview(state, winner, facts, head)
13679}
13680
13681/// Append public facts from the run records after every prose generation,
13682/// including posting-gate rewrites. The agent cannot drop this provenance.
13683fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13684    let mut body = crate::pr_outcome::review_rounds(state);
13685    body.push_str(&crate::pr_outcome::final_verification(state, head));
13686    let open = state.last_round_findings();
13687    if !open.is_empty() {
13688        body.push_str("## Open review findings\n\n");
13689        for f in open {
13690            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13691        }
13692        body.push('\n');
13693    }
13694    if let Some(c) = state.change_summary.as_ref()
13695        && head == crate::pr_outcome::FinalHead::At(&c.head)
13696    {
13697        body.push_str(&format!(
13698            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13699            c.base, c.head
13700        ));
13701    }
13702    body
13703}
13704
13705/// Local-only preview of the operator's task and candidate summary.
13706fn pr_preview(
13707    state: &RunState,
13708    winner: char,
13709    facts: Option<&BranchFacts>,
13710    head: crate::pr_outcome::FinalHead<'_>,
13711) -> PrMessage {
13712    let summary = state
13713        .candidates
13714        .iter()
13715        .find(|c| c.label == winner)
13716        .map(|c| c.summary.as_str())
13717        .unwrap_or_default();
13718    // The fallback is the operator's own words and may not be English; GitHub
13719    // text always is, so a non-English task gets a neutral title instead.
13720    let review = is_review_run(state);
13721    let title = if review {
13722        facts
13723            .and_then(|f| {
13724                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13725            })
13726            .or_else(|| review_title(state))
13727            .or_else(|| {
13728                state
13729                    .candidates
13730                    .iter()
13731                    .find(|c| c.label == winner)
13732                    .filter(|c| !c.branch.starts_with("magi/"))
13733                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13734            })
13735            .unwrap_or_else(|| neutral_title(state, winner))
13736    } else {
13737        summary_title(summary).unwrap_or_else(|| {
13738            english_title(
13739                &state.instruction,
13740                PR_TITLE_MAX,
13741                state.config.graph.github_english(),
13742            )
13743            .unwrap_or_else(|| neutral_title(state, winner))
13744        })
13745    };
13746
13747    let mut body = String::new();
13748    let what = summary_without_title(summary);
13749    if !what.is_empty() {
13750        body.push_str("## Summary\n\n");
13751        body.push_str(&what);
13752        body.push_str("\n\n");
13753    }
13754
13755    // Review history uses structured facts across all rounds, never reports.
13756    body.push_str(&crate::pr_outcome::review_rounds(state));
13757    body.push_str(&crate::pr_outcome::final_verification(state, head));
13758    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13759
13760    let open = state.open_findings();
13761    if !open.is_empty() {
13762        body.push_str("## Open review findings\n\n");
13763        for f in &open {
13764            body.push_str(&format!(
13765                "- `{}` [{:?}] {}\n",
13766                f.id, f.severity, "Context retained in local review records."
13767            ));
13768        }
13769        body.push('\n');
13770    }
13771
13772    if let Some(fix) = fix
13773        && !fix.rejected.is_empty()
13774    {
13775        body.push_str("## Declined by the fixer\n\n");
13776        for r in &fix.rejected {
13777            body.push_str(&format!(
13778                "- `{}`: {}\n",
13779                r.id, "Reason retained in local review records."
13780            ));
13781        }
13782        body.push('\n');
13783    }
13784
13785    if review {
13786        // The review prompt is not the task; list what the branch carries.
13787        body.push_str("## Commits under review\n\n");
13788        if let Some(facts) = facts {
13789            let mut left = COMMITS_MAX_CHARS;
13790            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13791                let mut entry = format!("- {}\n", markdown_safe(subject));
13792                for l in markdown_safe(text).lines() {
13793                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13794                }
13795                if left == 0 {
13796                    body.push_str(&format!(
13797                        "- ... {} more commit(s)\n",
13798                        facts.commits.len() - i
13799                    ));
13800                    break;
13801                }
13802                if entry.len() > left {
13803                    // Even the first commit is cut: one huge body must not
13804                    // push the whole description past GitHub's limit.
13805                    let mut end = left;
13806                    while !entry.is_char_boundary(end) {
13807                        end -= 1;
13808                    }
13809                    entry.truncate(end);
13810                    entry.push_str("\n  ... (truncated)\n");
13811                    left = 0;
13812                } else {
13813                    left -= entry.len();
13814                }
13815                body.push_str(&entry);
13816            }
13817            if !facts.stat.trim().is_empty() {
13818                body.push_str(&format!(
13819                    "\n## Diff stat\n\n```\n{}\n```\n",
13820                    markdown_safe(facts.stat.trim())
13821                ));
13822            }
13823        } else {
13824            match &state.reviewed_commits {
13825                Some(subjects) => {
13826                    for s in subjects {
13827                        body.push_str(&format!("- {}\n", s.trim()));
13828                    }
13829                }
13830                None => {
13831                    // An older run kept only the prompt, with the commit list
13832                    // after its first paragraph.
13833                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13834                    body.push_str(rest.trim());
13835                    body.push('\n');
13836                }
13837            }
13838        }
13839    } else {
13840        let task = state.instruction.trim();
13841        let task = if task.is_empty() {
13842            "(empty task)"
13843        } else {
13844            task
13845        };
13846        body.push_str(&format!(
13847            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13848            task.replace("</details>", "&lt;/details&gt;")
13849        ));
13850    }
13851
13852    body.push_str(&format!(
13853        "\n---\nmagi:run/{} magi:candidate-{}\n",
13854        state.id,
13855        winner.to_ascii_lowercase()
13856    ));
13857
13858    PrMessage { title, body }
13859}
13860
13861/// Source imports have already been prepared from structured inputs. Legacy
13862/// inferred references must never instruct a seat to reconstruct those imports.
13863fn seeded_instruction(state: &RunState) -> String {
13864    let mut inputs = Vec::new();
13865    if let Some(start) = &state.sources.start_from {
13866        inputs.push(format!(
13867            "Start from `{}` at `{}` (including ancestry).",
13868            start.token, start.sha
13869        ));
13870    }
13871    for pick in &state.sources.pick_commits {
13872        inputs.push(format!(
13873            "Pick `{}` at `{}` (single commit).",
13874            pick.token, pick.sha
13875        ));
13876    }
13877    if inputs.is_empty() {
13878        state.instruction.clone()
13879    } else {
13880        format!(
13881            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13882            state.instruction,
13883            inputs.join("\n")
13884        )
13885    }
13886}
13887
13888/// Does the winner have no commits ahead of the base it would land on?
13889/// Any failure to find out reads as "not empty": the merge then behaves as it
13890/// always did rather than refusing on a guess.
13891async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13892    let base = &state.base_branch;
13893    let mut against = base.clone();
13894    if mode == MergeMode::Pr {
13895        // A pull request lands on the remote's base, never the local branch
13896        // of the same name: if that cannot be read, "not empty" is the safe
13897        // answer.
13898        let remote = &state.config.merge.remote;
13899        let tracking = format!("{remote}/{base}");
13900        let fetched = git::fetch(repo, remote, base).await;
13901        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13902            against = tracking;
13903        } else {
13904            return false;
13905        }
13906    }
13907    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13908}
13909
13910/// Why nothing was opened for an empty winner, with what the task's own
13911/// references resolved to.
13912fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13913    let mut detail = format!(
13914        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13915         nothing to open a pull request for"
13916    );
13917    detail.push_str(
13918        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13919    );
13920    detail
13921}
13922
13923/// What the `Pr` merge does once it knows whether the branch already has an
13924/// open pull request.
13925#[derive(Debug, PartialEq, Eq)]
13926enum PrPlan {
13927    Create,
13928    Adopt { url: String, title: String },
13929    Stop(String),
13930}
13931
13932/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13933/// a failed lookup -> stop with the real reason. Never guesses.
13934fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13935    match found {
13936        Ok(land::OpenPr::None) => PrPlan::Create,
13937        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13938        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13939            "several open pull requests exist for this branch, not picking one: {}",
13940            urls.join(" ")
13941        )),
13942        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13943    }
13944}
13945
13946/// `gh pr create`, returning the PR url.
13947pub(crate) async fn gh_pr_create(
13948    cwd: &Path,
13949    base: &str,
13950    head: &str,
13951    title: &str,
13952    body: &str,
13953) -> Result<String> {
13954    let out = tokio::process::Command::new("gh")
13955        .args([
13956            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13957        ])
13958        .current_dir(cwd)
13959        .quiet()
13960        .stdin(std::process::Stdio::null())
13961        .output()
13962        .await
13963        .context("spawn gh")?;
13964    if out.status.success() {
13965        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13966    } else {
13967        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13968    }
13969}
13970
13971/// Never force deletion of uncommitted work, including unknown legacy trees.
13972async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13973    match std::fs::symlink_metadata(path) {
13974        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13975            // A previous cleanup may have removed the tree before a branch
13976            // deletion or state save failed. Unregister it if still present.
13977            git::worktree_remove_clean(repo, path).await?;
13978            return Ok(());
13979        }
13980        Err(e) => return Err(e.into()),
13981        Ok(_) => {}
13982    }
13983    if !git::is_clean(path).await? {
13984        bail!(
13985            "worktree has uncommitted work; refusing removal: {}",
13986            path.display()
13987        );
13988    }
13989    if !git::worktree_remove_clean(repo, path).await? {
13990        bail!("worktree removal refused: {}", path.display());
13991    }
13992    Ok(())
13993}
13994
13995/// Read seats return replies, not working-tree changes. Only registered,
13996/// detached seats directly inside this run's root may discard those changes.
13997async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13998    if !crate::retention::read_seat(path) || !path.exists() {
13999        return remove_preserved_worktree(&state.repo, path).await;
14000    }
14001    let owned = std::fs::symlink_metadata(path)?.is_dir()
14002        && path.parent().map(Path::canonicalize).transpose()?
14003            == Some(state.worktree_root().canonicalize()?)
14004        && crate::retention::worktrees(state)
14005            .await?
14006            .contains(&path.canonicalize()?);
14007    let common = crate::repo_lock::common_dir(&state.repo).await?;
14008    if !owned
14009        || common.is_none()
14010        || crate::repo_lock::common_dir(path).await? != common
14011        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14012            .await?
14013            .ok()
14014        || state.candidates.iter().any(|c| c.worktree == path)
14015    {
14016        return remove_preserved_worktree(&state.repo, path).await;
14017    }
14018    let changes = git::status_porcelain(path).await?;
14019    if !git::worktree_remove(&state.repo, path).await? {
14020        bail!(
14021            "read-only seat worktree removal refused: {}",
14022            path.display()
14023        );
14024    }
14025    if !changes.is_empty() {
14026        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14027        let paths: String = paths.chars().take(1024).collect();
14028        state.event(
14029            "fold",
14030            format!(
14031                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14032                path.file_name().unwrap_or_default().to_string_lossy(),
14033                changes.lines().count()
14034            ),
14035        );
14036    }
14037    Ok(())
14038}
14039
14040fn fold_target(
14041    home: &Path,
14042    root: &Path,
14043    path: &Path,
14044    isolated: bool,
14045) -> Option<crate::build_target::FoldTarget> {
14046    if !isolated {
14047        return None;
14048    }
14049    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14050        Ok(target) => target,
14051        Err(error) => {
14052            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14053            None
14054        }
14055    }
14056}
14057
14058fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14059    if let Some(target) = target
14060        && let Err(error) = target.reclaim_orphaned_target(home)
14061    {
14062        tracing::warn!(%error, "isolated target retained after fold");
14063    }
14064}
14065
14066/// Tear a run's worktrees and branches down.
14067///
14068/// `home` is where the updated `run.json` is saved (via
14069/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14070/// a housekeeping pass already has its own honest `home` handed to it, and
14071/// falling through to the global here would write back through whichever
14072/// directory some other process or test pinned into that `OnceLock` first,
14073/// not the one the caller actually resolved its `runs` and `state` from.
14074pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14075    fold_run_with_policy(state, drop_winner, home, false).await
14076}
14077
14078/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14079pub async fn fold_run_overriding_recovery_retention(
14080    state: &mut RunState,
14081    drop_winner: bool,
14082    home: &Path,
14083) -> Result<Vec<String>> {
14084    fold_run_with_policy(state, drop_winner, home, true).await
14085}
14086
14087async fn fold_run_with_policy(
14088    state: &mut RunState,
14089    drop_winner: bool,
14090    home: &Path,
14091    override_recovery_retention: bool,
14092) -> Result<Vec<String>> {
14093    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14094        && !override_recovery_retention
14095    {
14096        bail!("refusing fold: {reason}");
14097    }
14098    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14099        bail!("candidate preservation incomplete; refusing cleanup");
14100    }
14101    // Serialize ordinary folding with the same starts/resumes as target-only
14102    // eviction. Otherwise a second janitor could remove the whole worktree
14103    // around a live output borrower even though target eviction was fenced.
14104    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
14105    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
14106    // An override must use current durable ownership, not a pre-lock snapshot.
14107    if override_recovery_retention {
14108        *state = RunState::load_under(&state.id, home)?;
14109        anyhow::ensure!(
14110            state.status.done() && !state.status.resumable(),
14111            "recovery retention override requires a finished, non-resumable run"
14112        );
14113        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
14114        anyhow::ensure!(
14115            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14116            "run is live or its ownership is unknown"
14117        );
14118        anyhow::ensure!(
14119            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
14120            "candidate preservation incomplete; refusing cleanup"
14121        );
14122    }
14123    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14124    if let Some(reason) = &retention_reason
14125        && !override_recovery_retention
14126    {
14127        bail!("refusing fold: {reason}");
14128    }
14129    let _driver = crate::driver::maintenance(home, &state.id)?;
14130    let mut output_guards = Vec::new();
14131    for entry in std::fs::read_dir(state.worktree_root())
14132        .into_iter()
14133        .flatten()
14134        .flatten()
14135    {
14136        if entry.path().join(".git").is_file() {
14137            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
14138        }
14139    }
14140    let repo = state.repo.clone();
14141    // CLI, Web and automatic cleanup all enter here, independently of
14142    // Runner::fold_losers. Protect deletion and shared config release too.
14143    let wait = repository_wait(state, None);
14144    let _coordination = match coordinate_operation(state, &repo, &wait).await {
14145        Ok(lease) => lease,
14146        Err(e) => {
14147            state.save_under(home)?;
14148            return Err(e);
14149        }
14150    };
14151    // Confirmed merges dispose of their owned sources after durable evidence
14152    // capture. Preflight every source before removing anything.
14153    let _source_outputs = if retention_reason.is_some()
14154        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14155    {
14156        verify_merged_fold_sources(state, drop_winner, home).await?
14157    } else {
14158        Vec::new()
14159    };
14160    if let Some(reason) = retention_reason {
14161        state.event(
14162            "fold",
14163            format!(
14164                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14165                state.id
14166            ),
14167        );
14168        state.save_under(home)?;
14169    }
14170    let root = state.worktree_root();
14171    let winner = state.tally.as_ref().map(|t| t.winner);
14172    let mut removed = Vec::new();
14173    let isolated = crate::build_target::isolated(&state.config);
14174
14175    for i in 0..state.candidates.len() {
14176        let c = state.candidates[i].clone();
14177        let is_winner = Some(c.label) == winner;
14178        if is_winner && !drop_winner {
14179            continue;
14180        }
14181        let existed = c.worktree.exists();
14182        let target = fold_target(home, &root, &c.worktree, isolated);
14183        // A vanished directory can still have a Git registration that keeps
14184        // its branch checked out. Remove that registration before the branch.
14185        remove_preserved_worktree(&repo, &c.worktree).await?;
14186        reclaim_fold_target(home, target);
14187        if existed {
14188            removed.push(c.worktree.to_string_lossy().into_owned());
14189        }
14190        // A branch handed to a later run (and its pull request) is not this
14191        // run's to delete.
14192        let handed_over = state.released_branches.contains(&c.branch);
14193        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14194            if !git::branch_delete(&repo, &c.branch).await? {
14195                bail!("candidate branch removal refused");
14196            }
14197            removed.push(c.branch.clone());
14198        }
14199        state.candidates[i].folded = true;
14200    }
14201
14202    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14203        let path = name.path();
14204        let keep = !drop_winner
14205            && winner.is_some_and(|w| {
14206                path.file_name()
14207                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14208            });
14209        if keep {
14210            continue;
14211        }
14212        let target = fold_target(home, &root, &path, isolated);
14213        remove_read_seat_worktree(state, &path).await?;
14214        reclaim_fold_target(home, target);
14215        removed.push(path.to_string_lossy().into_owned());
14216    }
14217
14218    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14219    // judge worktrees, so once the loop above has cleared all of them out,
14220    // the parent is a bare directory nobody else was ever going to remove -
14221    // git only ever managed what was inside it. Left alone, one of these
14222    // accumulates per fully-folded run; the operator's own machine had 74.
14223    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14224    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14225    // so does anything a run never claimed that happens to share the bay.
14226    remove_if_empty(&root);
14227
14228    if state.enabled_worktree_config && drop_winner {
14229        // A release, not a raw disable: some sibling run in this repository
14230        // may still hold its own reference (see `git::acquire_worktree_config`),
14231        // and only the last release actually turns the setting back off.
14232        git::release_worktree_config(&repo).await.ok();
14233        state.enabled_worktree_config = false;
14234    }
14235    state.save_under(home)?;
14236    Ok(removed)
14237}
14238
14239async fn verify_merged_fold_sources(
14240    state: &RunState,
14241    drop_winner: bool,
14242    home: &Path,
14243) -> Result<Vec<std::fs::File>> {
14244    let winner = state.tally.as_ref().map(|t| t.winner);
14245    let mut heads = BTreeSet::new();
14246    for candidate in &state.candidates {
14247        if Some(candidate.label) == winner && !drop_winner {
14248            continue;
14249        }
14250        anyhow::ensure!(
14251            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14252            "candidate recovery source is outside the inventoried run root: {}",
14253            candidate.worktree.display()
14254        );
14255        match std::fs::symlink_metadata(&candidate.worktree) {
14256            Ok(_) => {}
14257            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14258            Err(error) => return Err(error.into()),
14259        }
14260        if !state.released_branches.contains(&candidate.branch)
14261            && git::branch_exists(&state.repo, &candidate.branch).await?
14262        {
14263            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14264        }
14265    }
14266    let mut cargo_guards = Vec::new();
14267    let entries = match std::fs::read_dir(state.worktree_root()) {
14268        Ok(entries) => Some(entries),
14269        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14270        Err(error) => return Err(error.into()),
14271    };
14272    for entry in entries.into_iter().flatten() {
14273        let path = entry?.path();
14274        let metadata = std::fs::symlink_metadata(&path)?;
14275        anyhow::ensure!(
14276            metadata.is_dir() && !metadata.file_type().is_symlink(),
14277            "non-directory or symlink recovery source retained: {}",
14278            path.display()
14279        );
14280        if !drop_winner
14281            && winner.is_some_and(|w| {
14282                path.file_name()
14283                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14284            })
14285        {
14286            continue;
14287        }
14288        anyhow::ensure!(
14289            path.join(".git").is_file(),
14290            "unregistered recovery source retained: {}",
14291            path.display()
14292        );
14293        anyhow::ensure!(
14294            git::git(
14295                &path,
14296                &[
14297                    "status",
14298                    "--porcelain",
14299                    "--untracked-files=all",
14300                    "--ignored",
14301                    "--",
14302                    ".",
14303                    ":(exclude)target"
14304                ]
14305            )
14306            .await?
14307            .is_empty(),
14308            "source changes or ignored recovery files retained: {}",
14309            path.display()
14310        );
14311        match std::fs::symlink_metadata(path.join("target")) {
14312            Ok(_) => {
14313                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14314            }
14315            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14316            Err(error) => return Err(error.into()),
14317        }
14318        for checkpoint in [
14319            "rebase-merge",
14320            "rebase-apply",
14321            "sequencer",
14322            "CHERRY_PICK_HEAD",
14323            "MERGE_HEAD",
14324            "REBASE_HEAD",
14325            "REVERT_HEAD",
14326            "BISECT_LOG",
14327            "AUTO_MERGE",
14328            "MERGE_MSG",
14329        ] {
14330            let location = git::git(
14331                &path,
14332                &[
14333                    "rev-parse",
14334                    "--path-format=absolute",
14335                    "--git-path",
14336                    checkpoint,
14337                ],
14338            )
14339            .await?;
14340            anyhow::ensure!(
14341                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14342                if e.kind() == std::io::ErrorKind::NotFound),
14343                "Git recovery checkpoint retained: {checkpoint}"
14344            );
14345        }
14346        heads.insert(git::rev_parse(&path, "HEAD").await?);
14347    }
14348    crate::fold_evidence::preserve(state, home, &heads).await?;
14349
14350    Ok(cargo_guards)
14351}
14352
14353/// Remove `dir` if it exists and has nothing in it.
14354///
14355/// Best-effort and silent by design: a directory that is not empty (a run
14356/// whose winner is still parked there, a stray file some other process left)
14357/// is exactly the case this must refuse, and a directory that is already gone
14358/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14359/// already refuses a non-empty directory, so the emptiness check below is
14360/// belt, not suspenders - it is what keeps this from ever attempting the
14361/// removal in the case that matters, rather than trusting `remove_dir`'s
14362/// error path to have no side effects if it ever changed.
14363fn remove_if_empty(dir: &Path) {
14364    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14365        std::fs::remove_dir(dir).ok();
14366    }
14367}
14368
14369/// Severity of the worst open finding in the last review round, for reporting.
14370pub fn worst_open(state: &RunState) -> Option<Severity> {
14371    state
14372        .reviews
14373        .last()?
14374        .reviews
14375        .iter()
14376        .flat_map(|r| r.findings.iter())
14377        .map(|f| f.severity)
14378        .max()
14379}
14380
14381/// `[worktree] setup` hides its products per worktree, which needs
14382/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14383/// worktrees, like the hook's; every place that runs setup calls this first.
14384async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14385    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14386        git::acquire_worktree_config(repo).await?;
14387        state.enabled_worktree_config = true;
14388    }
14389    Ok(())
14390}
14391
14392#[cfg(test)]
14393mod tests {
14394    #[tokio::test]
14395    async fn launcher_base_fetch_requires_remote_success() {
14396        let tmp = tempfile::tempdir().unwrap();
14397        let repo = tmp.path().join("repo");
14398        let remote = tmp.path().join("remote");
14399        std::fs::create_dir(&repo).unwrap();
14400        std::fs::create_dir(&remote).unwrap();
14401        git::git(&remote, &["init", "--bare", "-b", "main"])
14402            .await
14403            .unwrap();
14404        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14405        git::git(
14406            &repo,
14407            &[
14408                "-c",
14409                "user.name=Fixture",
14410                "-c",
14411                "user.email=fixture@example.invalid",
14412                "commit",
14413                "--allow-empty",
14414                "-m",
14415                "fixture",
14416            ],
14417        )
14418        .await
14419        .unwrap();
14420        git::git(
14421            &repo,
14422            &["remote", "add", "origin", remote.to_str().unwrap()],
14423        )
14424        .await
14425        .unwrap();
14426        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14427        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14428        assert_eq!(
14429            resolve_base(&repo, "main", "origin", None)
14430                .await
14431                .unwrap()
14432                .commit,
14433            head
14434        );
14435        #[cfg(unix)]
14436        {
14437            let policy: crate::config::Coordination = toml::from_str(
14438                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14439            ).unwrap();
14440            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14441            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14442            let held = crate::repo_lock::SeatLease::operation_with(
14443                &repo,
14444                Some(&policy),
14445                &crate::repo_lock::WaitPolicy::default(),
14446            )
14447            .await
14448            .unwrap();
14449            assert!(held.is_some());
14450            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14451            tokio::pin!(fetch);
14452            assert!(
14453                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14454                    .await
14455                    .is_err()
14456            );
14457            assert!(
14458                !repo.join(".git/FETCH_HEAD").exists(),
14459                "no fetch before admission"
14460            );
14461            drop(held);
14462            let fetched = fetch.await.unwrap();
14463            assert_eq!(fetched.commit, head);
14464            assert_eq!(fetched.remote, "origin");
14465            assert_eq!(fetched.branch, "main");
14466        }
14467        // A surviving tracking ref is not successful fetch evidence.
14468        git::git(
14469            &repo,
14470            &[
14471                "remote",
14472                "set-url",
14473                "origin",
14474                tmp.path().join("missing").to_str().unwrap(),
14475            ],
14476        )
14477        .await
14478        .unwrap();
14479        let error = resolve_base(&repo, "main", "origin", None)
14480            .await
14481            .unwrap_err()
14482            .to_string();
14483        assert!(error.contains("cannot read origin/main"));
14484        assert!(error.contains("refusing to branch off"));
14485    }
14486
14487    #[test]
14488    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14489        let leaked = vec!["chore(deps): update a crate".to_owned()];
14490        let own = "fix(daemon): apply a chosen action";
14491        assert!(should_retitle("", own, &leaked));
14492        assert!(should_retitle(
14493            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14494            own,
14495            &leaked
14496        ));
14497        assert!(should_retitle(
14498            "chore: land candidate A of run 1",
14499            own,
14500            &leaked
14501        ));
14502        assert!(should_retitle(
14503            "magi: candidate A (uncommitted work)",
14504            own,
14505            &leaked
14506        ));
14507        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14508        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14509        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14510    }
14511
14512    #[test]
14513    fn pr_merge_plan_creates_adopts_or_stops() {
14514        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14515        assert_eq!(
14516            pr_merge_plan(Ok(land::OpenPr::One {
14517                url: "u".into(),
14518                title: "t".into()
14519            })),
14520            PrPlan::Adopt {
14521                url: "u".into(),
14522                title: "t".into()
14523            }
14524        );
14525        let PrPlan::Stop(many) =
14526            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14527        else {
14528            panic!("many must stop");
14529        };
14530        assert!(many.contains('a') && many.contains('b'));
14531        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14532            panic!("a failed lookup must stop");
14533        };
14534        assert!(err.contains("bad token"));
14535    }
14536
14537    use super::*;
14538    use crate::run::GateStatus;
14539    use std::collections::BTreeMap;
14540    use std::time::Duration;
14541
14542    fn conductor() -> AgentSpec {
14543        AgentSpec {
14544            id: "conductor".to_owned(),
14545            kind: crate::config::AgentKind::Command,
14546            model: None,
14547            command: vec!["true".to_owned()],
14548            extra_args: Vec::new(),
14549            env: BTreeMap::new(),
14550            prompt_delivery: None,
14551            max_turn_secs: None,
14552        }
14553    }
14554
14555    fn spec(id: &str) -> AgentSpec {
14556        AgentSpec {
14557            id: id.to_owned(),
14558            kind: crate::config::AgentKind::Command,
14559            model: None,
14560            command: vec!["true".to_owned()],
14561            extra_args: Vec::new(),
14562            env: BTreeMap::new(),
14563            prompt_delivery: None,
14564            max_turn_secs: None,
14565        }
14566    }
14567
14568    fn ids(xs: &[&str]) -> BTreeSet<String> {
14569        xs.iter().map(|s| (*s).to_owned()).collect()
14570    }
14571
14572    #[test]
14573    fn pick_successor_skips_an_agent_another_seat_holds() {
14574        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14575        let roster = [spec("a"), spec("b"), spec("c")];
14576        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14577        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14578    }
14579
14580    #[test]
14581    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14582        // The other seat started on c but was handed to d; c is free again.
14583        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14584        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14585        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14586        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14587        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14588    }
14589
14590    #[test]
14591    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14592        let roster = [spec("a"), spec("b")];
14593        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14594        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14595        let carried = ids(&["b"]);
14596        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14597        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14598    }
14599
14600    #[test]
14601    fn pick_successor_returns_none_without_any_untried_successor() {
14602        let roster = [spec("a"), spec("b")];
14603        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14604        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14605        let carried = ids(&["a"]);
14606        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14607    }
14608
14609    #[test]
14610    fn pick_successor_rescue_avoids_another_seats_occupant() {
14611        // b is a carried failure and free; a is held by the other seat.
14612        let roster = [spec("a"), spec("b"), spec("c")];
14613        let carried = ids(&["b", "c"]);
14614        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14615        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14616    }
14617
14618    #[test]
14619    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14620        let roster = [spec("a"), spec("b"), spec("c")];
14621        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14622        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14623    }
14624
14625    #[test]
14626    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14627        let roster = [spec("a"), spec("b"), spec("c")];
14628        let failed = ids(&["a", "b", "c"]);
14629        // Rescue looks at the whole roster, once per id, then runs out.
14630        let mut tried = ids(&["b"]);
14631        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14632        assert_eq!(first.id, "a");
14633        tried.insert(first.id.clone());
14634        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14635        assert_eq!(second.id, "c");
14636        tried.insert(second.id.clone());
14637        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14638    }
14639
14640    #[test]
14641    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14642        let roster = [spec("a"), spec("b")];
14643        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14644        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14645    }
14646
14647    #[test]
14648    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14649        let roster = [spec("a"), spec("b"), spec("c")];
14650        let h = SeatHistory {
14651            failed: ids(&["a"]),
14652            last_ok: Some("b".to_owned()),
14653            last_fail: None,
14654        };
14655        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14656        // A last answerer that left the roster, or later failed, is ignored.
14657        let gone = SeatHistory {
14658            last_ok: Some("zzz".to_owned()),
14659            ..h.clone()
14660        };
14661        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14662        let failed = SeatHistory {
14663            failed: ids(&["a", "b"]),
14664            last_ok: Some("b".to_owned()),
14665            last_fail: None,
14666        };
14667        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14668    }
14669
14670    #[test]
14671    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14672        let first = SeatState::new("review-1", "alpha", 7);
14673        let next = handover_seat("review-1", "gamma", 7);
14674        assert_ne!(first.claude_session, next.claude_session);
14675    }
14676
14677    #[test]
14678    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14679        let mut state = state_with_summary("x", "y");
14680        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14681        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14682        assert_ne!(a.claude_session, b.claude_session);
14683    }
14684
14685    #[test]
14686    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14687        let roster = [spec("a"), spec("b")];
14688        let h = SeatHistory {
14689            failed: ids(&["a", "b"]),
14690            ..SeatHistory::default()
14691        };
14692        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14693        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14694        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14695    }
14696
14697    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14698    // fallback loop depends on to terminate: it must walk forward from the
14699    // seat's own position, never restart at the front of the roster, and it
14700    // must never hand back an id already tried, however many times that id
14701    // happens to appear.
14702
14703    #[test]
14704    fn failure_signature_ignores_numbers_and_paths() {
14705        assert_eq!(
14706            failure_signature("exited with Some(2) and no usable output"),
14707            failure_signature("exited with Some(137) and no usable output")
14708        );
14709        assert_eq!(
14710            failure_signature("process exited with no usable output (exit code 2)"),
14711            failure_signature("process exited with no usable output (exit code 137)")
14712        );
14713        for (old, new) in [
14714            (
14715                "exited with Some(2) and no usable output",
14716                "process exited with no usable output (exit code 2)",
14717            ),
14718            (
14719                "exited with None and no usable output",
14720                "process exited with no usable output (exit code unavailable)",
14721            ),
14722        ] {
14723            let previous = FailClass::Other(failure_signature(old));
14724            let current = FailClass::Other(failure_signature(new));
14725            assert_eq!(previous, current, "resumption retains the failure class");
14726            assert!(!should_hand_over(Some(&previous), &current));
14727        }
14728        assert_eq!(
14729            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14730            failure_signature("cannot open /var/x.txt: denied")
14731        );
14732        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14733    }
14734
14735    #[test]
14736    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14737        let other = FailClass::Other("x".into());
14738        assert!(should_hand_over(None, &FailClass::Quota));
14739        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14740        assert!(should_hand_over(
14741            Some(&FailClass::Timeout),
14742            &FailClass::Timeout
14743        ));
14744        assert!(should_hand_over(None, &other));
14745        assert!(!should_hand_over(Some(&other), &other));
14746        assert!(should_hand_over(
14747            Some(&other),
14748            &FailClass::Other("y".into())
14749        ));
14750        // A quota or timeout in between ends the run of identical failures.
14751        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14752        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14753    }
14754
14755    #[test]
14756    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14757        let a = SeatState::new("judge-1", "alpha", 7);
14758        let b = handover_seat("judge-1", "beta", 7);
14759        assert_ne!(a.claude_session, b.claude_session);
14760        assert_eq!(b.turns, 0);
14761    }
14762
14763    #[test]
14764    fn a_timeout_is_classified_apart_from_other_failures() {
14765        assert_eq!(
14766            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14767            Some(FailClass::Timeout)
14768        );
14769        assert!(matches!(
14770            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14771            Some(FailClass::Other(_))
14772        ));
14773    }
14774
14775    #[test]
14776    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14777        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14778        let tried = BTreeSet::from(["beta".to_owned()]);
14779        // beta sits at index 1; the next candidate is gamma, never alpha —
14780        // which is very likely a different candidate slot's own agent.
14781        let next = next_untried_in_roster(&roster, 1, &tried);
14782        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14783    }
14784
14785    #[test]
14786    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14787        let roster = vec![spec("alpha"), spec("beta")];
14788        let tried = BTreeSet::from(["beta".to_owned()]);
14789        // beta is the roster's last entry: nothing follows it, and alpha —
14790        // earlier in the roster, almost certainly a different candidate
14791        // slot's own agent — must not be reached by wrapping back to it.
14792        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14793    }
14794
14795    #[test]
14796    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14797        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14798        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14799        // beta (index 1) and gamma (index 2, the only entry after it) have
14800        // both been tried; alpha (index 0) never has, but it comes before
14801        // beta's own position, so there is nothing further for this seat.
14802        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14803    }
14804
14805    #[test]
14806    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14807        let roster = vec![spec("a"), spec("a"), spec("b")];
14808        let tried = BTreeSet::from(["a".to_owned()]);
14809        let next = next_untried_in_roster(&roster, 0, &tried);
14810        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14811    }
14812
14813    #[test]
14814    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14815        let roster = vec![spec("a"), spec("b")];
14816        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14817        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14818    }
14819
14820    #[test]
14821    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14822        let dir = tempfile::tempdir().unwrap();
14823        let bay = dir.path().join("ffff");
14824
14825        // Not there yet: nothing to do, nothing to panic on.
14826        remove_if_empty(&bay);
14827        assert!(!bay.exists());
14828
14829        // Something still inside - the winner's worktree, or a stray file -
14830        // keeps the directory standing.
14831        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14832        remove_if_empty(&bay);
14833        assert!(bay.exists(), "non-empty directory must survive");
14834
14835        // Once the last entry is gone, so is the directory itself.
14836        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14837        remove_if_empty(&bay);
14838        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14839    }
14840
14841    // `round_is_clean` is the exact decision this task fixed: a round with a
14842    // seat that never answered must not read the same as a round every seat
14843    // actually reviewed. These are deterministic and process-free by design —
14844    // the equivalent end-to-end check (a real reviewer timing out under a
14845    // live graph run) is a genuine race against wall-clock contention, and a
14846    // spawn slow enough to blow even a generous budget under a loaded test
14847    // run must not turn this specific regression check flaky.
14848
14849    #[test]
14850    fn a_full_panel_that_found_nothing_is_clean() {
14851        assert!(round_is_clean(
14852            0,
14853            true,
14854            2,
14855            2,
14856            0,
14857            IncompleteReviewPolicy::Block
14858        ));
14859    }
14860
14861    #[test]
14862    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14863        assert!(!round_is_clean(
14864            0,
14865            true,
14866            1,
14867            2,
14868            0,
14869            IncompleteReviewPolicy::Block
14870        ));
14871    }
14872
14873    #[test]
14874    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14875        assert!(!round_is_clean(
14876            1,
14877            true,
14878            1,
14879            2,
14880            0,
14881            IncompleteReviewPolicy::Warn
14882        ));
14883    }
14884
14885    #[test]
14886    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14887        assert!(round_is_clean(
14888            0,
14889            true,
14890            1,
14891            2,
14892            0,
14893            IncompleteReviewPolicy::Warn
14894        ));
14895    }
14896
14897    #[test]
14898    fn a_full_panel_with_an_open_finding_is_not_clean() {
14899        assert!(!round_is_clean(
14900            1,
14901            true,
14902            2,
14903            2,
14904            0,
14905            IncompleteReviewPolicy::Block
14906        ));
14907    }
14908
14909    #[test]
14910    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14911        assert!(!round_is_clean(
14912            0,
14913            false,
14914            2,
14915            2,
14916            0,
14917            IncompleteReviewPolicy::Block
14918        ));
14919    }
14920
14921    // The stall this task closes: under the default `block` policy, a seat
14922    // missing only because it was rate limited must not force a wait for a
14923    // session limit that will not lift by the next round. `round_is_clean`
14924    // is where that quorum carve-out lives; the review loop around it never
14925    // changes what a reviewer's vote or a finding's severity means.
14926
14927    #[test]
14928    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14929        // 1 of 2 answered, and the one missing was quota'd — the exact
14930        // "review-2 rate limited (quota)" shape from the field report.
14931        assert!(round_is_clean(
14932            0,
14933            true,
14934            1,
14935            2,
14936            1,
14937            IncompleteReviewPolicy::Block
14938        ));
14939    }
14940
14941    #[test]
14942    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14943        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14944        // not a quota loss (`quota_missing` stays 0) — worth another try.
14945        assert!(!round_is_clean(
14946            0,
14947            true,
14948            1,
14949            2,
14950            0,
14951            IncompleteReviewPolicy::Block
14952        ));
14953    }
14954
14955    #[test]
14956    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14957        assert!(!round_is_clean(
14958            1,
14959            true,
14960            1,
14961            2,
14962            1,
14963            IncompleteReviewPolicy::Block
14964        ));
14965        assert!(!round_is_clean(
14966            0,
14967            false,
14968            1,
14969            2,
14970            1,
14971            IncompleteReviewPolicy::Block
14972        ));
14973    }
14974
14975    #[test]
14976    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14977        // Every seat quota'd, nobody answered: there is no panel to decide
14978        // on, so this must fall through to the existing block-and-retry
14979        // fallback rather than call an unreviewed patch clean.
14980        assert!(!round_is_clean(
14981            0,
14982            true,
14983            0,
14984            2,
14985            2,
14986            IncompleteReviewPolicy::Block
14987        ));
14988    }
14989
14990    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14991        CommandOutcome {
14992            command: "test".to_owned(),
14993            code,
14994            output_tail: String::new(),
14995            duration_ms: 0,
14996            resource_blocked,
14997            ..Default::default()
14998        }
14999    }
15000
15001    #[cfg(unix)]
15002    #[tokio::test]
15003    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15004        ask_test_home();
15005        let temp = tempfile::tempdir().unwrap();
15006        let mut runner = runner_at(RunStatus::Gating);
15007        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15008        let commands = vec![
15009            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15010            "touch must-not-run".to_owned(),
15011        ];
15012        let (outcomes, retried, pids) = run_e2e_with_retry(
15013            &mut runner.state,
15014            &shell,
15015            &commands,
15016            temp.path(),
15017            Duration::from_secs(5),
15018            "fixture",
15019            None,
15020        )
15021        .await;
15022        assert_eq!(outcomes.len(), 1);
15023        assert!(outcomes[0].resource_blocked);
15024        assert!(!outcomes[0].build_failed());
15025        assert!(!retried);
15026        assert!(pids.is_empty());
15027        assert!(!temp.path().join("must-not-run").exists());
15028        assert_eq!(
15029            runner.state.resource_block.as_ref().unwrap().kind,
15030            "incremental cache admission"
15031        );
15032    }
15033
15034    #[test]
15035    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15036        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15037        assert!(
15038            !verify_inconclusive(&[outcome(Some(1), false)]),
15039            "an ordinary failure is still evidence about the patch"
15040        );
15041        assert!(verify_inconclusive(&[outcome(None, true)]));
15042        assert!(
15043            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15044            "one inconclusive outcome taints the whole batch"
15045        );
15046        assert!(!verify_inconclusive(&[]));
15047    }
15048
15049    #[tokio::test]
15050    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15051        // Alive for the first two checks, then dead - confirms the loop
15052        // actually re-polls rather than deciding once and sleeping out the
15053        // ceiling regardless.
15054        let calls = std::sync::atomic::AtomicUsize::new(0);
15055        let started = Instant::now();
15056        wait_for_pids_with(
15057            &[123],
15058            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15059            Duration::from_millis(5),
15060            Duration::from_secs(5),
15061        )
15062        .await;
15063        assert!(
15064            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15065            "must keep checking rather than deciding on the first answer"
15066        );
15067        assert!(
15068            started.elapsed() < Duration::from_secs(1),
15069            "must return the moment it is confirmed dead, not wait out the ceiling"
15070        );
15071    }
15072
15073    #[tokio::test]
15074    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15075        let started = Instant::now();
15076        wait_for_pids_with(
15077            &[123],
15078            |_| true, // never reports dead
15079            Duration::from_millis(5),
15080            Duration::from_millis(30),
15081        )
15082        .await;
15083        let elapsed = started.elapsed();
15084        assert!(
15085            elapsed >= Duration::from_millis(30),
15086            "must not give up before its own ceiling: {elapsed:?}"
15087        );
15088        assert!(
15089            elapsed < Duration::from_secs(1),
15090            "must not wait past its own ceiling either: {elapsed:?}"
15091        );
15092    }
15093
15094    #[tokio::test]
15095    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15096        let started = Instant::now();
15097        wait_for_pids_with(
15098            &[],
15099            |_| true,
15100            Duration::from_secs(5),
15101            Duration::from_secs(5),
15102        )
15103        .await;
15104        assert!(
15105            started.elapsed() < Duration::from_millis(200),
15106            "an empty pid list has nothing to confirm"
15107        );
15108    }
15109
15110    // `review_conclusion` is the exact decision the review hand-off task
15111    // fixed: a round budget spent (or a tree that stopped moving) must not
15112    // collapse into `Blocked` regardless of what verification actually
15113    // said. Deterministic and process-free for the same reason the
15114    // `round_is_clean` family above is.
15115    fn review_round(
15116        clean: bool,
15117        blocking: usize,
15118        answered: usize,
15119        expected: usize,
15120        progressed: bool,
15121        e2e_ok: bool,
15122    ) -> ReviewRound {
15123        ReviewRound {
15124            round: 1,
15125            head: "h".to_owned(),
15126            verified_head: None,
15127            verified_at: None,
15128            reviews: Vec::new(),
15129            e2e: vec![CommandOutcome {
15130                command: "test".to_owned(),
15131                code: Some(if e2e_ok { 0 } else { 1 }),
15132                output_tail: String::new(),
15133                duration_ms: 0,
15134                resource_blocked: false,
15135                ..Default::default()
15136            }],
15137            verify_retried: false,
15138            e2e_deferred: false,
15139            e2e_defer_reason: None,
15140            fix: None,
15141            blocking,
15142            answered,
15143            expected,
15144            clean,
15145            progressed,
15146            vote_split: false,
15147            reconsideration: Vec::new(),
15148            verdict: None,
15149        }
15150    }
15151
15152    #[test]
15153    fn review_conclusion_is_none_when_nothing_has_run() {
15154        assert_eq!(review_conclusion(&[], 3), None);
15155    }
15156
15157    #[test]
15158    fn review_conclusion_is_none_while_rounds_remain() {
15159        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15160        assert_eq!(review_conclusion(&rounds, 3), None);
15161    }
15162
15163    #[test]
15164    fn review_conclusion_is_gating_once_a_round_is_clean() {
15165        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15166        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15167    }
15168
15169    #[test]
15170    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15171        let rounds = vec![
15172            review_round(false, 1, 2, 2, true, true),
15173            review_round(false, 1, 2, 2, true, true),
15174        ];
15175        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15176    }
15177
15178    #[test]
15179    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15180        let rounds = vec![
15181            review_round(false, 1, 2, 2, true, true),
15182            review_round(false, 1, 2, 2, true, false),
15183        ];
15184        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15185    }
15186
15187    #[test]
15188    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15189        // Magi never got a command to run against this round's own head — a
15190        // resource-blocked attempt, not a red one — so this must never
15191        // settle on `Blocked` the way a genuine e2e failure would. `None`
15192        // here is what tells `Runner::review_loop` to retry the check
15193        // itself rather than trust this cheap recomputation with a verdict
15194        // it cannot actually produce.
15195        let mut blocked = review_round(false, 1, 2, 2, true, false);
15196        blocked.e2e[0].resource_blocked = true;
15197        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15198        assert_eq!(review_conclusion(&rounds, 2), None);
15199    }
15200
15201    #[test]
15202    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15203        // Missing input, not a verified tree — never a hand-off candidate.
15204        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15205        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15206    }
15207
15208    #[test]
15209    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15210        let rounds = vec![
15211            review_round(false, 1, 2, 2, false, true),
15212            review_round(false, 1, 2, 2, false, true),
15213        ];
15214        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15215    }
15216
15217    fn secs(n: u64) -> Duration {
15218        Duration::from_secs(n)
15219    }
15220
15221    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15222    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15223    #[tokio::test]
15224    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15225        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15226        if std::env::var_os(CHILD).is_none() {
15227            // Other tests reconcile every run in the process-global home,
15228            // briefly taking owner locks. This ancestry test expects an idle
15229            // predecessor, so give it its own process and pinned test home.
15230            let output = std::process::Command::new(std::env::current_exe().unwrap())
15231                .args([
15232                    "--exact",
15233                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15234                    "--nocapture",
15235                ])
15236                .env(CHILD, "1")
15237                .env_remove("MAGI_WORKER_HOME")
15238                .env_remove("MAGI_WORKER_ID")
15239                .output()
15240                .unwrap();
15241            assert!(
15242                output.status.success()
15243                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15244                "{}\n{}",
15245                String::from_utf8_lossy(&output.stdout),
15246                String::from_utf8_lossy(&output.stderr)
15247            );
15248            return;
15249        }
15250        ask_test_home();
15251        let tmp = tempfile::tempdir().unwrap();
15252        let repo = tmp.path().join("repo");
15253        std::fs::create_dir_all(&repo).unwrap();
15254        init_repo(&repo);
15255        let g = |args: &[&str]| {
15256            let out = std::process::Command::new("git")
15257                .args(args)
15258                .current_dir(&repo)
15259                .quiet()
15260                .output()
15261                .unwrap();
15262            assert!(
15263                out.status.success(),
15264                "{}",
15265                String::from_utf8_lossy(&out.stderr)
15266            );
15267        };
15268        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15269        g(&["checkout", "-b", "historical"]);
15270        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15271        g(&["add", "."]);
15272        g(&["commit", "-m", "old alternative"]);
15273        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15274        g(&["checkout", "-b", "magi/task-selected", &base]);
15275        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15276        g(&["add", "."]);
15277        g(&["commit", "-m", "measurement infrastructure"]);
15278        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15279        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15280        g(&["add", "."]);
15281        g(&["commit", "-m", "dependent implementation"]);
15282        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15283        g(&["checkout", "main"]);
15284        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15285        g(&["add", "."]);
15286        g(&["commit", "-m", "unrelated base change"]);
15287        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15288        let origin = tmp.path().join("origin.git");
15289        g(&[
15290            "clone",
15291            "--bare",
15292            repo.to_str().unwrap(),
15293            origin.to_str().unwrap(),
15294        ]);
15295        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15296        g(&["fetch", "origin"]);
15297        let selection = crate::pr_recovery::Selection {
15298            url: "https://example.test/project/pull/1".into(),
15299            branch: "magi/task-selected".into(),
15300            head: head.clone(),
15301            source_head: None,
15302            source_run: None,
15303            source_proof: None,
15304            disposition: Some(crate::pr_recovery::Disposition::Review),
15305            instruction: "preserve measured behavior".into(),
15306            approved_at: jiff::Timestamp::now(),
15307        };
15308        let mut template = runner_at(RunStatus::Reviewing);
15309        template.state.repo = repo.clone();
15310        template.state.base_commit = current.clone();
15311        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15312        template.state.origin = Some(crate::run::Origin::queue("selected"));
15313        template.state.pr_head = Some(selection.branch.clone());
15314        template.state.pr_recovery = Some(selection.clone());
15315        let mut runner =
15316            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15317                .await
15318                .unwrap();
15319        let wt = runner.state.winner().unwrap().worktree.clone();
15320        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15321        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15322        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15323        assert!(runner.state.seeds.is_empty());
15324        assert_eq!(runner.state.instruction, "preserve measured behavior");
15325        runner.sync_to_base().await.unwrap();
15326        assert_eq!(
15327            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15328            "prerequisite"
15329        );
15330        assert_eq!(
15331            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15332            "measured implementation"
15333        );
15334        assert_eq!(
15335            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15336            "current main change"
15337        );
15338        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15339        assert_eq!(
15340            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15341            head
15342        );
15343
15344        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15345        let mut partial = runner_at(RunStatus::Reviewing);
15346        partial.state.repo = repo.clone();
15347        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15348        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15349            run: Some("exit 1".into()),
15350            ..Default::default()
15351        }];
15352        let selection = runner.state.pr_recovery.clone().unwrap();
15353        partial.state.pr_recovery = Some(selection.clone());
15354        partial.state.pr_head = Some(selection.branch.clone());
15355        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15356        let id = partial.state.id.clone();
15357        let error = match Runner::open_selected(
15358            &repo,
15359            partial.state,
15360            partial.roles,
15361            1,
15362            runner.state.base_commit.clone(),
15363            selection,
15364        )
15365        .await
15366        {
15367            Ok(_) => panic!("setup must fail"),
15368            Err(e) => e,
15369        };
15370        assert_eq!(
15371            error
15372                .downcast_ref::<crate::run::StartupFailure>()
15373                .unwrap()
15374                .run,
15375            id
15376        );
15377        let failed = RunState::load(&id).unwrap();
15378        assert_eq!(failed.status, RunStatus::Failed);
15379        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15380        assert!(Runner::resume(&id).is_err());
15381        runner.state.status = RunStatus::Ready;
15382        runner.state.driver_exited = true;
15383        runner.state.save().unwrap();
15384        let mut retry = runner_at(RunStatus::Reviewing);
15385        retry.state.repo = repo.clone();
15386        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15387        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15388        reselected.approved_at = jiff::Timestamp::now();
15389        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15390        retry.state.pr_head = Some(reselected.branch.clone());
15391        retry.state.pr_recovery = Some(reselected.clone());
15392        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15393            .await
15394            .unwrap();
15395        let restarted = Runner::open_selected(
15396            &repo,
15397            retry.state,
15398            retry.roles,
15399            1,
15400            runner.state.base_commit.clone(),
15401            reselected,
15402        )
15403        .await
15404        .unwrap();
15405        assert_eq!(
15406            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15407                .await
15408                .unwrap(),
15409            head
15410        );
15411        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15412        assert_eq!(
15413            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15414            head
15415        );
15416    }
15417
15418    #[tokio::test]
15419    #[cfg(unix)]
15420    async fn fallback_and_interrupted_restoration_require_coordination() {
15421        use std::os::fd::AsRawFd as _;
15422        ask_test_home();
15423        let tmp = tempfile::tempdir().unwrap();
15424        let mut runner = registered_runner(tmp.path()).await;
15425        runner.state.config.graph.timeout_resource_wait = 1;
15426        let winner = runner.state.candidates[0].clone();
15427        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15428        let leftover = winner.worktree.join("leftover");
15429        std::fs::write(&leftover, "untrusted edits").unwrap();
15430        let next = tmp.path().join("next-fixer");
15431        let mut failed = spec("first");
15432        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15433        let mut successor = spec("second");
15434        successor.command = vec![
15435            "sh".into(),
15436            "-c".into(),
15437            format!("touch '{}'; echo done", next.display()),
15438        ];
15439        let attempts = vec![
15440            (failed.clone(), "first".into()),
15441            (successor.clone(), "second".into()),
15442        ];
15443        let lock_path = runner.state.repo.join(".git/updater.lock");
15444        let external = std::fs::File::create(&lock_path).unwrap();
15445        assert_eq!(
15446            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15447            0
15448        );
15449        let artifacts = tmp.path().join("artifacts");
15450        let build = |spec, seat| SeatJob {
15451            spec,
15452            seat,
15453            cwd: winner.worktree.clone(),
15454            prompt: "fixture".into(),
15455            timeout: Duration::from_secs(10),
15456            allow_write: true,
15457            sessions: false,
15458            artifacts: artifacts.clone(),
15459            stem: "fix".into(),
15460            handover: None,
15461        };
15462        let (_, _, out) = runner
15463            .ask_fixer_among(
15464                attempts.clone(),
15465                "graft",
15466                None,
15467                Some((&winner.worktree, &head)),
15468                build,
15469            )
15470            .await;
15471        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15472        assert!(leftover.exists(), "contention must prevent clean");
15473        assert!(!next.exists());
15474        assert!(runner.state.handovers.is_empty());
15475        // Early interrupted-repair rollback uses the same protected route.
15476        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15477            from_run: "earlier".into(),
15478            generation: 1,
15479            mode: crate::recovery::Mode::VerifyRepair,
15480            reasons: Vec::new(),
15481            reviewed_head: None,
15482            rounds: Vec::new(),
15483            open_findings: Vec::new(),
15484            evidence: None,
15485            criteria_inherited: true,
15486            repair: crate::recovery::Repair::Started {
15487                before: head.clone(),
15488            },
15489        });
15490        assert!(
15491            runner
15492                .recovery_repair(&winner)
15493                .await
15494                .unwrap_err()
15495                .is::<crate::repo_lock::ResourceBlocked>()
15496        );
15497        assert!(matches!(
15498            runner.state.recovery.as_ref().unwrap().repair,
15499            crate::recovery::Repair::Started { .. }
15500        ));
15501        assert!(leftover.exists());
15502        drop(external);
15503        runner.recovery_repair(&winner).await.unwrap();
15504        assert!(!leftover.exists());
15505        assert!(matches!(
15506            runner.state.recovery.as_ref().unwrap().repair,
15507            crate::recovery::Repair::Done { .. }
15508        ));
15509        // A hard lock-open failure also leaves HEAD and untracked work intact.
15510        std::fs::remove_file(&lock_path).unwrap();
15511        std::fs::create_dir(&lock_path).unwrap();
15512        std::fs::write(&leftover, "untrusted edits").unwrap();
15513        let (_, _, out) = runner
15514            .ask_fixer_among(
15515                attempts,
15516                "graft",
15517                None,
15518                Some((&winner.worktree, &head)),
15519                build,
15520            )
15521            .await;
15522        assert!(matches!(out, AgentOutcome::Failed(_)));
15523        assert!(leftover.exists());
15524        assert!(!next.exists());
15525        assert_eq!(
15526            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15527            head
15528        );
15529    }
15530
15531    #[cfg(unix)]
15532    async fn registered_runner(root: &Path) -> Runner {
15533        repository_runner(root, crate::config::test_coordination()).await
15534    }
15535
15536    async fn repository_runner(
15537        root: &Path,
15538        coordination: Option<crate::config::Coordination>,
15539    ) -> Runner {
15540        ask_test_home();
15541        let repo = root.join("repo");
15542        std::fs::create_dir_all(&repo).unwrap();
15543        init_repo(&repo);
15544        if coordination.is_some() {
15545            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15546        }
15547        let mut runner = runner_at(RunStatus::Prep);
15548        runner.state.repo = repo.clone();
15549        runner.state.config.coordination = coordination;
15550        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15551        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15552        runner.state.config.graph.advise = false;
15553        runner.roles.implementers = vec![spec("implement")];
15554        runner.roles.judges = vec![spec("judge")];
15555        runner.prep().await.unwrap();
15556        runner
15557    }
15558
15559    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15560
15561    #[tokio::test]
15562    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15563        let tmp = tempfile::tempdir().unwrap();
15564        let mut runner = repository_runner(tmp.path(), None).await;
15565        let prompts = runner.state.config.prompts.clone();
15566        let run = runner.state.id.clone();
15567        let ctx = WaveCtx {
15568            carry_seats: false,
15569            pauses: None,
15570            run: &run,
15571            node: "advise",
15572            prompts: &prompts,
15573            cache: None,
15574            round: None,
15575        };
15576        let jobs: Vec<_> = ["alpha", "beta"]
15577            .into_iter()
15578            .map(|id| SeatJob {
15579                spec: scripted(id, AUTH_OUTAGE),
15580                seat: SeatState::new(id, id, 7),
15581                prompt: "propose".into(),
15582                cwd: runner.state.candidates[0].worktree.clone(),
15583                timeout: Duration::from_secs(10),
15584                allow_write: false,
15585                sessions: false,
15586                artifacts: agent::artifacts_dir(&runner.state.dir()),
15587                stem: id.into(),
15588                handover: None,
15589            })
15590            .collect();
15591        let mut losses = Vec::new();
15592        let results = ask_wave_with(
15593            jobs.clone(),
15594            runner.sem.clone(),
15595            2,
15596            &[],
15597            &ctx,
15598            &mut losses,
15599            &mut runner.state,
15600            &|_: &str| Ok(()),
15601        )
15602        .await;
15603        assert!(
15604            results
15605                .iter()
15606                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15607        );
15608        assert_eq!(runner.state.quota.len(), 2);
15609        assert!(
15610            runner
15611                .state
15612                .quota
15613                .iter()
15614                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15615        );
15616        assert!(!runner.state.advise_attempted);
15617        runner.stop_for_resource().unwrap();
15618        assert_eq!(runner.state.status, RunStatus::Blocked);
15619        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15620        assert_eq!(
15621            runner.state.resource_block.as_ref().unwrap().kind,
15622            "agent authentication"
15623        );
15624        // A machine loss followed by an ordinary failure is not evidence
15625        // that the whole node was unavailable, and must not earn a refund.
15626        runner.state.resource_block = None;
15627        runner.state.quota.clear();
15628        let mut mixed = jobs;
15629        mixed[1].spec.command = vec!["false".into()];
15630        let results = ask_wave_with(
15631            mixed,
15632            runner.sem.clone(),
15633            0,
15634            &[],
15635            &ctx,
15636            &mut losses,
15637            &mut runner.state,
15638            &|_: &str| Ok(()),
15639        )
15640        .await;
15641        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15642        assert!(runner.state.resource_block.is_none());
15643        assert_eq!(losses.len(), 1);
15644    }
15645
15646    #[tokio::test]
15647    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15648        let tmp = tempfile::tempdir().unwrap();
15649        let mut runner = repository_runner(tmp.path(), None).await;
15650        let implementer = scripted("implement", AUTH_OUTAGE);
15651        runner.roles.implementers = vec![implementer.clone()];
15652        runner.state.config.agents = vec![implementer];
15653        runner.implement().await.unwrap();
15654        assert_eq!(runner.state.status, RunStatus::Blocked);
15655        assert_eq!(runner.state.quota.len(), 1);
15656        assert_eq!(
15657            runner.state.quota[0].cause,
15658            agent::QuotaCause::Authentication
15659        );
15660        let candidate = &runner.state.candidates[0];
15661        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15662        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15663    }
15664
15665    #[tokio::test]
15666    #[cfg(unix)]
15667    async fn parked_implementer_persists_completed_work() {
15668        for registered in [false, true] {
15669            let tmp = tempfile::tempdir().unwrap();
15670            let mut runner = registered_runner(tmp.path()).await;
15671            if !registered {
15672                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15673            }
15674            let marker = tmp.path().join("started");
15675            let release = tmp.path().join("release");
15676            let mut implementer = spec("implement");
15677            implementer.command = vec![
15678                "sh".into(),
15679                "-c".into(),
15680                format!(
15681                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15682                    marker.display(),
15683                    release.display()
15684                ),
15685            ];
15686            runner.roles.implementers = vec![implementer.clone()];
15687            runner.state.config.agents = vec![implementer];
15688            let pause = runner.pause.clone();
15689            let (result, ()) = tokio::join!(runner.implement(), async {
15690                tokio::time::timeout(Duration::from_secs(10), async {
15691                    while !marker.exists() {
15692                        tokio::time::sleep(Duration::from_millis(10)).await;
15693                    }
15694                })
15695                .await
15696                .unwrap();
15697                pause.park();
15698                std::fs::write(&release, "go").unwrap();
15699            });
15700            result.unwrap();
15701            let candidate = &runner.state.candidates[0];
15702            assert!(candidate.commits > 0, "{candidate:?}");
15703            assert!(candidate.summary.contains("saved-result"));
15704            assert_eq!(candidate.files, 1);
15705            let before = candidate.commits;
15706            runner.implement().await.unwrap();
15707            assert_eq!(runner.state.candidates[0].commits, before);
15708        }
15709    }
15710
15711    #[tokio::test]
15712    #[cfg(unix)]
15713    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15714        let tmp = tempfile::tempdir().unwrap();
15715        let mut runner = registered_runner(tmp.path()).await;
15716        let winner = runner.state.candidates[0].clone();
15717        let cache = tmp.path().join("cache");
15718        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15719        runner.state.config.graph.timeout_resource_wait = 0;
15720        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15721        let crate::cache::AcquireOutcome::Acquired(held) =
15722            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15723        else {
15724            panic!("cache must be free")
15725        };
15726        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15727            from_run: "earlier".into(),
15728            generation: 1,
15729            mode: crate::recovery::Mode::VerifyRepair,
15730            reasons: Vec::new(),
15731            reviewed_head: None,
15732            rounds: Vec::new(),
15733            open_findings: Vec::new(),
15734            evidence: None,
15735            criteria_inherited: true,
15736            repair: crate::recovery::Repair::NotStarted,
15737        });
15738        runner.recovery_repair(&winner).await.unwrap();
15739        assert!(matches!(
15740            runner.state.recovery.as_ref().unwrap().repair,
15741            crate::recovery::Repair::WaitingForRestore { .. }
15742        ));
15743        drop(held);
15744        runner.state.resource_block = None;
15745        runner.state.config.graph.timeout_resource_wait = 1;
15746        runner.recovery_repair(&winner).await.unwrap();
15747        assert!(matches!(
15748            runner.state.recovery.as_ref().unwrap().repair,
15749            crate::recovery::Repair::Done { .. }
15750        ));
15751        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15752    }
15753
15754    #[tokio::test]
15755    #[cfg(unix)]
15756    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15757        use std::os::fd::AsRawFd as _;
15758        for graft in [false, true] {
15759            let tmp = tempfile::tempdir().unwrap();
15760            let mut runner = registered_runner(tmp.path()).await;
15761            runner.state.config.graph.timeout_resource_wait = 1;
15762            let winner = runner.state.candidates[0].clone();
15763            let marker = tmp.path().join("fixer-started");
15764            let mut fixer = spec("fixer");
15765            fixer.command = vec![
15766                "sh".into(),
15767                "-c".into(),
15768                format!("echo started >> '{}'; echo done", marker.display()),
15769            ];
15770            runner.roles.fixer = Some(vec![fixer]);
15771            if graft {
15772                let mut loser = winner.clone();
15773                loser.label = 'B';
15774                loser.index = 1;
15775                runner.state.candidates.push(loser);
15776                runner.state.config.graph.graft_runner_up = true;
15777                runner.state.tally = Some(Tally {
15778                    first_choice: BTreeMap::new(),
15779                    borda: BTreeMap::new(),
15780                    winner: winner.label,
15781                    rankings: 1,
15782                    unanimous_initial: true,
15783                    deliberated: false,
15784                    changed_votes: 0,
15785                    unanimous_final: true,
15786                    tie_break: None,
15787                    judges: 1,
15788                    present: 1,
15789                    quorum: 1,
15790                    met_quorum: true,
15791                    uncontested: None,
15792                });
15793                runner.state.judgements.push(crate::run::Judgement {
15794                    judge: 1,
15795                    seat: "judge-1".into(),
15796                    agent: "judge".into(),
15797                    ranking: vec![winner.label, 'B'],
15798                    reasons: BTreeMap::new(),
15799                    confidence: None,
15800                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15801                    order: vec![0, 1],
15802                    failed: None,
15803                    duration_ms: 0,
15804                });
15805            } else {
15806                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15807                    from_run: "earlier".into(),
15808                    generation: 1,
15809                    mode: crate::recovery::Mode::VerifyRepair,
15810                    reasons: Vec::new(),
15811                    reviewed_head: None,
15812                    rounds: Vec::new(),
15813                    open_findings: Vec::new(),
15814                    evidence: None,
15815                    criteria_inherited: true,
15816                    repair: crate::recovery::Repair::NotStarted,
15817                });
15818            }
15819            let reader = crate::repo_lock::SeatLease::for_checkout(
15820                &winner.worktree,
15821                false,
15822                crate::config::test_coordination().as_ref(),
15823            )
15824            .await
15825            .unwrap();
15826            let pause = runner.pause.clone();
15827            let (result, ()) = tokio::join!(
15828                async {
15829                    if graft {
15830                        runner.graft().await
15831                    } else {
15832                        runner.recovery_repair(&winner).await
15833                    }
15834                },
15835                async {
15836                    tokio::time::sleep(Duration::from_millis(100)).await;
15837                    pause.park();
15838                }
15839            );
15840            result.unwrap();
15841            assert!(!marker.exists(), "a blocked seat must not spawn");
15842            // Exercise the persisted state, as a binary replacement/resume does.
15843            runner.state = RunState::load(&runner.state.id).unwrap();
15844            if graft {
15845                assert_eq!(
15846                    runner.state.graft.as_ref().unwrap().outcome,
15847                    GraftOutcome::WaitingForRestore
15848                );
15849            } else {
15850                assert!(matches!(
15851                    runner.state.recovery.as_ref().unwrap().repair,
15852                    crate::recovery::Repair::WaitingForRestore { .. }
15853                ));
15854            }
15855            drop(reader);
15856            runner.pause = Pause::new();
15857            runner.state.resource_block = None;
15858            // Deferred restoration must still respect an external lock owner.
15859            let external =
15860                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15861            assert_eq!(
15862                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15863                0
15864            );
15865            let leftover = winner.worktree.join("leftover");
15866            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15867            let result = if graft {
15868                runner.graft().await
15869            } else {
15870                runner.recovery_repair(&winner).await
15871            };
15872            assert!(
15873                result
15874                    .unwrap_err()
15875                    .is::<crate::repo_lock::ResourceBlocked>()
15876            );
15877            assert!(leftover.exists());
15878            assert!(!marker.exists());
15879            drop(external);
15880            runner.state.resource_block = None;
15881            let result = if graft {
15882                runner.graft().await
15883            } else {
15884                runner.recovery_repair(&winner).await
15885            };
15886            result.unwrap();
15887            assert!(!leftover.exists(), "restore must precede retry");
15888            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15889            if graft {
15890                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15891            } else {
15892                assert!(matches!(
15893                    runner.state.recovery.as_ref().unwrap().repair,
15894                    crate::recovery::Repair::Done { .. }
15895                ));
15896            }
15897        }
15898    }
15899
15900    #[tokio::test]
15901    #[cfg(unix)]
15902    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15903        use std::os::fd::AsRawFd as _;
15904        let tmp = tempfile::tempdir().unwrap();
15905        let mut runner = registered_runner(tmp.path()).await;
15906        runner.state.config.graph.timeout_resource_wait = 1;
15907        let winner = runner.state.candidates[0].clone();
15908        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15909        runner.state.tally = Some(Tally {
15910            first_choice: BTreeMap::new(),
15911            borda: BTreeMap::new(),
15912            winner: winner.label,
15913            rankings: 0,
15914            unanimous_initial: false,
15915            deliberated: false,
15916            changed_votes: 0,
15917            unanimous_final: false,
15918            tie_break: None,
15919            judges: 0,
15920            present: 0,
15921            quorum: 0,
15922            met_quorum: true,
15923            uncontested: Some("fixture".into()),
15924        });
15925        runner.state.graft = Some(GraftRecord {
15926            pre: pre.clone(),
15927            post: None,
15928            lines: None,
15929            limit: None,
15930            agent: None,
15931            outcome: GraftOutcome::Running,
15932            requested: Vec::new(),
15933            adoption: None,
15934            adoption_error: None,
15935        });
15936        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15937        git::commit_all(&winner.worktree, "unfinished graft")
15938            .await
15939            .unwrap();
15940        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15941        let leftover = winner.worktree.join("leftover");
15942        std::fs::write(&leftover, "untrusted edits").unwrap();
15943        let path = runner.state.repo.join(".git/updater.lock");
15944        let external = std::fs::File::create(&path).unwrap();
15945        assert_eq!(
15946            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15947            0
15948        );
15949        assert!(
15950            runner
15951                .graft()
15952                .await
15953                .unwrap_err()
15954                .is::<crate::repo_lock::ResourceBlocked>()
15955        );
15956        assert!(matches!(
15957            runner.state.graft.as_ref().unwrap().outcome,
15958            GraftOutcome::Running
15959        ));
15960        assert_eq!(
15961            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15962            unfinished
15963        );
15964        assert!(leftover.exists());
15965        drop(external);
15966        std::fs::remove_file(&path).unwrap();
15967        std::fs::create_dir(&path).unwrap();
15968        assert!(runner.graft().await.is_err());
15969        assert!(matches!(
15970            runner.state.graft.as_ref().unwrap().outcome,
15971            GraftOutcome::Running
15972        ));
15973        assert_eq!(
15974            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15975            unfinished
15976        );
15977        assert!(leftover.exists());
15978        std::fs::remove_dir(&path).unwrap();
15979        runner.graft().await.unwrap();
15980        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15981        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15982        assert!(!leftover.exists());
15983    }
15984
15985    #[tokio::test]
15986    #[cfg(unix)]
15987    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15988        use std::os::fd::AsRawFd as _;
15989        let tmp = tempfile::tempdir().unwrap();
15990        let mut runner = registered_runner(tmp.path()).await;
15991        runner.state.prep_complete = Some(false);
15992        runner.state.config.graph.timeout_resource_wait = 1;
15993        runner.state.save().unwrap();
15994        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15995        assert_eq!(
15996            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15997            0
15998        );
15999        runner.execute().await.unwrap();
16000        let disk = RunState::load(&runner.state.id).unwrap();
16001        assert!(disk.driver_exited);
16002        assert_eq!(disk.driver_pid, None);
16003        assert_eq!(runner.state.status, RunStatus::Blocked);
16004        assert_eq!(
16005            runner.state.resource_block.as_ref().unwrap().kind,
16006            "repository coordination"
16007        );
16008        assert!(runner.state.prep_failure.is_none());
16009        assert!(runner.state.seats.is_empty());
16010        runner.pause.park();
16011        // Include headroom for Git subprocesses under parallel test load;
16012        // the repository contention deadline itself remains one second.
16013        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16014            .await
16015            .unwrap()
16016            .unwrap();
16017        assert!(runner.state.parked);
16018        assert!(runner.state.prep_failure.is_none());
16019        let disk = RunState::load(&runner.state.id).unwrap();
16020        assert!(disk.driver_exited);
16021        assert_eq!(disk.driver_pid, None);
16022    }
16023
16024    #[tokio::test]
16025    #[cfg(unix)]
16026    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16027        use std::os::fd::AsRawFd as _;
16028        let tmp = tempfile::tempdir().unwrap();
16029        let mut runner = registered_runner(tmp.path()).await;
16030        runner.state.prep_complete = Some(false);
16031        runner.state.config.graph.timeout_resource_wait = 30;
16032        runner.state.save().unwrap();
16033        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16034        assert_eq!(
16035            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16036            0
16037        );
16038        assert!(
16039            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16040                .await
16041                .is_err()
16042        );
16043        let disk = RunState::load(&runner.state.id).unwrap();
16044        assert!(disk.driver_exited);
16045        assert_eq!(disk.driver_pid, None);
16046        assert!(disk.status.resumable());
16047        assert!(runner.state.driver_exited);
16048        assert_eq!(runner.state.driver_pid, None);
16049        runner.state.save().unwrap();
16050        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16051    }
16052
16053    #[tokio::test]
16054    #[cfg(unix)]
16055    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16056        let tmp = tempfile::tempdir().unwrap();
16057        let mut runner = registered_runner(tmp.path()).await;
16058        let winner = runner.state.candidates[0].clone();
16059        let cache = tmp.path().join("cache");
16060        let started = tmp.path().join("pre-gate-started");
16061        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16062        runner.state.config.verify.gate =
16063            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16064        let home = crate::run::home();
16065        let owner =
16066            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16067        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16068            crate::cache::AcquireOutcome::Acquired(g) => g,
16069            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16070        };
16071        let mut gate = Box::pin(runner.run_gate(&winner));
16072        assert!(
16073            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16074                .await
16075                .is_err()
16076        );
16077        assert!(!started.exists(), "pre-gate must wait for the cache too");
16078        // Simulate the wave that already owns the cache entering invoke.
16079        // It must obtain the editor reservation and finish without waiting
16080        // for the gate that is queued behind its cache.
16081        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16082        let editor = crate::repo_lock::SeatLease::checkout_with(
16083            &winner.worktree,
16084            true,
16085            crate::config::test_coordination().as_ref(),
16086            &wait,
16087        )
16088        .await
16089        .unwrap();
16090        drop(editor);
16091        guard.release();
16092        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16093            .await
16094            .unwrap()
16095            .unwrap();
16096        drop(gate);
16097        assert!(outcomes.iter().all(CommandOutcome::ok));
16098        assert!(started.exists());
16099    }
16100
16101    #[tokio::test]
16102    #[cfg(unix)]
16103    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16104        use std::os::fd::AsRawFd as _;
16105
16106        ask_test_home();
16107        let tmp = tempfile::tempdir().unwrap();
16108        let repo = tmp.path().join("repo");
16109        std::fs::create_dir_all(&repo).unwrap();
16110        init_repo(&repo);
16111        let common = repo.join(".git");
16112        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16113        let mut runner = runner_at(RunStatus::Prep);
16114        runner.state.repo = repo.clone();
16115        runner.state.config.coordination = crate::config::test_coordination();
16116        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16117        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16118        runner.state.config.graph.advise = false;
16119        runner.roles.implementers = vec![spec("implement")];
16120        runner.roles.judges = vec![spec("judge")];
16121        runner.prep().await.unwrap();
16122        let winner = runner.state.candidates[0].clone();
16123        // Emulate edits already left by a completed seat. The fixture CLI
16124        // only reports completion; it performs no repository operations.
16125        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16126        let completed = tmp.path().join("seat-completed");
16127        runner.roles.implementers[0].command = vec![
16128            "sh".into(),
16129            "-c".into(),
16130            format!("touch '{}'; echo completed", completed.display()),
16131        ];
16132        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16133        assert_eq!(
16134            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16135            0
16136        );
16137        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16138        let mut implement = Box::pin(runner.implement());
16139        tokio::select! {
16140            result = &mut implement => panic!("rescue must wait: {result:?}"),
16141            result = tokio::time::timeout(Duration::from_secs(10), async {
16142                while !completed.exists() {
16143                    tokio::time::sleep(Duration::from_millis(20)).await;
16144                }
16145            }) => result.unwrap(),
16146        }
16147        assert!(
16148            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16149                .await
16150                .is_err()
16151        );
16152        assert_eq!(
16153            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16154            before
16155        );
16156        assert_eq!(
16157            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16158            0
16159        );
16160        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16161            .await
16162            .unwrap()
16163            .unwrap();
16164        drop(implement);
16165        assert_ne!(
16166            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16167            before
16168        );
16169        assert!(git::is_clean(&winner.worktree).await.unwrap());
16170
16171        let started = tmp.path().join("pre-gate-started");
16172        let proceed = tmp.path().join("pre-gate-proceed");
16173        let checked = tmp.path().join("gate-ran");
16174        runner.state.config.verify.pre_gate = vec![format!(
16175            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16176            started.display(),
16177            proceed.display()
16178        )];
16179        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16180        assert_eq!(
16181            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16182            0
16183        );
16184        let mut gate = Box::pin(runner.run_gate(&winner));
16185        assert!(
16186            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16187                .await
16188                .is_err()
16189        );
16190        assert!(!started.exists());
16191        assert!(!checked.exists());
16192        assert!(git::is_clean(&winner.worktree).await.unwrap());
16193        assert_eq!(
16194            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16195            0
16196        );
16197        tokio::select! {
16198            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16199            result = tokio::time::timeout(Duration::from_secs(10), async {
16200                while !started.exists() {
16201                    tokio::time::sleep(Duration::from_millis(20)).await;
16202                }
16203            }) => result.unwrap(),
16204        }
16205        assert_eq!(
16206            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16207            -1,
16208            "mechanical edits must hold the real lock"
16209        );
16210        std::fs::write(proceed, "ready").unwrap();
16211        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16212            .await
16213            .unwrap()
16214            .unwrap();
16215        drop(gate);
16216        assert!(outcomes.iter().all(CommandOutcome::ok));
16217        assert!(checked.exists());
16218        assert!(runner.state.pre_gate_commit.is_some());
16219        assert!(git::is_clean(&winner.worktree).await.unwrap());
16220        assert_eq!(
16221            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16222            0,
16223            "gate completion must release coordination"
16224        );
16225        drop(outsider);
16226        std::fs::remove_file(common.join("updater.lock")).unwrap();
16227        std::fs::create_dir(common.join("updater.lock")).unwrap();
16228        std::fs::remove_file(&started).unwrap();
16229        std::fs::remove_file(&checked).unwrap();
16230        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16231        let error = runner.run_gate(&winner).await.unwrap_err();
16232        assert!(
16233            error
16234                .to_string()
16235                .contains("acquire mandatory repository lock")
16236        );
16237        assert!(
16238            !started.exists(),
16239            "failed acquisition must prevent pre-gate"
16240        );
16241        assert!(!checked.exists(), "failed acquisition must prevent gate");
16242        assert!(git::is_clean(&winner.worktree).await.unwrap());
16243        assert_eq!(
16244            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16245            head
16246        );
16247    }
16248
16249    #[tokio::test]
16250    #[cfg(unix)]
16251    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16252        use std::os::fd::AsRawFd as _;
16253        use std::time::Duration;
16254
16255        ask_test_home();
16256        let tmp = tempfile::tempdir().unwrap();
16257        let repo = tmp.path().join("repo");
16258        std::fs::create_dir_all(&repo).unwrap();
16259        init_repo(&repo);
16260        let common = repo.join(".git");
16261        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16262        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16263        assert_eq!(
16264            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16265            0
16266        );
16267        let mut runner = runner_at(RunStatus::Prep);
16268        runner.state.repo = repo.clone();
16269        runner.state.config.coordination = crate::config::test_coordination();
16270        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16271        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16272        runner.state.config.graph.advise = true;
16273        runner.state.config.graph.advisors = 1;
16274        runner.roles.implementers = vec![spec("implement")];
16275        runner.roles.judges = vec![spec("judge")];
16276        let root = runner.state.worktree_root();
16277        let started = tmp.path().join("setup-started");
16278        let proceed = tmp.path().join("setup-proceed");
16279        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16280            run: Some(format!(
16281                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16282                started.display(),
16283                proceed.display()
16284            )),
16285            ..Default::default()
16286        }];
16287        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16288        let config = git::git(&repo, &["config", "--local", "--list"])
16289            .await
16290            .unwrap();
16291        let mut prep = Box::pin(runner.prep());
16292        assert!(
16293            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16294                .await
16295                .is_err()
16296        );
16297        assert!(
16298            !root.exists(),
16299            "contention must prevent even checkout creation"
16300        );
16301        assert!(!started.exists(), "contention must prevent setup");
16302        assert_eq!(
16303            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16304            branches
16305        );
16306        assert_eq!(
16307            git::git(&repo, &["config", "--local", "--list"])
16308                .await
16309                .unwrap(),
16310            config
16311        );
16312        drop(lock);
16313        tokio::select! {
16314            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16315            result = tokio::time::timeout(Duration::from_secs(10), async {
16316                while !started.exists() {
16317                    tokio::time::sleep(Duration::from_millis(20)).await;
16318                }
16319            }) => result.unwrap(),
16320        }
16321        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16322        assert_eq!(
16323            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16324            -1
16325        );
16326        assert!(
16327            tokio::time::timeout(
16328                Duration::from_millis(100),
16329                crate::repo_lock::SeatLease::for_checkout(
16330                    &repo,
16331                    true,
16332                    crate::config::test_coordination().as_ref()
16333                )
16334            )
16335            .await
16336            .is_err(),
16337            "preparation must also exclude local editors"
16338        );
16339        std::fs::write(proceed, "ready").unwrap();
16340        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16341            .await
16342            .unwrap()
16343            .unwrap();
16344        drop(prep);
16345        assert_eq!(runner.state.prep_complete, Some(true));
16346        assert!(root.join("judge-1").exists());
16347        assert!(root.join("advisor-1").exists());
16348        assert_eq!(
16349            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16350            0
16351        );
16352    }
16353
16354    #[tokio::test]
16355    #[cfg(unix)]
16356    async fn preparation_lock_failure_prevents_repository_changes() {
16357        ask_test_home();
16358        let tmp = tempfile::tempdir().unwrap();
16359        let repo = tmp.path().join("repo");
16360        std::fs::create_dir_all(&repo).unwrap();
16361        init_repo(&repo);
16362        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16363        // A directory at the required lock path makes opening the real lock
16364        // fail, rather than merely exercising an invalid registration.
16365        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16366        let mut runner = runner_at(RunStatus::Prep);
16367        runner.state.repo = repo.clone();
16368        runner.state.config.coordination = crate::config::test_coordination();
16369        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16370        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16371        runner.roles.implementers = vec![spec("implement")];
16372        let error = runner.prep().await.unwrap_err();
16373        assert!(
16374            error
16375                .to_string()
16376                .contains("acquire mandatory repository lock")
16377        );
16378        assert!(!runner.state.worktree_root().exists());
16379        assert!(runner.state.candidates.is_empty());
16380        assert!(!repo.join(".git/config.worktree").exists());
16381        assert_eq!(
16382            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16383            "* main"
16384        );
16385    }
16386
16387    #[tokio::test]
16388    async fn preparation_records_creation_intent_before_git_can_fail() {
16389        ask_test_home();
16390        let tmp = tempfile::tempdir().unwrap();
16391        let repo = tmp.path().join("repo");
16392        std::fs::create_dir_all(&repo).unwrap();
16393        init_repo(&repo);
16394        let mut runner = runner_at(RunStatus::Prep);
16395        runner.state.repo = repo.clone();
16396        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16397        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16398        runner.state.config.blind.commit_msg_hook = false;
16399        runner.roles.implementers = vec![spec("one")];
16400        let label = blind::assign_labels(1, runner.state.seed)[0];
16401        let branch = runner.state.branch_for(label);
16402        // A conflicting branch makes Git refuse creation before a candidate
16403        // can be registered. The durable intent must still identify it.
16404        git::git(&repo, &["branch", &branch]).await.unwrap();
16405        assert!(runner.prep().await.is_err());
16406        let saved = RunState::load(&runner.state.id).unwrap();
16407        assert!(saved.candidates.is_empty());
16408        let event = saved
16409            .events
16410            .iter()
16411            .find(|e| e.node == "prep-intent")
16412            .unwrap();
16413        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16414        assert_eq!(intent["branch"], branch);
16415        assert_eq!(intent["start"], runner.state.base_commit);
16416        assert_eq!(
16417            intent["worktree"],
16418            runner
16419                .state
16420                .worktree_root()
16421                .join(format!("cand-{label}"))
16422                .to_string_lossy()
16423                .as_ref()
16424        );
16425        assert_eq!(intent["picks"], serde_json::json!([]));
16426    }
16427
16428    #[tokio::test]
16429    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16430        ask_test_home();
16431        let tmp = tempfile::tempdir().unwrap();
16432        let repo = tmp.path().join("repo");
16433        std::fs::create_dir_all(&repo).unwrap();
16434        init_repo(&repo);
16435        let mut runner = runner_at(RunStatus::Prep);
16436        runner.state.repo = repo.clone();
16437        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16438        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16439        runner.state.sources.pick_commits.push(refs::Input {
16440            token: "missing".into(),
16441            sha: "0".repeat(40),
16442            provenance: refs::Provenance::ExplicitCli,
16443        });
16444        assert!(runner.prep().await.is_err());
16445        assert!(runner.state.candidates.is_empty());
16446        assert!(!runner.state.worktree_root().exists());
16447    }
16448
16449    #[tokio::test]
16450    async fn prose_and_legacy_inference_never_import_into_candidates() {
16451        ask_test_home();
16452        let tmp = tempfile::tempdir().unwrap();
16453        let repo = tmp.path().join("repo");
16454        std::fs::create_dir_all(&repo).unwrap();
16455        init_repo(&repo);
16456        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16457        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16458            .await
16459            .unwrap();
16460        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16461        git::git(&repo, &["add", "."]).await.unwrap();
16462        git::git(&repo, &["commit", "-m", "historical implementation"])
16463            .await
16464            .unwrap();
16465        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16466        git::git(&repo, &["checkout", "main"]).await.unwrap();
16467        for instruction in [
16468            format!("Example: magi/history/A at {source}"),
16469            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16470            format!("Never import magi/history/A or {source}"),
16471            format!("Conversation answer: I mentioned {source} only as background"),
16472        ] {
16473            let mut runner = runner_at(RunStatus::Prep);
16474            runner.state.repo = repo.clone();
16475            runner.state.base_commit = base.clone();
16476            runner.state.instruction = instruction.clone();
16477            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16478            runner.state.config.blind.commit_msg_hook = false;
16479            runner.state.seeds = vec![refs::Seed {
16480                token: "magi/history/A".into(),
16481                sha: source.clone(),
16482                kind: refs::SeedKind::Unmerged,
16483                branch: true,
16484                detail: String::new(),
16485            }];
16486            runner.roles.implementers = vec![spec("one")];
16487            assert_eq!(seeded_instruction(&runner.state), instruction);
16488            // Model an old record with inferred seeds but no structured input field.
16489            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16490            legacy.as_object_mut().unwrap().remove("sources");
16491            runner.state = serde_json::from_value(legacy).unwrap();
16492            assert_eq!(runner.state.sources, refs::Sources::default());
16493            runner.state.save().unwrap();
16494            runner.state = RunState::load(&runner.state.id).unwrap();
16495            runner.prep().await.unwrap();
16496            for candidate in &runner.state.candidates {
16497                assert_eq!(
16498                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16499                    base
16500                );
16501                assert!(!candidate.worktree.join("unwanted").exists());
16502            }
16503        }
16504    }
16505
16506    #[tokio::test]
16507    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16508        ask_test_home();
16509        let tmp = tempfile::tempdir().unwrap();
16510        let repo = tmp.path().join("repo");
16511        std::fs::create_dir_all(&repo).unwrap();
16512        init_repo(&repo);
16513        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16514        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16515        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16516        git::git(&repo, &["add", "."]).await.unwrap();
16517        git::git(&repo, &["commit", "-m", "required seed"])
16518            .await
16519            .unwrap();
16520        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16521        git::git(&repo, &["checkout", "main"]).await.unwrap();
16522        let mut runner = runner_at(RunStatus::Prep);
16523        runner.state.repo = repo.clone();
16524        runner.state.base_commit = base.clone();
16525        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16526        runner.state.config.graph.advise = false;
16527        runner.state.config.blind.commit_msg_hook = false;
16528        runner.state.sources =
16529            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16530                .await
16531                .unwrap();
16532        runner.roles.implementers = vec![spec("one"), spec("two")];
16533        runner.roles.judges = vec![spec("judge")];
16534        let label = blind::assign_labels(2, runner.state.seed)[0];
16535        let branch = runner.state.branch_for(label);
16536        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16537        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16538            .await
16539            .unwrap();
16540        runner.state.candidates.push(Candidate {
16541            index: 0,
16542            label,
16543            agent: "one".into(),
16544            branch,
16545            worktree,
16546            summary: String::new(),
16547            stat: String::new(),
16548            files: 0,
16549            commits: 0,
16550            empty: false,
16551            failed: None,
16552            verified_noop: None,
16553            duration_ms: 0,
16554            folded: false,
16555        });
16556        runner.state.save().unwrap();
16557        // Reload the checkpoint immediately before its first cherry-pick.
16558        runner.state = RunState::load(&runner.state.id).unwrap();
16559        assert_eq!(runner.state.prep_complete, Some(false));
16560        runner.prep().await.unwrap();
16561        assert_eq!(runner.state.prep_complete, Some(true));
16562        assert_eq!(runner.state.candidates.len(), 2);
16563        for candidate in &runner.state.candidates {
16564            assert_eq!(
16565                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16566                git::tree_of(&repo, &seed).await.unwrap()
16567            );
16568            assert_eq!(
16569                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16570                "required commit"
16571            );
16572        }
16573        assert!(runner.state.worktree_root().join("judge-1").exists());
16574        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16575        runner.prep().await.unwrap();
16576        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16577
16578        runner.state.prep_complete = Some(false);
16579        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16580            run: Some(format!(
16581                "test -f '{}'",
16582                tmp.path().join("dependency-ready").display()
16583            )),
16584            ..Default::default()
16585        }];
16586        assert!(runner.prep().await.is_err());
16587        assert!(runner.state.prep_failure.is_some());
16588        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16589        runner.state = RunState::load(&runner.state.id).unwrap();
16590        assert!(
16591            runner.prep().await.is_err(),
16592            "correcting the cause alone must not auto-retry"
16593        );
16594        let failed_at = runner.state.events.last().unwrap().at;
16595        assert!(
16596            runner.retry_preparation(failed_at).is_err(),
16597            "old approvals cannot unlock the hold"
16598        );
16599        let mut task = crate::queue::Task::new(
16600            "retry".into(),
16601            "retry setup".into(),
16602            repo.clone(),
16603            crate::queue::Source::Human,
16604        );
16605        task.start(runner.state.id.clone());
16606        task.hold_machine(Some("setup failed".into()));
16607        task.release_operator("cli", None);
16608        runner
16609            .retry_preparation(task.resumption.as_ref().unwrap().at)
16610            .unwrap();
16611        runner.prep().await.unwrap();
16612        assert!(runner.state.prep_failure.is_none());
16613        assert_eq!(runner.state.prep_complete, Some(true));
16614        assert_eq!(runner.state.candidates.len(), 2);
16615        assert!(runner.state.worktree_root().join("judge-1").exists());
16616        for candidate in &runner.state.candidates {
16617            assert_eq!(
16618                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16619                git::tree_of(&repo, &seed).await.unwrap()
16620            );
16621        }
16622    }
16623
16624    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16625        let mut heads = Vec::new();
16626        for candidate in candidates {
16627            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16628        }
16629        heads
16630    }
16631
16632    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16633        ask_test_home();
16634        let tmp = tempfile::tempdir().unwrap();
16635        let repo = tmp.path().join("repo");
16636        std::fs::create_dir(&repo).unwrap();
16637        init_repo(&repo);
16638        let mut runner = runner_at(RunStatus::Reviewing);
16639        runner.state.repo = repo.clone();
16640        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16641        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16642        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16643            let branch = format!("candidate-{label}");
16644            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16645            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16646                .await
16647                .unwrap();
16648            if label == 'B' {
16649                std::fs::write(worktree.join("change"), "winner").unwrap();
16650                git::rescue_commit(&worktree, "candidate change")
16651                    .await
16652                    .unwrap();
16653            }
16654            runner.state.candidates.push(Candidate {
16655                index,
16656                label,
16657                agent: "alpha".into(),
16658                branch,
16659                worktree,
16660                summary: "completed reply".into(),
16661                stat: String::new(),
16662                files: usize::from(label == 'B'),
16663                commits: usize::from(label == 'B'),
16664                empty: label == 'A',
16665                failed: None,
16666                verified_noop: None,
16667                duration_ms: 1,
16668                folded: false,
16669            });
16670        }
16671        runner.state.judge_skipped = true;
16672        runner.state.tally = Some(Tally {
16673            first_choice: BTreeMap::new(),
16674            borda: BTreeMap::new(),
16675            winner: 'B',
16676            rankings: 0,
16677            unanimous_initial: false,
16678            deliberated: false,
16679            changed_votes: 0,
16680            unanimous_final: false,
16681            tie_break: None,
16682            judges: 0,
16683            present: 0,
16684            quorum: 0,
16685            met_quorum: true,
16686            uncontested: Some("only B produced a change".into()),
16687        });
16688        runner.state.save().unwrap();
16689        (tmp, runner)
16690    }
16691
16692    #[tokio::test]
16693    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16694        let (_tmp, mut runner) = preservation_resume_fixture().await;
16695        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16696        runner.state.config.disk.cache_limit_bytes = 0;
16697        runner.state.config.graph.advise = true;
16698        runner.state.config.graph.advisors = 1;
16699        let advisor = runner.state.worktree_root().join("advisor-1");
16700        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16701            .await
16702            .unwrap();
16703        let home = crate::run::home();
16704        let loser =
16705            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16706        let winner =
16707            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16708        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16709        for target in [&loser, &winner, &advisor] {
16710            std::fs::write(target.join("build-output"), "compiled").unwrap();
16711        }
16712
16713        runner.fold_losers().await.unwrap();
16714
16715        assert!(!loser.join("build-output").exists());
16716        assert!(!advisor.join("build-output").exists());
16717        assert!(winner.join("build-output").is_file());
16718    }
16719
16720    #[tokio::test]
16721    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16722        let (_tmp, mut runner) = preservation_resume_fixture().await;
16723        runner.state.candidates[0].folded = true;
16724        runner.state.config.graph.advise = true;
16725        runner.state.config.graph.advisors = 2;
16726        let repo = runner.state.repo.clone();
16727        let root = runner.state.worktree_root();
16728        let discarded = root.join("advisor-1");
16729        git::worktree_add_detached(&repo, &discarded, "main")
16730            .await
16731            .unwrap();
16732        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16733        let protected = root.join("advisor-2");
16734        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16735            .await
16736            .unwrap();
16737        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16738        runner.state.save().unwrap();
16739
16740        assert!(runner.fold_losers().await.is_err());
16741        assert!(!discarded.exists());
16742        assert!(protected.join("keep").exists());
16743        let saved = RunState::load(&runner.state.id).unwrap();
16744        assert!(saved.events.iter().any(|event| {
16745            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16746        }));
16747    }
16748
16749    #[tokio::test]
16750    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16751        let (tmp, mut runner) = preservation_resume_fixture().await;
16752        let repo = runner.state.repo.clone();
16753        let root = runner.state.worktree_root();
16754        for name in ["advisor-3", "judge-1", "review-2"] {
16755            let path = root.join(name);
16756            git::worktree_add_detached(&repo, &path, "main")
16757                .await
16758                .unwrap();
16759            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16760            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16761            remove_read_seat_worktree(&mut runner.state, &path)
16762                .await
16763                .unwrap();
16764            assert!(!path.exists());
16765        }
16766        let outside = tmp.path().join("advisor-1");
16767        let unknown = root.join("unknown");
16768        let attached = root.join("advisor-4");
16769        git::worktree_add_detached(&repo, &outside, "main")
16770            .await
16771            .unwrap();
16772        git::worktree_add_detached(&repo, &unknown, "main")
16773            .await
16774            .unwrap();
16775        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16776            .await
16777            .unwrap();
16778        let foreign = tmp.path().join("foreign");
16779        std::fs::create_dir(&foreign).unwrap();
16780        init_repo(&foreign);
16781        let wrong_repo = root.join("judge-2");
16782        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16783            .await
16784            .unwrap();
16785        let candidate = runner.state.candidates[0].worktree.clone();
16786        for path in [outside, unknown, attached, wrong_repo, candidate] {
16787            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16788            assert!(
16789                remove_read_seat_worktree(&mut runner.state, &path)
16790                    .await
16791                    .is_err()
16792            );
16793            assert_eq!(
16794                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16795                "keep"
16796            );
16797        }
16798    }
16799
16800    #[tokio::test]
16801    #[cfg(unix)]
16802    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16803        for (solo, failed_checkpoint) in
16804            [(true, false), (false, false), (true, true), (false, true)]
16805        {
16806            let (_tmp, mut runner) = preservation_resume_fixture().await;
16807            if solo {
16808                runner.state.candidates.retain(|c| c.label == 'A');
16809            }
16810            runner.state.candidates[0].empty = false;
16811            runner.state.candidates[0].summary.clear();
16812            runner.state.tally = None;
16813            runner.state.judge_skipped = false;
16814            runner.state.status = RunStatus::Implementing;
16815            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16816            let mut implementer = spec("alpha");
16817            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16818            runner.roles.implementers = vec![implementer];
16819            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16820            if failed_checkpoint {
16821                std::fs::create_dir_all(&patch).unwrap();
16822            }
16823            runner.state.save().unwrap();
16824            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16825            drop(pressure);
16826            runner.state = RunState::load(&runner.state.id).unwrap();
16827            assert_eq!(runner.state.status, RunStatus::Blocked);
16828            assert!(runner.state.interrupted_implementations.contains(&'A'));
16829            assert_eq!(runner.state.candidates[0].commits, 0);
16830            assert!(!runner.state.candidates[0].empty);
16831            assert!(runner.state.candidates[0].failed.is_none());
16832            if failed_checkpoint {
16833                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16834                std::fs::remove_dir(patch).unwrap();
16835            }
16836            runner.state.resource_block = None;
16837            runner.state.config.disk.min_free_bytes = 0;
16838            runner.roles.implementers[0].command = vec![
16839                "sh".into(),
16840                "-c".into(),
16841                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16842            ];
16843            runner.implement().await.unwrap();
16844            assert!(runner.state.interrupted_implementations.is_empty());
16845            assert!(runner.state.candidate_preservation.is_empty());
16846            assert_eq!(runner.state.candidates[0].commits, 1);
16847            assert!(!runner.state.candidates[0].empty);
16848            assert!(
16849                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16850                    .unwrap()
16851                    .contains("retried empty interrupted seat")
16852            );
16853            if !solo {
16854                assert_eq!(runner.state.candidates[1].commits, 1);
16855            }
16856        }
16857    }
16858
16859    #[tokio::test]
16860    #[cfg(unix)]
16861    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16862        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16863            let (_tmp, mut runner) = preservation_resume_fixture().await;
16864            runner.state.candidates.retain(|c| c.label == 'A');
16865            runner.state.candidates[0].empty = false;
16866            runner.state.candidates[0].summary.clear();
16867            runner.state.tally = None;
16868            runner.state.judge_skipped = false;
16869            runner.state.status = RunStatus::Implementing;
16870            // Force only the real post-spawn watchdog, without failing the
16871            // separate admission check. Existing edits predate its measurement.
16872            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16873            let wt = runner.state.candidates[0].worktree.clone();
16874            std::fs::write(
16875                wt.join("interrupted-source"),
16876                "retain implementation work\n",
16877            )
16878            .unwrap();
16879            if committed {
16880                git::rescue_commit(&wt, "implementation checkpoint")
16881                    .await
16882                    .unwrap();
16883            }
16884            let lock = git::git(
16885                &wt,
16886                &[
16887                    "rev-parse",
16888                    "--path-format=absolute",
16889                    "--git-path",
16890                    "index.lock",
16891                ],
16892            )
16893            .await
16894            .unwrap();
16895            if block_rescue {
16896                std::fs::write(&lock, "fixture-owned lock").unwrap();
16897            }
16898            let mut implementer = spec("alpha");
16899            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16900            runner.roles.implementers = vec![implementer];
16901            runner.state.save().unwrap();
16902            let result = runner.implement().await;
16903            drop(pressure);
16904            assert_eq!(result.is_err(), block_rescue);
16905            assert_eq!(
16906                runner.state.resource_block.as_ref().unwrap().kind,
16907                "disk pressure"
16908            );
16909            assert!(
16910                runner
16911                    .state
16912                    .events
16913                    .iter()
16914                    .any(|e| e.message.contains("agent execution interrupted"))
16915            );
16916            assert!(
16917                runner
16918                    .state
16919                    .dir()
16920                    .join("artifacts/candidate-A-recovery/staged.patch")
16921                    .exists()
16922            );
16923            if block_rescue {
16924                let saved = RunState::load(&runner.state.id).unwrap();
16925                assert!(saved.candidate_preservation.contains_key(&'A'));
16926                assert!(!saved.candidates[0].empty);
16927                assert_eq!(
16928                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16929                    "retain implementation work\n"
16930                );
16931                std::fs::remove_file(lock).unwrap();
16932                runner.state = saved;
16933            } else {
16934                assert_eq!(runner.state.status, RunStatus::Blocked);
16935                assert_eq!(runner.state.candidates[0].commits, 1);
16936            }
16937            // Recovery must save the candidate before deciding whether another
16938            // implementation is needed. No implementer is available on retry.
16939            runner.roles.implementers.clear();
16940            runner.state.config.disk.min_free_bytes = 0;
16941            runner.state.resource_block = None;
16942            runner.implement().await.unwrap();
16943            assert!(runner.state.candidate_preservation.is_empty());
16944            assert_eq!(runner.state.candidates[0].commits, 1);
16945            assert!(!runner.state.candidates[0].empty);
16946            assert!(git::is_clean(&wt).await.unwrap());
16947            assert!(
16948                crate::run::read_artifact(&runner.state, "cand-A.patch")
16949                    .unwrap()
16950                    .contains("retain implementation work")
16951            );
16952        }
16953    }
16954
16955    #[tokio::test]
16956    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16957        let (_tmp, mut runner) = preservation_resume_fixture().await;
16958        // Schema 15 already confirmed the unfolded no-change result.
16959        runner.implement().await.unwrap();
16960        assert!(runner.state.candidate_preservation.is_empty());
16961        assert!(
16962            !runner
16963                .state
16964                .dir()
16965                .join("artifacts/candidate-A-recovery")
16966                .exists()
16967        );
16968        runner.fold_losers().await.unwrap();
16969        assert!(!runner.state.candidates[0].worktree.exists());
16970        for schema in [14, crate::run::SCHEMA] {
16971            runner.state.schema = schema;
16972            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16973            runner.state.save().unwrap();
16974            runner.state = RunState::load(&runner.state.id).unwrap();
16975            runner.implement().await.unwrap();
16976            assert!(runner.state.candidate_preservation.is_empty());
16977            assert!(runner.state.candidates[0].folded);
16978            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16979        }
16980    }
16981
16982    #[tokio::test]
16983    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16984        let (_tmp, mut runner) = preservation_resume_fixture().await;
16985        runner.state.candidates.retain(|c| c.label == 'A');
16986        runner.state.tally = None;
16987        runner.state.judge_skipped = false;
16988        let candidate = &mut runner.state.candidates[0];
16989        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16990        candidate.failed = Some("deployment validation unavailable".into());
16991        std::fs::write(
16992            candidate.worktree.join("repair"),
16993            "future launcher policy\n",
16994        )
16995        .unwrap();
16996        runner
16997            .state
16998            .candidate_preservation
16999            .insert('A', "awaiting persistence".into());
17000        runner.persist_candidates().await.unwrap();
17001        let candidate = &runner.state.candidates[0];
17002        assert!(!candidate.empty);
17003        assert_eq!(candidate.commits, 1);
17004        assert_eq!(candidate.files, 1);
17005        assert!(candidate.failed.is_none());
17006        assert!(candidate.summary.contains("EPERM"));
17007        assert!(
17008            crate::run::read_artifact(&runner.state, "cand-A.patch")
17009                .unwrap()
17010                .contains("future launcher policy")
17011        );
17012        assert!(runner.state.candidate_preservation.is_empty());
17013    }
17014
17015    #[tokio::test]
17016    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17017        let (_tmp, mut runner) = preservation_resume_fixture().await;
17018        let wt = runner.state.candidates[0].worktree.clone();
17019        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17020        runner.state.schema = 14;
17021        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17022        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17023        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17024        for _ in 0..2 {
17025            assert!(runner.implement().await.is_err());
17026            assert_eq!(runner.state.status, RunStatus::Blocked);
17027            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17028            assert!(
17029                runner.state.candidates[0].empty,
17030                "old verdict must remain unusable"
17031            );
17032            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17033            assert!(runner.state.judge_skipped);
17034            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17035            assert!(
17036                crate::run::read_artifact(&runner.state, "cand-A.patch")
17037                    .unwrap()
17038                    .contains("owned edits")
17039            );
17040            assert!(wt.exists());
17041            assert_eq!(
17042                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17043                    .await
17044                    .unwrap(),
17045                1
17046            );
17047            runner.state = RunState::load(&runner.state.id).unwrap();
17048        }
17049    }
17050
17051    #[tokio::test]
17052    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17053        let (_tmp, mut runner) = preservation_resume_fixture().await;
17054        let wt = runner.state.candidates[0].worktree.clone();
17055        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17056        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17057        let index_lock = PathBuf::from(
17058            git::git(
17059                &wt,
17060                &[
17061                    "rev-parse",
17062                    "--path-format=absolute",
17063                    "--git-path",
17064                    "index.lock",
17065                ],
17066            )
17067            .await
17068            .unwrap(),
17069        );
17070        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17071        runner.state.schema = 14;
17072        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17073        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17074        assert!(runner.implement().await.is_err());
17075        assert!(runner.after_implement().is_err());
17076        assert!(runner.fold_losers().await.is_err());
17077        assert_eq!(
17078            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17079            "failed seat edits"
17080        );
17081        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17082        runner.state = RunState::load(&runner.state.id).unwrap();
17083        std::fs::remove_file(index_lock).unwrap();
17084        // Recovery finds changes that the old uncontested result never judged.
17085        assert!(runner.implement().await.is_err());
17086        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17087        assert!(runner.state.candidates[0].empty);
17088        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17089        assert!(
17090            crate::run::read_artifact(&runner.state, "cand-A.patch")
17091                .unwrap()
17092                .contains("failed seat edits")
17093        );
17094        assert!(wt.exists());
17095    }
17096
17097    #[tokio::test]
17098    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17099        let (_tmp, mut runner) = preservation_resume_fixture().await;
17100        let repo = runner.state.repo.clone();
17101        let common = git::git(
17102            &repo,
17103            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17104        )
17105        .await
17106        .unwrap();
17107        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17108        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17109        assert!(runner.fold_losers().await.is_err());
17110        assert!(!runner.state.candidates[0].worktree.exists());
17111        assert!(!runner.state.candidates[0].folded);
17112        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17113        runner.state = RunState::load(&runner.state.id).unwrap();
17114        std::fs::remove_file(branch_lock).unwrap();
17115        let judge = runner.state.worktree_root().join("judge-1");
17116        git::worktree_add_detached(&repo, &judge, "main")
17117            .await
17118            .unwrap();
17119        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17120        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17121            .await
17122            .unwrap();
17123        runner.roles.judges = vec![spec("judge")];
17124        assert!(runner.fold_losers().await.is_err());
17125        runner.state = RunState::load(&runner.state.id).unwrap();
17126        assert!(
17127            runner.state.candidates[0].folded,
17128            "candidate progress saved before judge failure"
17129        );
17130        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17131        assert!(judge.join("uncommitted").exists());
17132        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17133            .await
17134            .unwrap();
17135        runner.fold_losers().await.unwrap();
17136        assert!(!judge.exists());
17137        runner.fold_losers().await.unwrap();
17138    }
17139
17140    #[tokio::test]
17141    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17142        let (_tmp, mut runner) = preservation_resume_fixture().await;
17143        runner.state.candidates.retain(|c| c.label == 'B');
17144        runner.state.tally = None;
17145        runner.state.judge_skipped = false;
17146        runner.state.prep_complete = Some(true);
17147        runner.state.config.graph.advise = false;
17148        runner.state.config.graph.selected_implementer = Some("alpha".into());
17149        let wt = runner.state.candidates[0].worktree.clone();
17150        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17151        runner
17152            .state
17153            .candidate_preservation
17154            .insert('B', "awaiting persistence".into());
17155        let index_lock = git::git(
17156            &wt,
17157            &[
17158                "rev-parse",
17159                "--path-format=absolute",
17160                "--git-path",
17161                "index.lock",
17162            ],
17163        )
17164        .await
17165        .unwrap();
17166        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17167        runner.state.save().unwrap();
17168        assert!(runner.execute_graph().await.is_err());
17169        assert_eq!(runner.state.status, RunStatus::Blocked);
17170        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17171        std::fs::remove_file(index_lock).unwrap();
17172        // Park at the next graph boundary: this tests the real selected-seat
17173        // hold guard without dispatching reviewers or publishing anything.
17174        for _ in 0..2 {
17175            runner.state = RunState::load(&runner.state.id).unwrap();
17176            runner.pause.park();
17177            runner.execute_graph().await.unwrap();
17178            assert_eq!(runner.state.status, RunStatus::Implementing);
17179            assert!(runner.state.candidate_preservation.is_empty());
17180            assert_eq!(runner.state.candidates[0].commits, 2);
17181            assert!(runner.state.tally.is_none());
17182        }
17183        runner.implement().await.unwrap();
17184        assert_eq!(runner.state.status, RunStatus::Judging);
17185        // A genuine selected-implementer hold must still require release.
17186        runner.state.status = RunStatus::Blocked;
17187        runner.state.candidates[0].failed = Some("implementation failed".into());
17188        runner.state.save().unwrap();
17189        let error = runner.execute_graph().await.unwrap_err();
17190        assert!(
17191            error
17192                .to_string()
17193                .contains("selected implementation is held")
17194        );
17195    }
17196
17197    #[tokio::test]
17198    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17199        let (_tmp, mut runner) = preservation_resume_fixture().await;
17200        let repo = runner.state.repo.clone();
17201        let candidate = runner.state.candidates[0].clone();
17202        // Remove only the disposable fixture directory, leaving Git's linked
17203        // worktree registration and branch intact, as in a vanished checkout.
17204        let registered = git::worktree_holding(&repo, &candidate.branch)
17205            .await
17206            .unwrap()
17207            .unwrap();
17208        assert_eq!(
17209            registered.canonicalize().unwrap(),
17210            candidate.worktree.canonicalize().unwrap()
17211        );
17212        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17213        assert_eq!(
17214            git::worktree_holding(&repo, &candidate.branch)
17215                .await
17216                .unwrap(),
17217            Some(registered)
17218        );
17219        assert!(
17220            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17221            "the stale registration initially keeps the branch checked out"
17222        );
17223        runner.fold_losers().await.unwrap();
17224        assert!(runner.state.candidates[0].folded);
17225        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17226        assert_eq!(
17227            git::worktree_holding(&repo, &candidate.branch)
17228                .await
17229                .unwrap(),
17230            None
17231        );
17232        runner.state = RunState::load(&runner.state.id).unwrap();
17233        runner.fold_losers().await.unwrap();
17234    }
17235
17236    #[tokio::test]
17237    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17238        let (_tmp, mut runner) = preservation_resume_fixture().await;
17239        let repo = runner.state.repo.clone();
17240        let candidate = runner.state.candidates[0].clone();
17241        let winner = runner.state.candidates[1].clone();
17242        let registered = git::worktree_holding(&repo, &candidate.branch)
17243            .await
17244            .unwrap()
17245            .unwrap();
17246        assert_eq!(
17247            registered.canonicalize().unwrap(),
17248            candidate.worktree.canonicalize().unwrap()
17249        );
17250        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17251        assert_eq!(
17252            git::worktree_holding(&repo, &candidate.branch)
17253                .await
17254                .unwrap(),
17255            Some(registered)
17256        );
17257        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17258
17259        for _ in 0..2 {
17260            fold_run(&mut runner.state, false, &crate::run::home())
17261                .await
17262                .unwrap();
17263            runner.state = RunState::load(&runner.state.id).unwrap();
17264            assert!(runner.state.candidates[0].folded);
17265            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17266            assert_eq!(
17267                git::worktree_holding(&repo, &candidate.branch)
17268                    .await
17269                    .unwrap(),
17270                None
17271            );
17272            assert!(!runner.state.candidates[1].folded);
17273            assert!(winner.worktree.exists());
17274            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17275        }
17276    }
17277    #[tokio::test]
17278    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17279        for sidecar in [false, true] {
17280            let tmp = tempfile::tempdir().unwrap();
17281            let home = tmp.path().join("home");
17282            let repo = tmp.path().join("repo");
17283            std::fs::create_dir(&repo).unwrap();
17284            init_repo(&repo);
17285            let mut state = runner_at(RunStatus::Superseded).state;
17286            state.repo = repo.clone();
17287            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17288            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17289            state.driver_exited = true;
17290            state.reserve_under(&home).unwrap();
17291            git::git(
17292                &repo,
17293                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17294            )
17295            .await
17296            .unwrap();
17297            let wt = state.worktree_root().join("cand-A");
17298            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17299                .await
17300                .unwrap();
17301            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17302            git::commit_all(&wt, "fixture: independent source")
17303                .await
17304                .unwrap();
17305            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17306            state.candidates.push(Candidate {
17307                index: 0,
17308                label: 'A',
17309                agent: "fixture".into(),
17310                branch: "candidate".into(),
17311                worktree: wt.clone(),
17312                summary: String::new(),
17313                stat: String::new(),
17314                files: 0,
17315                commits: 0,
17316                empty: false,
17317                failed: None,
17318                verified_noop: None,
17319                duration_ms: 0,
17320                folded: false,
17321            });
17322            let mut task = crate::queue::Task::new(
17323                "task".into(),
17324                "task".into(),
17325                repo.clone(),
17326                crate::queue::Source::Human,
17327            );
17328            task.runs.push(state.id.clone());
17329            crate::queue::Queue::at(home.join("queue"))
17330                .put(&mut task)
17331                .unwrap();
17332            if sidecar {
17333                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17334            }
17335            state.save_under(&home).unwrap();
17336            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17337            assert!(
17338                fold_run(&mut state, true, &home)
17339                    .await
17340                    .unwrap_err()
17341                    .to_string()
17342                    .contains(&reason)
17343            );
17344            let mut disk = state.config.disk.clone();
17345            disk.fold_grace_secs = 0;
17346            assert_eq!(
17347                crate::clean::fold_due(
17348                    &home.join("runs"),
17349                    &home,
17350                    &state.worktree_root(),
17351                    &disk,
17352                    Timestamp::now() + std::time::Duration::from_secs(10),
17353                )
17354                .await
17355                .unwrap(),
17356                (0, 0)
17357            );
17358            assert!(wt.exists());
17359            state.status = RunStatus::Blocked;
17360            state.save_under(&home).unwrap();
17361            assert!(
17362                fold_run_overriding_recovery_retention(&mut state, true, &home)
17363                    .await
17364                    .is_err()
17365            );
17366            state.status = RunStatus::Superseded;
17367            state.driver_exited = false;
17368            state.driver_claimed = None;
17369            state.save_under(&home).unwrap();
17370            assert!(
17371                fold_run_overriding_recovery_retention(&mut state, true, &home)
17372                    .await
17373                    .is_err()
17374            );
17375            state.driver_pid = Some(std::process::id());
17376            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17377            state.save_under(&home).unwrap();
17378            assert!(
17379                fold_run_overriding_recovery_retention(&mut state, true, &home)
17380                    .await
17381                    .is_err()
17382            );
17383            state.driver_exited = true;
17384            state.driver_pid = None;
17385            state.driver_started_at = None;
17386            state.save_under(&home).unwrap();
17387            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17388            assert!(
17389                fold_run_overriding_recovery_retention(&mut state, true, &home)
17390                    .await
17391                    .is_err()
17392            );
17393            drop(lease);
17394            #[cfg(unix)]
17395            {
17396                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17397                assert!(
17398                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17399                        .await
17400                        .is_err()
17401                );
17402                drop(output);
17403            }
17404            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17405            assert!(
17406                fold_run_overriding_recovery_retention(&mut state, true, &home)
17407                    .await
17408                    .is_err()
17409            );
17410            drop(owner);
17411            let checkpoint = git::git(
17412                &wt,
17413                &[
17414                    "rev-parse",
17415                    "--path-format=absolute",
17416                    "--git-path",
17417                    "CHERRY_PICK_HEAD",
17418                ],
17419            )
17420            .await
17421            .unwrap();
17422            std::fs::write(&checkpoint, &head).unwrap();
17423            assert!(
17424                fold_run_overriding_recovery_retention(&mut state, true, &home)
17425                    .await
17426                    .is_err()
17427            );
17428            std::fs::remove_file(checkpoint).unwrap();
17429            std::fs::write(wt.join("dirty"), "keep").unwrap();
17430            assert!(
17431                fold_run_overriding_recovery_retention(&mut state, true, &home)
17432                    .await
17433                    .is_err()
17434            );
17435            assert!(wt.join("dirty").exists());
17436            std::fs::remove_file(wt.join("dirty")).unwrap();
17437            let evidence = home
17438                .join("runs")
17439                .join(&state.id)
17440                .join("artifacts/fold-evidence");
17441            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17442            std::fs::write(&evidence, "blocked archive").unwrap();
17443            assert!(
17444                fold_run_overriding_recovery_retention(&mut state, true, &home)
17445                    .await
17446                    .is_err()
17447            );
17448            assert!(wt.exists());
17449            assert!(
17450                !RunState::load_under(&state.id, &home)
17451                    .unwrap()
17452                    .events
17453                    .iter()
17454                    .any(|event| event.message.contains("--override-recovery-retention"))
17455            );
17456            std::fs::remove_file(&evidence).unwrap();
17457            fold_run_overriding_recovery_retention(&mut state, true, &home)
17458                .await
17459                .unwrap();
17460            assert!(!wt.exists());
17461            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17462            assert!(
17463                git::worktree_holding(&repo, "candidate")
17464                    .await
17465                    .unwrap()
17466                    .is_none()
17467            );
17468            assert!(
17469                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17470                    .unwrap()
17471                    .contains("retained implementation")
17472            );
17473            assert!(evidence.join(format!("{head}.index")).is_file());
17474            let saved = RunState::load_under(&state.id, &home).unwrap();
17475            assert_eq!(saved.status, RunStatus::Superseded);
17476            assert!(saved.candidates[0].folded);
17477            assert!(saved.events.iter().any(|event| {
17478                event.message.contains("--override-recovery-retention")
17479                    && event.message.contains(&state.id)
17480                    && event.message.contains(&reason)
17481            }));
17482            assert_eq!(
17483                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17484                sidecar
17485            );
17486        }
17487    }
17488
17489    #[tokio::test]
17490    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17491        ask_test_home();
17492        let tmp = tempfile::tempdir().unwrap();
17493        let repo = tmp.path().join("repo");
17494        std::fs::create_dir(&repo).unwrap();
17495        init_repo(&repo);
17496        let mut runner = runner_at(RunStatus::Implementing);
17497        runner.state.repo = repo.clone();
17498        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17499        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17500        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17501            let branch = format!("candidate-{label}");
17502            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17503            git::worktree_add_branch(&repo, &wt, &branch, "main")
17504                .await
17505                .unwrap();
17506            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17507            git::git(&wt, &["add", "README.md"]).await.unwrap();
17508            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17509            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17510            runner.state.candidates.push(Candidate {
17511                index,
17512                label,
17513                agent: "alpha".to_owned(),
17514                branch,
17515                worktree: wt,
17516                summary: "completed implementation".to_owned(),
17517                stat: String::new(),
17518                files: 0,
17519                commits: 0,
17520                empty: false,
17521                failed: None,
17522                verified_noop: None,
17523                duration_ms: 42,
17524                folded: false,
17525            });
17526            runner
17527                .state
17528                .candidate_preservation
17529                .insert(label, "awaiting persistence".to_owned());
17530        }
17531        let wt = runner.state.candidates[0].worktree.clone();
17532        let index_lock = git::git(
17533            &wt,
17534            &[
17535                "rev-parse",
17536                "--path-format=absolute",
17537                "--git-path",
17538                "index.lock",
17539            ],
17540        )
17541        .await
17542        .unwrap();
17543        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17544        runner.state.save().unwrap();
17545        assert!(runner.persist_candidates().await.is_err());
17546        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17547        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17548        assert_eq!(
17549            runner.state.candidates[1].commits, 1,
17550            "other results are still collected"
17551        );
17552        assert!(
17553            !runner.state.candidates[0].empty,
17554            "failed rescue is not no change"
17555        );
17556        assert_eq!(
17557            runner.state.candidates[0].summary,
17558            "completed implementation"
17559        );
17560        assert!(runner.after_implement().is_err());
17561        let home = tmp.path().join("fold-home");
17562        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17563        assert!(wt.join("new-file").exists());
17564        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17565        assert!(recovery.join("staged.patch").exists());
17566        assert!(recovery.join("unstaged.patch").exists());
17567        assert_eq!(
17568            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17569            "untracked edits\n"
17570        );
17571        runner.state.begin_pass();
17572        runner.state.end_pass_parked(ParkCause::Upgrade {
17573            from: "1.0".into(),
17574            to: Some("1.1".into()),
17575        });
17576        runner.state.save().unwrap();
17577        runner.state = RunState::load(&runner.state.id).unwrap();
17578        assert!(matches!(
17579            runner.state.passes.last().unwrap().end,
17580            Some(crate::run::PassEnd::Parked {
17581                cause: ParkCause::Upgrade { .. }
17582            })
17583        ));
17584        std::fs::remove_file(index_lock).unwrap();
17585        // No implementer is configured: a persistence retry cannot dispatch a seat.
17586        runner.implement().await.unwrap();
17587        assert!(runner.state.candidate_preservation.is_empty());
17588        assert!(
17589            runner
17590                .state
17591                .candidates
17592                .iter()
17593                .all(|c| c.commits == 1 && !c.empty)
17594        );
17595        assert!(git::is_clean(&wt).await.unwrap());
17596        assert!(
17597            crate::run::read_artifact(&runner.state, "cand-A.patch")
17598                .unwrap()
17599                .contains("later tracked edits")
17600        );
17601    }
17602
17603    #[tokio::test]
17604    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17605        ask_test_home();
17606        let tmp = tempfile::tempdir().unwrap();
17607        let repo = tmp.path().join("repo");
17608        std::fs::create_dir(&repo).unwrap();
17609        init_repo(&repo);
17610        let wt = tmp.path().join("candidate");
17611        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17612            .await
17613            .unwrap();
17614        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17615        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17616        assert!(wt.join("uncommitted").exists());
17617        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17618        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17619        let mut runner = runner_at(RunStatus::Implementing);
17620        runner.state.repo = repo.clone();
17621        runner.state.base_commit = "missing-base".to_owned();
17622        runner.state.candidates.push(Candidate {
17623            index: 0,
17624            label: 'A',
17625            agent: "alpha".into(),
17626            branch: "candidate".into(),
17627            worktree: wt.clone(),
17628            summary: "completed".into(),
17629            stat: String::new(),
17630            files: 0,
17631            commits: 0,
17632            empty: false,
17633            failed: None,
17634            verified_noop: None,
17635            duration_ms: 1,
17636            folded: false,
17637        });
17638        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17639        assert!(
17640            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17641                .await
17642                .is_err()
17643        );
17644        assert!(!runner.state.candidates[0].folded);
17645        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17646        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17647        runner
17648            .state
17649            .candidate_preservation
17650            .insert('A', "pending".into());
17651        assert!(runner.persist_candidates().await.is_err());
17652        assert!(!runner.state.candidates[0].empty);
17653        assert!(!runner.state.candidates[0].folded);
17654        assert!(wt.exists());
17655        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17656        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17657        std::fs::create_dir_all(&patch_path).unwrap();
17658        assert!(
17659            runner.persist_candidates().await.is_err(),
17660            "artifact failure stays pending"
17661        );
17662        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17663        assert!(!runner.state.candidates[0].empty);
17664        std::fs::remove_dir(patch_path).unwrap();
17665        runner.persist_candidates().await.unwrap();
17666        assert!(
17667            runner.state.candidates[0].empty,
17668            "only successful inspection confirms no change"
17669        );
17670    }
17671
17672    fn init_repo(dir: &Path) {
17673        let run = |args: &[&str]| {
17674            let out = std::process::Command::new("git")
17675                .args(args)
17676                .current_dir(dir)
17677                .quiet()
17678                .output()
17679                .expect("spawn git");
17680            assert!(
17681                out.status.success(),
17682                "git {args:?} failed: {}",
17683                String::from_utf8_lossy(&out.stderr)
17684            );
17685        };
17686        run(&["init", "-b", "main"]);
17687        run(&["config", "user.name", "magi test"]);
17688        run(&["config", "user.email", "magi@example.com"]);
17689        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17690        run(&["add", "-A"]);
17691        run(&["commit", "-m", "init"]);
17692    }
17693
17694    // `settle_questions` is what closes the ghost the phone showed: a run's
17695    // seat asked something, the run then ended, and nothing was left to
17696    // abandon the question it left `open`. `HOME` is a process-wide
17697    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17698    // first time it runs in the binary — every test below still reaches the
17699    // same directory whichever call won, and each gets its own run id from
17700    // `RunState::new`, so they never collide there.
17701    fn ask_test_home() {
17702        crate::run::pin_test_home();
17703    }
17704
17705    #[test]
17706    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17707        ask_test_home();
17708        let mut runner = runner_at(RunStatus::Prep);
17709        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17710        // A blocked temporary output path makes the terminal save fail while
17711        // preserving the already published reservation.
17712        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17713        let error = guard
17714            .finish(
17715                &mut runner.state,
17716                Err(
17717                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17718                        .into(),
17719                ),
17720            )
17721            .unwrap_err();
17722        assert_eq!(
17723            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17724            std::io::ErrorKind::PermissionDenied
17725        );
17726        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17727        let message = format!("{error:#}");
17728        assert!(message.contains("original refusal"));
17729        assert!(!message.contains("could not save terminal"));
17730        assert_eq!(
17731            error.chain().count(),
17732            2,
17733            "only startup attribution wraps the original error"
17734        );
17735        let saved = RunState::load(&runner.state.id).unwrap();
17736        assert_eq!(saved.status, RunStatus::Blocked);
17737        assert!(!saved.startup.unwrap().complete);
17738    }
17739
17740    #[test]
17741    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17742        ask_test_home();
17743        let mut runner = runner_at(RunStatus::Prep);
17744        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17745        let id = runner.state.id.clone();
17746        drop(guard);
17747        let saved = RunState::load(&id).unwrap();
17748        assert_eq!(saved.status, RunStatus::Blocked);
17749        assert!(!saved.startup.as_ref().unwrap().complete);
17750        assert!(
17751            saved
17752                .startup
17753                .unwrap()
17754                .failure
17755                .unwrap()
17756                .contains("interrupted")
17757        );
17758        assert!(Runner::resume(&id).is_err());
17759    }
17760
17761    #[test]
17762    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17763        ask_test_home();
17764        let mut runner = runner_at(RunStatus::Prep);
17765        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17766        let error = guard
17767            .finish(
17768                &mut runner.state,
17769                Err(
17770                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17771                        .into(),
17772                ),
17773            )
17774            .unwrap_err();
17775        assert_eq!(
17776            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17777            std::io::ErrorKind::PermissionDenied
17778        );
17779        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17780        let mut task = crate::queue::Task::new(
17781            "review".into(),
17782            "criteria".into(),
17783            runner.state.repo.clone(),
17784            crate::queue::Source::Human,
17785        );
17786        task.record_startup_failure(failure.clone());
17787        task.record_startup_failure(failure.clone());
17788        assert_eq!(task.startup_failures.len(), 1);
17789        assert!(task.runs.is_empty());
17790        assert_eq!(task.attempts, 0);
17791    }
17792
17793    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17794        ask_test_home();
17795        let tmp = tempfile::tempdir().unwrap();
17796        let repo = tmp.path().join("repo");
17797        std::fs::create_dir(&repo).unwrap();
17798        init_repo(&repo);
17799        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17800        let origin = tmp.path().join("origin.git");
17801        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17802            .await
17803            .unwrap();
17804        git::git(
17805            &repo,
17806            &["remote", "add", "origin", origin.to_str().unwrap()],
17807        )
17808        .await
17809        .unwrap();
17810        git::git(&repo, &["checkout", "-b", "fix/retained"])
17811            .await
17812            .unwrap();
17813        std::fs::write(repo.join("retained"), "retained change").unwrap();
17814        git::git(&repo, &["add", "."]).await.unwrap();
17815        git::git(&repo, &["commit", "-m", "retained implementation"])
17816            .await
17817            .unwrap();
17818        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17819        git::git(&repo, &["checkout", "main"]).await.unwrap();
17820        std::fs::write(repo.join("base-change"), "new base").unwrap();
17821        git::git(&repo, &["add", "."]).await.unwrap();
17822        git::git(&repo, &["commit", "-m", "base moved"])
17823            .await
17824            .unwrap();
17825        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17826        git::git(&repo, &["checkout", "fix/retained"])
17827            .await
17828            .unwrap();
17829        let mut runner = runner_at(RunStatus::Voting);
17830        runner.state.repo = repo.clone();
17831        runner.state.base_commit = base;
17832        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17833        runner.state.config.disk.min_free_bytes = 0;
17834        runner.state.config.graph.review_rounds = 1;
17835        runner.state.config.verify.e2e = vec!["true".into()];
17836        runner.state.config.verify.gate = vec!["true".into()];
17837        runner.state.candidates = vec![Candidate {
17838            index: 0,
17839            label: 'A',
17840            agent: "fixture".into(),
17841            branch: "fix/retained".into(),
17842            worktree: repo.clone(),
17843            summary: String::new(),
17844            stat: String::new(),
17845            files: 1,
17846            commits: 1,
17847            empty: false,
17848            failed: None,
17849            verified_noop: None,
17850            duration_ms: 0,
17851            folded: false,
17852        }];
17853        runner.state.tally = Some(Tally {
17854            first_choice: BTreeMap::new(),
17855            borda: BTreeMap::new(),
17856            winner: 'A',
17857            rankings: 0,
17858            unanimous_initial: true,
17859            deliberated: false,
17860            changed_votes: 0,
17861            unanimous_final: true,
17862            tie_break: None,
17863            judges: 0,
17864            present: 0,
17865            quorum: 0,
17866            met_quorum: true,
17867            uncontested: Some("review-only".into()),
17868        });
17869        let mut task = crate::queue::Task::new(
17870            "fixture".into(),
17871            "fixture".into(),
17872            repo,
17873            crate::queue::Source::Human,
17874        );
17875        task.link_run(&runner.state.id);
17876        crate::queue::Queue::open().put(&mut task).unwrap();
17877        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17878        runner.state.base_sync = Some(BaseSync {
17879            tip: String::new(),
17880            behind: 1,
17881            attempts: BASE_SYNC_ROUNDS,
17882            conflict: None,
17883            already_in: None,
17884        });
17885        runner.sync_to_base().await.unwrap();
17886        assert_eq!(runner.state.status, RunStatus::Blocked);
17887        (tmp, runner, head, task.id)
17888    }
17889
17890    #[tokio::test]
17891    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17892        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17893        runner.state.status = RunStatus::Voting;
17894        runner.state.base_sync = None;
17895        runner.state.base_sync_recovery = Default::default();
17896        let scratch = runner.state.dir().join("base-sync");
17897        std::fs::create_dir_all(&scratch).unwrap();
17898        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17899        runner.sync_to_base().await.unwrap();
17900        assert!(runner.state.resource_block.is_some());
17901        assert!(!runner.state.base_sync_blocked());
17902        assert!(runner.state.base_sync.is_none());
17903        assert_eq!(
17904            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
17905            "keep"
17906        );
17907        assert_eq!(runner.state.base_episode_used(), 0);
17908        assert!(runner.state.base_sync_recovery.operations.is_empty());
17909        assert!(runner.state.rebase_fixes.is_empty());
17910        assert_eq!(
17911            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17912            head
17913        );
17914        std::fs::remove_dir_all(&scratch).unwrap();
17915        runner.state.resource_block = None;
17916        runner.sync_to_base().await.unwrap();
17917        assert!(!runner.state.base_sync_blocked());
17918        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17919        assert_eq!(runner.state.base_episode_used(), 1);
17920        assert!(runner.state.base_sync_recovery.operations[0].finished);
17921        assert!(runner.state.rebase_fixes.is_empty());
17922        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17923        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17924    }
17925
17926    #[tokio::test]
17927    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
17928        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17929        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
17930        runner.state.base_sync_recovery = Default::default();
17931        runner.state.task_instruction = Some("fixture".into());
17932        runner.state.config.agents = vec![spec("fixture")];
17933        runner.state.config.graph.review_rounds = 0;
17934        runner.state.config.merge.mode = MergeMode::None;
17935        runner.state.driver_exited = true;
17936        let sync = runner.state.base_sync.as_mut().unwrap();
17937        sync.conflict = None;
17938        sync.attempts = 0;
17939        runner.state.reserve_base_operation(&head, &tip);
17940        runner.state.finish_base_operation(None);
17941        let detail = format!(
17942            "fix/retained conflicts with origin/main and did not rebase: \
17943             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
17944             remaining conflicted path(s): none recorded; git said: \
17945             warning: execution failed: {}",
17946            git::REBASE_EXEC
17947        );
17948        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
17949        runner.state.record_base_sync_stop(&head);
17950        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
17951            unstarted: false,
17952            agent: "fixture".into(),
17953            paths: Vec::new(),
17954            from: Some(head.clone()),
17955            finished: true,
17956            error: None,
17957            stop: None,
17958            onto: None,
17959            index_outside: None,
17960            launcher: None,
17961            infra: None,
17962            outage: None,
17963        });
17964        runner.state.save().unwrap();
17965        assert_eq!(
17966            crate::resume::validate(&crate::run::home(), &runner.state.id)
17967                .unwrap()
17968                .id,
17969            runner.state.id
17970        );
17971
17972        let dirty = runner.state.repo.join("owner-work");
17973        std::fs::write(&dirty, "keep").unwrap();
17974        runner.sync_to_base().await.unwrap();
17975        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
17976        assert!(runner.state.base_sync_recovery.operations[0].finished);
17977        assert!(runner.state.base_sync_blocked());
17978        std::fs::remove_file(dirty).unwrap();
17979
17980        let queue = crate::queue::Queue::open();
17981        let id = runner.state.id.clone();
17982        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
17983        let _claim = queue.claim(&owner).unwrap();
17984        let mut task = queue.get(&owner).unwrap();
17985        let config = tmp.path().join("test-config.toml");
17986        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
17987        let opts = crate::daemon::Opts {
17988            repo: task.repo.clone(),
17989            config: Some(config),
17990            ..Default::default()
17991        };
17992        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
17993        let task = queue.get(&owner).unwrap();
17994        assert_eq!(
17995            task.runs.as_slice(),
17996            std::slice::from_ref(&id),
17997            "{:?}",
17998            task.hold_reason
17999        );
18000        runner.state = RunState::load(&id).unwrap();
18001        assert!(!runner.state.base_sync_blocked());
18002        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18003        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18004        assert!(runner.state.base_sync_recovery.operations[0].finished);
18005        assert_eq!(
18006            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18007            detail
18008        );
18009        assert_eq!(runner.state.rebase_fixes.len(), 1);
18010        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18011    }
18012
18013    #[cfg(unix)]
18014    #[tokio::test]
18015    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18016        for routed in [false, true] {
18017            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18018            let home = crate::run::home();
18019            let queue = crate::queue::Queue::open();
18020            let task = queue.get(&owner).unwrap();
18021            runner.state.task_instruction = Some(task.instruction.clone());
18022            runner.state.driver_exited = true;
18023            runner.state.save().unwrap();
18024            let questions = crate::ask::Questions::at(home.join("questions"));
18025            let mut q = crate::ask::Question::new(
18026                runner.state.id.clone(),
18027                "base-recovery".into(),
18028                "owner".into(),
18029                "Recover bounded base movement?".into(),
18030                String::new(),
18031                vec!["recover".into()],
18032            );
18033            q.actions.insert(
18034                "recover".into(),
18035                crate::ask::ChoiceAction::RecoverBase {
18036                    run: runner.state.id.clone(),
18037                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18038                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18039                },
18040            );
18041            q.routed_task = Some(owner.clone());
18042            q.answer(crate::ask::Answer::Choice("recover".into()))
18043                .unwrap();
18044            questions.put(&mut q).unwrap();
18045            crate::base_recovery_control::recover(
18046                &queue,
18047                &home,
18048                crate::base_recovery_control::Request {
18049                    run: runner.state.id.clone(),
18050                    head: head.clone(),
18051                    actor: "decisions".into(),
18052                    request: q.id.clone(),
18053                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18054                    expected_stop: Some((
18055                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18056                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18057                    )),
18058                },
18059            )
18060            .await
18061            .unwrap();
18062            if routed {
18063                questions
18064                    .update(&q.id, |q| {
18065                        q.routed_task = Some("another-owner".into());
18066                        Ok(())
18067                    })
18068                    .unwrap();
18069            } else {
18070                let mut task = queue.get(&owner).unwrap();
18071                task.hold_manual(Some("new owner decision".into()));
18072                // Keep the generation to exercise the separate owner-decision binding.
18073                task.status = crate::queue::TaskStatus::Queued;
18074                queue.put(&mut task).unwrap();
18075            }
18076            runner.state = RunState::load(&runner.state.id).unwrap();
18077            runner.sync_to_base().await.unwrap();
18078            let approval = runner
18079                .state
18080                .base_sync_recovery
18081                .authorizations
18082                .last()
18083                .unwrap();
18084            assert!(approval.consumed);
18085            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18086                "routing"
18087            } else {
18088                "owner decision"
18089            }));
18090            assert_eq!(
18091                runner.state.base_sync.as_ref().unwrap().attempts,
18092                BASE_SYNC_ROUNDS
18093            );
18094            assert_eq!(
18095                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18096                head
18097            );
18098        }
18099    }
18100
18101    #[cfg(unix)]
18102    #[tokio::test]
18103    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
18104        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
18105        if std::env::var_os(CHILD).is_none() {
18106            let home = tempfile::tempdir().unwrap();
18107            let output = std::process::Command::new(std::env::current_exe().unwrap())
18108                .args([
18109                    "--exact",
18110                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
18111                    "--nocapture",
18112                ])
18113                .env(CHILD, "1")
18114                .env("MAGI_HOME", home.path())
18115                .env("MAGI_WORKER_HOME", home.path())
18116                .env("MAGI_WORKER_ID", "abcdef")
18117                .output()
18118                .unwrap();
18119            assert!(
18120                output.status.success()
18121                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18122                "{}\n{}",
18123                String::from_utf8_lossy(&output.stdout),
18124                String::from_utf8_lossy(&output.stderr)
18125            );
18126            return;
18127        }
18128        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
18129        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18130        let home = crate::run::home();
18131        let queue = crate::queue::Queue::open();
18132        let mut owner = queue.get(&task).unwrap();
18133        owner.release_operator("test-release", None);
18134        owner.start(runner.state.id.clone());
18135        queue.put(&mut owner).unwrap();
18136        runner.state.driver_exited = true;
18137        runner.state.task_instruction = Some(owner.instruction.clone());
18138        runner.state.save().unwrap();
18139        let _claim = queue.claim(&task).unwrap();
18140        let reserve = |id: &str| {
18141            let directory = home.join("workers/jobs").join(id);
18142            std::fs::create_dir_all(&directory).unwrap();
18143            let job = crate::worker::Job {
18144                id: id.into(),
18145                sequence: 1,
18146                kind: "task".into(),
18147                key: format!("task:{task}"),
18148                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
18149                generation: "fixture-generation".into(),
18150                version: None,
18151                status: crate::worker::Status::Running,
18152                result: None,
18153                pid: Some(std::process::id()),
18154                created_at: 0,
18155                finished_at: None,
18156            };
18157            std::fs::write(
18158                directory.join("job.json"),
18159                serde_json::to_vec(&job).unwrap(),
18160            )
18161            .unwrap();
18162            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
18163        };
18164        let _own = reserve("abcdef");
18165        let other = reserve("fedcba");
18166        assert!(
18167            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18168                .await
18169                .is_err()
18170        );
18171        assert!(
18172            RunState::load(&runner.state.id)
18173                .unwrap()
18174                .base_sync_recovery
18175                .authorizations
18176                .is_empty()
18177        );
18178        drop(other);
18179        assert!(crate::daemon::is_working_on(
18180            &home,
18181            &runner.state.id,
18182            Timestamp::now()
18183        ));
18184        assert!(
18185            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
18186        );
18187        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18188            .await
18189            .unwrap();
18190        assert!(
18191            RunState::load(&runner.state.id)
18192                .unwrap()
18193                .base_recovery_pending()
18194        );
18195    }
18196
18197    #[cfg(unix)]
18198    #[tokio::test]
18199    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
18200        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18201        let home = crate::run::home();
18202        runner.state.driver_pid = Some(std::process::id());
18203        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
18204        runner.state.driver_exited = false;
18205        runner.state.begin_pass();
18206        runner.state.save().unwrap();
18207        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
18208        driver.record(&runner.state).unwrap();
18209        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
18210        // Preserve the durable claim as if the process died before Drop saved.
18211        drop(driver);
18212        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
18213        assert_eq!(
18214            runner.state.liveness_under(&home, false),
18215            crate::run::Liveness::Dead
18216        );
18217        let queue = crate::queue::Queue::open();
18218        let _claim = queue.claim(&task).unwrap();
18219        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18220            .await
18221            .unwrap();
18222        let disk = RunState::load(&runner.state.id).unwrap();
18223        assert!(!disk.driver_exited);
18224        assert!(disk.base_recovery_pending());
18225    }
18226
18227    #[cfg(unix)]
18228    #[tokio::test]
18229    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18230        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18231        if std::env::var_os(CHILD).is_none() {
18232            use std::os::unix::fs::PermissionsExt;
18233            let tmp = tempfile::tempdir().unwrap();
18234            let gh = tmp.path().join("gh");
18235            std::fs::write(&gh, r#"#!/bin/sh
18236case "$1 $2" in
18237  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18238  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18239  *) exit 2 ;;
18240esac
18241"#).unwrap();
18242            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18243            let mut paths = vec![tmp.path().to_path_buf()];
18244            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18245            let output = std::process::Command::new(std::env::current_exe().unwrap())
18246                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18247                .env(CHILD, "1")
18248                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18249                .env("PATH", std::env::join_paths(paths).unwrap())
18250                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18251                .output().unwrap();
18252            assert!(
18253                output.status.success()
18254                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18255                "{}\n{}",
18256                String::from_utf8_lossy(&output.stdout),
18257                String::from_utf8_lossy(&output.stderr)
18258            );
18259            return;
18260        }
18261        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18262        let repo = runner.state.repo.clone();
18263        git::git(&repo, &["checkout", "main"]).await.unwrap();
18264        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18265        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18266        git::git(&repo, &["checkout", "fix/retained"])
18267            .await
18268            .unwrap();
18269        runner.state.pr = Some(crate::run::PrRecord {
18270            url: "https://example.test/project/pull/1".into(),
18271            number: 1,
18272            state: "open".into(),
18273            checks: "unknown".into(),
18274            round: 0,
18275            rounds: 1,
18276            red_at_merge: Vec::new(),
18277        });
18278        runner.sync_to_base().await.unwrap();
18279        assert_eq!(runner.state.status, RunStatus::Blocked);
18280        assert_eq!(
18281            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18282            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18283        );
18284        assert!(runner.state.base_sync_closure_pending());
18285        assert!(crate::handover::can_resume(&runner.state));
18286        let queue = crate::queue::Queue::open();
18287        assert!(!crate::base_sync_recovery::held_task(
18288            &queue,
18289            &queue.get(&task).unwrap()
18290        ));
18291        assert!(runner.state.authorize_base_sync(&task).is_err());
18292        // Legacy closure stops have no typed stop but must retain the checkpoint.
18293        runner.state.base_sync_recovery.stop = None;
18294        runner.state.status = RunStatus::Voting;
18295        runner.state.gate_ran = true;
18296        runner.state.config.graph.review_rounds = 0;
18297        runner.state.save().unwrap();
18298        assert!(crate::handover::can_resume(&runner.state));
18299        runner.state = RunState::load(&runner.state.id).unwrap();
18300        runner.execute_graph().await.unwrap();
18301        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18302        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18303        assert_eq!(
18304            runner.state.base_sync.as_ref().unwrap().attempts,
18305            BASE_SYNC_ROUNDS
18306        );
18307        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18308        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18309        assert!(runner.state.reviews.is_empty());
18310        assert!(runner.state.gate.is_empty());
18311    }
18312
18313    #[cfg(unix)]
18314    #[tokio::test]
18315    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18316        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18317        runner.state.driver_exited = true;
18318        runner.state.save().unwrap();
18319        let home = crate::run::home();
18320        let queue = crate::queue::Queue::open();
18321        let _claim = queue.claim(&task).unwrap();
18322        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18323        assert!(
18324            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18325                .await
18326                .is_err()
18327        );
18328        drop(lease);
18329        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18330        assert!(
18331            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18332                .await
18333                .is_err()
18334        );
18335        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18336        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18337            .await
18338            .unwrap();
18339        let disk = RunState::load(&runner.state.id).unwrap();
18340        assert!(disk.base_recovery_pending());
18341        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18342        assert!(
18343            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18344                .await
18345                .is_err()
18346        );
18347        assert_eq!(
18348            RunState::load(&runner.state.id)
18349                .unwrap()
18350                .base_sync_recovery
18351                .authorizations
18352                .len(),
18353            1
18354        );
18355        let mut owner = queue.get(&task).unwrap();
18356        owner.runs.push("20260101-000000-ffff".into());
18357        queue.put(&mut owner).unwrap();
18358        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18359            .await
18360            .unwrap_err();
18361        assert!(error.to_string().contains("run task ownership changed"));
18362    }
18363
18364    #[cfg(unix)]
18365    #[tokio::test]
18366    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18367        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18368        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18369        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18370        legacy["status"] = serde_json::json!("voting");
18371        runner.state = serde_json::from_value(legacy).unwrap();
18372        runner.state.save().unwrap();
18373        for _ in 0..3 {
18374            runner.execute_graph().await.unwrap();
18375            assert_eq!(runner.state.status, RunStatus::Blocked);
18376            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18377            assert!(!crate::handover::can_resume(&runner.state));
18378            assert_eq!(
18379                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18380                head
18381            );
18382            assert!(runner.state.reviews.is_empty());
18383            assert!(!runner.state.gate_ran);
18384        }
18385        let notice = crate::notices::run_ended(&runner.state).unwrap();
18386        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18387        runner.state.begin_pass();
18388        runner.state.status = RunStatus::Voting;
18389        runner.deliberate().await.unwrap();
18390        runner.vote().await.unwrap();
18391        runner.finish_after_tally().await.unwrap();
18392        assert_eq!(runner.state.status, RunStatus::Blocked);
18393        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18394        assert_eq!(
18395            crate::notices::run_ended(&runner.state).unwrap().since,
18396            notice.since
18397        );
18398    }
18399
18400    #[cfg(unix)]
18401    #[tokio::test]
18402    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18403        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18404        for detail in [
18405            "fix/retained conflicts with origin/main and did not rebase: conflict",
18406            "rebased fix/retained locally but origin refused the push",
18407            "unknown failure",
18408        ] {
18409            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18410            runner.state.record_base_sync_stop(&head);
18411            assert!(runner.state.authorize_base_sync(&task).is_err());
18412            runner.state.status = RunStatus::Voting;
18413            runner.execute_graph().await.unwrap();
18414            assert_eq!(runner.state.status, RunStatus::Blocked);
18415            assert!(!crate::handover::can_resume(&runner.state));
18416            assert_eq!(
18417                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18418                head
18419            );
18420        }
18421    }
18422
18423    #[cfg(unix)]
18424    #[tokio::test]
18425    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18426        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18427        runner.state.authorize_base_sync(&task).unwrap();
18428        assert!(runner.state.consume_base_recovery(&head));
18429        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18430        runner.state.reserve_base_operation(&head, &tip);
18431        runner.state.save().unwrap();
18432        runner.state = RunState::load(&runner.state.id).unwrap();
18433        assert!(!runner.state.consume_base_recovery(&head));
18434        runner.sync_to_base().await.unwrap();
18435        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18436        assert_eq!(runner.state.base_episode_used(), 1);
18437        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18438        assert!(
18439            runner
18440                .state
18441                .base_sync_recovery
18442                .operations
18443                .last()
18444                .unwrap()
18445                .finished
18446        );
18447        assert!(!runner.state.base_sync_blocked());
18448        runner.sync_to_base().await.unwrap();
18449        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18450    }
18451
18452    #[cfg(unix)]
18453    #[tokio::test]
18454    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18455        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18456        // Both historical diagnostic spellings retain an exhaustion identity.
18457        let original = runner
18458            .state
18459            .base_sync
18460            .as_ref()
18461            .unwrap()
18462            .conflict
18463            .clone()
18464            .unwrap();
18465        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18466            original
18467                .replace("synchronization(s)", "rebase(s)")
18468                .replace("synchronizing", "rebasing"),
18469        );
18470        runner.state.base_sync_recovery = Default::default();
18471        runner.state.record_base_sync_stop(&head);
18472        assert_eq!(
18473            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18474            crate::base_sync_recovery::StopKind::Exhausted
18475        );
18476        runner.state.authorize_base_sync(&task).unwrap();
18477        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18478        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18479            .as_object_mut()
18480            .unwrap();
18481        auth.remove("interval");
18482        auth.remove("scope");
18483        runner.state = serde_json::from_value(legacy).unwrap();
18484        assert!(runner.state.consume_base_recovery(&head));
18485        assert_eq!(runner.state.base_episode_used(), 3);
18486        runner.sync_to_base().await.unwrap();
18487        assert_eq!(runner.state.base_episode_used(), 4);
18488        runner.state.resource_block = Some(crate::run::ResourceBlock {
18489            node: "gate".into(),
18490            kind: "cache".into(),
18491            detail: "legacy wait".into(),
18492            at: Timestamp::now(),
18493            cause: crate::run::ResourceBlockCause::Unrecorded,
18494        });
18495        runner.state.save().unwrap();
18496        assert!(
18497            runner
18498                .state
18499                .base_sync_recovery
18500                .episodes
18501                .last()
18502                .unwrap()
18503                .boundary
18504                .is_none()
18505        );
18506        runner.state.resource_block = None;
18507        advance_base_fixture(&runner).await;
18508        runner.sync_to_base().await.unwrap();
18509        assert!(runner.state.base_sync_blocked());
18510        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18511    }
18512
18513    #[cfg(unix)]
18514    async fn advance_base_fixture(runner: &Runner) {
18515        let repo = &runner.state.repo;
18516        for args in [
18517            vec!["checkout", "main"],
18518            vec!["commit", "--allow-empty", "-m", "base advanced"],
18519            vec!["push", "origin", "main"],
18520            vec!["checkout", "fix/retained"],
18521        ] {
18522            git::git(repo, &args).await.unwrap();
18523        }
18524    }
18525
18526    #[cfg(unix)]
18527    fn fresh_base_interval_fixture(runner: &mut Runner) {
18528        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18529        runner.state.base_sync.as_mut().unwrap().conflict = None;
18530        runner.state.base_sync_recovery = Default::default();
18531        runner.state.status = RunStatus::Voting;
18532    }
18533
18534    #[cfg(unix)]
18535    #[tokio::test]
18536    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18537        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18538        fresh_base_interval_fixture(&mut runner);
18539        runner.state.begin_pass();
18540        runner.sync_to_base().await.unwrap();
18541        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18542        runner.state.resource_block = Some(crate::run::ResourceBlock {
18543            node: "gate".into(),
18544            kind: "build cache".into(),
18545            detail: "busy".into(),
18546            at: Timestamp::now(),
18547            cause: crate::run::ResourceBlockCause::Timeout {
18548                waited_secs: 1,
18549                limit_secs: 1,
18550            },
18551        });
18552        runner.state.save().unwrap();
18553        let queue = crate::queue::Queue::open();
18554        let mut owner = queue.get(&task).unwrap();
18555        runner.state.task_instruction = Some(owner.instruction.clone());
18556        owner.release_operator("fixture-owner", None);
18557        queue.put(&mut owner).unwrap();
18558        let approval = owner.resumption.clone().unwrap();
18559        runner.state.resource_block = None;
18560        runner.state.save().unwrap();
18561        runner.state = RunState::load(&runner.state.id).unwrap();
18562        advance_base_fixture(&runner).await;
18563        runner.sync_to_base().await.unwrap();
18564        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18565        assert_eq!(runner.state.base_episode_used(), 1);
18566        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18567        assert!(
18568            runner.state.base_sync_recovery.episodes[0]
18569                .boundary
18570                .as_ref()
18571                .unwrap()
18572                .consumed
18573        );
18574        assert!(
18575            !runner
18576                .state
18577                .renew_base_episode(&task, &approval, &head, "base")
18578        );
18579        for _ in 0..3 {
18580            owner.release_operator("fixture-owner", None);
18581            queue.put(&mut owner).unwrap();
18582            runner.state = RunState::load(&runner.state.id).unwrap();
18583            runner.state.begin_pass();
18584            runner.sync_to_base().await.unwrap();
18585            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18586            assert_eq!(runner.state.base_episode_used(), 1);
18587        }
18588        runner.state.resource_block = Some(crate::run::ResourceBlock {
18589            node: "gate".into(),
18590            kind: "disk pressure".into(),
18591            detail: "free space required".into(),
18592            at: Timestamp::now(),
18593            cause: crate::run::ResourceBlockCause::Other,
18594        });
18595        runner.state.end_pass_parked(ParkCause::Interrupt {
18596            reason: "disk pressure".into(),
18597        });
18598        runner.state.save().unwrap();
18599        owner.release_operator("fixture-owner-after-disk", None);
18600        queue.put(&mut owner).unwrap();
18601        runner.state.resource_block = None;
18602        advance_base_fixture(&runner).await;
18603        runner.sync_to_base().await.unwrap();
18604        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18605        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18606        assert_eq!(runner.state.base_episode_used(), 1);
18607        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18608    }
18609
18610    #[cfg(unix)]
18611    #[tokio::test]
18612    async fn base_recovery_continuous_advancement_stops_at_four() {
18613        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18614        fresh_base_interval_fixture(&mut runner);
18615        for spent in 1..=BASE_SYNC_ROUNDS {
18616            runner.sync_to_base().await.unwrap();
18617            assert!(!runner.state.base_sync_blocked());
18618            assert_eq!(runner.state.base_episode_used(), spent);
18619            advance_base_fixture(&runner).await;
18620        }
18621        runner.sync_to_base().await.unwrap();
18622        assert_eq!(
18623            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18624            crate::base_sync_recovery::StopKind::Exhausted
18625        );
18626        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18627        assert!(stop.unverified_sync);
18628        let action = runner.state.base_sync_next_action();
18629        assert!(action.contains("never reached its gate"));
18630        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18631        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18632        runner.state = RunState::load(&runner.state.id).unwrap();
18633        runner.sync_to_base().await.unwrap();
18634        assert_eq!(runner.state.base_episode_used(), 4);
18635        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18636    }
18637
18638    #[cfg(unix)]
18639    #[tokio::test]
18640    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18641        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18642        runner.state.ensure_base_episode();
18643        // Verification progress alone is not evidence of a successful sync.
18644        runner.state.record_base_progress(&head);
18645        runner.state.base_sync_recovery.stop = None;
18646        runner.state.record_base_sync_stop(&head);
18647        assert!(
18648            !runner
18649                .state
18650                .base_sync_recovery
18651                .stop
18652                .as_ref()
18653                .unwrap()
18654                .unverified_sync
18655        );
18656
18657        runner.state.finish_base_operation(Some(&head));
18658        // A gate for another head cannot verify this synchronization.
18659        runner.state.gate_ran = true;
18660        runner.state.gate_head = Some("older-head".into());
18661        runner.state.base_sync_recovery.stop = None;
18662        runner.state.record_base_sync_stop(&head);
18663        runner.state.save().unwrap();
18664        runner.state = RunState::load(&runner.state.id).unwrap();
18665        assert!(
18666            runner
18667                .state
18668                .base_sync_recovery
18669                .stop
18670                .as_ref()
18671                .unwrap()
18672                .unverified_sync
18673        );
18674
18675        runner.state.gate_head = Some(head.clone());
18676        runner.state.base_sync_recovery.stop = None;
18677        runner.state.record_base_sync_stop(&head);
18678        assert!(
18679            !runner
18680                .state
18681                .base_sync_recovery
18682                .stop
18683                .as_ref()
18684                .unwrap()
18685                .unverified_sync
18686        );
18687        assert!(
18688            !runner
18689                .state
18690                .base_sync_next_action()
18691                .contains("never reached its gate")
18692        );
18693
18694        // Historical records cannot establish the missing synchronization evidence.
18695        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18696        legacy["base_sync_recovery"]["stop"]
18697            .as_object_mut()
18698            .unwrap()
18699            .remove("unverified_sync");
18700        legacy["base_sync_recovery"]["episodes"][0]
18701            .as_object_mut()
18702            .unwrap()
18703            .remove("last_sync_head");
18704        runner.state = serde_json::from_value(legacy).unwrap();
18705        assert!(
18706            !runner
18707                .state
18708                .base_sync_recovery
18709                .stop
18710                .as_ref()
18711                .unwrap()
18712                .unverified_sync
18713        );
18714        assert!(
18715            runner.state.base_sync_recovery.episodes[0]
18716                .last_sync_head
18717                .is_none()
18718        );
18719    }
18720
18721    #[cfg(unix)]
18722    #[tokio::test]
18723    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18724        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18725        runner.state.authorize_base_sync(&task).unwrap();
18726        assert!(
18727            runner
18728                .state
18729                .base_sync_next_action()
18730                .contains("Approval recorded")
18731        );
18732        assert!(
18733            runner
18734                .state
18735                .base_sync_next_action()
18736                .contains("4/4 in episode 0, 4 lifetime")
18737        );
18738        assert!(runner.state.consume_base_recovery(&head));
18739        assert!(
18740            runner
18741                .state
18742                .base_sync_next_action()
18743                .contains("0/4 in episode 1, 4 lifetime")
18744        );
18745    }
18746
18747    #[cfg(unix)]
18748    #[tokio::test]
18749    async fn base_recovery_changed_head_invalidates_without_spending() {
18750        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18751        runner.state.authorize_base_sync(&task).unwrap();
18752        git::git(
18753            &runner.state.repo,
18754            &["commit", "--allow-empty", "-m", "external head change"],
18755        )
18756        .await
18757        .unwrap();
18758        runner.sync_to_base().await.unwrap();
18759        let a = runner
18760            .state
18761            .base_sync_recovery
18762            .authorizations
18763            .last()
18764            .unwrap();
18765        assert!(a.consumed);
18766        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18767        runner.state = RunState::load(&runner.state.id).unwrap();
18768        assert!(
18769            runner
18770                .state
18771                .base_sync_next_action()
18772                .contains("Approval invalidated")
18773        );
18774        assert!(!runner.state.base_recovery_pending());
18775        assert!(runner.state.base_sync_blocked());
18776        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18777    }
18778
18779    #[cfg(unix)]
18780    #[tokio::test]
18781    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18782        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18783        runner.state.driver_exited = true;
18784        runner.state.save().unwrap();
18785        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18786            .await
18787            .unwrap();
18788        runner.state = RunState::load(&runner.state.id).unwrap();
18789        advance_base_fixture(&runner).await;
18790        runner.sync_to_base().await.unwrap();
18791        let a = runner
18792            .state
18793            .base_sync_recovery
18794            .authorizations
18795            .last()
18796            .unwrap();
18797        assert!(
18798            a.consumed
18799                && a.invalidated
18800                    .as_deref()
18801                    .unwrap()
18802                    .contains("fetched base changed")
18803        );
18804        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18805        assert_eq!(
18806            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18807            head
18808        );
18809        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18810            .await
18811            .unwrap();
18812        runner.state = RunState::load(&runner.state.id).unwrap();
18813        runner.sync_to_base().await.unwrap();
18814        assert!(!runner.state.base_sync_blocked());
18815        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18816    }
18817
18818    #[cfg(unix)]
18819    #[tokio::test]
18820    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18821        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18822        runner.state.authorize_base_sync(&task).unwrap();
18823        assert!(runner.state.consume_base_recovery(&head));
18824        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18825        runner.state.reserve_base_operation(&head, &tip);
18826        runner.state.save().unwrap();
18827        let scratch = runner.state.dir().join("base-sync");
18828        assert_eq!(
18829            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18830                .await
18831                .unwrap(),
18832            crate::rebase::Rebased::Applied
18833        );
18834        runner.state = RunState::load(&runner.state.id).unwrap();
18835        runner.sync_to_base().await.unwrap();
18836        assert!(
18837            runner
18838                .state
18839                .base_sync_recovery
18840                .operations
18841                .last()
18842                .unwrap()
18843                .finished
18844        );
18845        assert_eq!(runner.state.base_episode_used(), 1);
18846        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18847        assert!(!runner.state.base_sync_blocked());
18848    }
18849
18850    #[cfg(unix)]
18851    #[tokio::test]
18852    async fn base_recovery_crash_preserves_untracked_files() {
18853        for ignored in [false, true] {
18854            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18855            runner.state.authorize_base_sync(&task).unwrap();
18856            assert!(runner.state.consume_base_recovery(&head));
18857            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18858            runner.state.reserve_base_operation(&head, &tip);
18859            runner.state.save().unwrap();
18860            let scratch = runner.state.dir().join("base-sync");
18861            assert_eq!(
18862                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18863                    .await
18864                    .unwrap(),
18865                crate::rebase::Rebased::Applied
18866            );
18867            let repo = &runner.state.repo;
18868            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18869            assert_ne!(result, head);
18870            if ignored {
18871                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18872                    .await
18873                    .unwrap();
18874                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18875            }
18876            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18877            assert!(
18878                git::git_raw(repo, &["diff", "--quiet", &head])
18879                    .await
18880                    .unwrap()
18881                    .ok()
18882            );
18883            // Resume after the branch moved, before its checkout was reset.
18884            runner.state = RunState::load(&runner.state.id).unwrap();
18885            runner.sync_to_base().await.unwrap();
18886            assert!(runner.state.base_sync_blocked());
18887            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18888            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18889            assert_eq!(
18890                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18891                result
18892            );
18893            assert_eq!(
18894                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18895                "retained work\n"
18896            );
18897            assert!(
18898                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18899                    .await
18900                    .unwrap()
18901                    .ok()
18902            );
18903        }
18904    }
18905
18906    #[cfg(unix)]
18907    #[tokio::test]
18908    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18909        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18910        runner.state.authorize_base_sync(&task).unwrap();
18911        assert!(runner.state.consume_base_recovery(&head));
18912        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18913        runner.state.reserve_base_operation(&head, &tip);
18914        runner.state.save().unwrap();
18915        let scratch = runner.state.dir().join("base-sync");
18916        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18917            .await
18918            .unwrap();
18919        git::sync_to_head(&runner.state.repo).await.unwrap();
18920        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18921        git::git(&runner.state.repo, &["add", "foreign"])
18922            .await
18923            .unwrap();
18924        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18925            .await
18926            .unwrap();
18927        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18928        runner.state = RunState::load(&runner.state.id).unwrap();
18929        runner.sync_to_base().await.unwrap();
18930        assert!(runner.state.base_sync_blocked());
18931        assert!(
18932            !runner
18933                .state
18934                .base_sync_recovery
18935                .operations
18936                .last()
18937                .unwrap()
18938                .finished
18939        );
18940        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18941        assert_eq!(
18942            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18943            foreign_head
18944        );
18945    }
18946
18947    #[cfg(unix)]
18948    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18949    {
18950        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18951        fresh_base_interval_fixture(&mut runner);
18952        let repo = &runner.state.repo;
18953        git::git(repo, &["checkout", "main"]).await.unwrap();
18954        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18955        git::git(repo, &["add", "retained"]).await.unwrap();
18956        git::git(repo, &["commit", "-m", "upstream retained change"])
18957            .await
18958            .unwrap();
18959        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18960        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18961        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18962        let scratch = runner.state.dir().join("base-sync");
18963        assert!(matches!(
18964            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18965                .await
18966                .unwrap(),
18967            git::RebaseStart::Conflicted(_)
18968        ));
18969        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18970            unstarted: false,
18971            agent: "fixture".into(),
18972            paths: vec!["retained".into()],
18973            from: Some(head.clone()),
18974            onto: None,
18975            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18976            index_outside: None,
18977            finished: false,
18978            error: None,
18979            launcher: None,
18980            infra: None,
18981            outage: None,
18982        });
18983        (tmp, runner, head, tip, scratch)
18984    }
18985
18986    #[cfg(unix)]
18987    #[tokio::test]
18988    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18989        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18990        // A resource stop from before reservations existed, with resolved
18991        // contents left for the launcher's ordinary staging continuation.
18992        std::fs::write(
18993            scratch.join("retained"),
18994            "upstream and retained resolution\n",
18995        )
18996        .unwrap();
18997        runner.state.resource_block = Some(crate::run::ResourceBlock {
18998            node: "rebase".into(),
18999            kind: "repository coordination".into(),
19000            detail: "busy".into(),
19001            at: Timestamp::now(),
19002            cause: crate::run::ResourceBlockCause::Other,
19003        });
19004        runner.state.save().unwrap();
19005        // Advance the remote without moving either checkout participating
19006        // in the standing rebase.
19007        let newer = git::git(
19008            &runner.state.repo,
19009            &[
19010                "commit-tree",
19011                "main^{tree}",
19012                "-p",
19013                "main",
19014                "-m",
19015                "base advanced during wait",
19016            ],
19017        )
19018        .await
19019        .unwrap();
19020        git::git(
19021            &runner.state.repo,
19022            &[
19023                "push",
19024                "origin",
19025                &format!("{}:refs/heads/main", newer.trim()),
19026            ],
19027        )
19028        .await
19029        .unwrap();
19030        runner.state = RunState::load(&runner.state.id).unwrap();
19031        runner.state.resource_block = None;
19032        runner.sync_to_base().await.unwrap();
19033        assert!(!runner.state.base_sync_blocked());
19034        let op = &runner.state.base_sync_recovery.operations[0];
19035        assert_eq!(op.head, head);
19036        assert_eq!(op.tip, tip);
19037        assert!(op.finished);
19038        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19039        assert_eq!(runner.state.rebase_fixes.len(), 1);
19040        let latest = git::rev_parse(&runner.state.repo, "origin/main")
19041            .await
19042            .unwrap();
19043        assert_ne!(latest, tip);
19044        runner.state = RunState::load(&runner.state.id).unwrap();
19045        runner.sync_to_base().await.unwrap();
19046        assert!(!runner.state.base_sync_blocked());
19047        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
19048        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
19049        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19050    }
19051
19052    #[cfg(unix)]
19053    #[tokio::test]
19054    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
19055        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19056        runner.state.reserve_base_operation(&head, &tip);
19057        runner.state.save().unwrap();
19058        std::fs::write(
19059            scratch.join("retained"),
19060            "upstream and retained resolution\n",
19061        )
19062        .unwrap();
19063        git::git(&scratch, &["add", "retained"]).await.unwrap();
19064        git::git(
19065            &scratch,
19066            &["-c", "core.editor=true", "rebase", "--continue"],
19067        )
19068        .await
19069        .unwrap();
19070        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19071        assert!(
19072            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19073                .await
19074                .unwrap()
19075                .is_empty()
19076        );
19077        assert_eq!(
19078            crate::rebase::finish(
19079                &mut runner.state,
19080                &scratch,
19081                "fix/retained",
19082                &head,
19083                &tip,
19084                &["retained".into()],
19085                ""
19086            )
19087            .await
19088            .unwrap(),
19089            crate::rebase::Rebased::Applied
19090        );
19091        assert!(!scratch.exists());
19092        // Simulate losing the caller before finish_base_operation/save.
19093        runner.state = RunState::load(&runner.state.id).unwrap();
19094        let op = &runner.state.base_sync_recovery.operations[0];
19095        assert!(!op.finished);
19096        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
19097        runner.sync_to_base().await.unwrap();
19098        assert!(!runner.state.base_sync_blocked());
19099        assert!(runner.state.base_sync_recovery.operations[0].finished);
19100        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19101        assert_eq!(runner.state.rebase_fixes.len(), 1);
19102        let winner = runner.state.winner().unwrap().clone();
19103        let wait = runner.repository_wait();
19104        assert!(
19105            verify_current_head(&mut runner.state, &winner, &wait)
19106                .await
19107                .unwrap()
19108        );
19109        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19110    }
19111
19112    #[cfg(unix)]
19113    #[tokio::test]
19114    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
19115        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
19116            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19117            runner.state.reserve_base_operation(&head, &tip);
19118            runner.state.save().unwrap();
19119            std::fs::write(
19120                scratch.join("retained"),
19121                "upstream and retained resolution\n",
19122            )
19123            .unwrap();
19124            git::git(&scratch, &["add", "retained"]).await.unwrap();
19125            git::git(
19126                &scratch,
19127                &["-c", "core.editor=true", "rebase", "--continue"],
19128            )
19129            .await
19130            .unwrap();
19131            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19132            assert!(!git::rebase_in_progress(&scratch).await);
19133            assert!(
19134                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19135                    .await
19136                    .unwrap()
19137                    .is_empty()
19138            );
19139            match damage {
19140                Some("record") => {
19141                    let path =
19142                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
19143                            .await
19144                            .unwrap();
19145                    std::fs::write(scratch.join(path), "").unwrap();
19146                }
19147                Some("foreign") => {
19148                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
19149                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
19150                    git::git(&scratch, &["commit", "-m", "foreign work"])
19151                        .await
19152                        .unwrap();
19153                }
19154                Some("dirty") => {
19155                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
19156                }
19157                _ => {}
19158            }
19159            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19160            // Crash immediately after Git continuation, before finish runs.
19161            runner.state = RunState::load(&runner.state.id).unwrap();
19162            assert!(
19163                runner.state.base_sync_recovery.operations[0]
19164                    .validated_head
19165                    .is_none()
19166            );
19167            runner.sync_to_base().await.unwrap();
19168            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19169            assert_eq!(runner.state.base_episode_used(), 1);
19170            assert_eq!(runner.state.rebase_fixes.len(), 1);
19171            assert_eq!(
19172                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19173                retained_head
19174            );
19175            if damage.is_some() {
19176                assert!(runner.state.base_sync_blocked());
19177                assert!(scratch.exists());
19178                assert!(!runner.state.base_sync_recovery.operations[0].finished);
19179                assert!(
19180                    runner.state.base_sync_recovery.operations[0]
19181                        .validated_head
19182                        .is_none()
19183                );
19184            } else {
19185                assert!(!runner.state.base_sync_blocked());
19186                assert!(!scratch.exists());
19187                assert!(runner.state.base_sync_recovery.operations[0].finished);
19188                assert_eq!(
19189                    runner.state.base_sync_recovery.operations[0]
19190                        .validated_head
19191                        .as_deref(),
19192                    Some(result.as_str())
19193                );
19194                let winner = runner.state.winner().unwrap().clone();
19195                let wait = runner.repository_wait();
19196                assert!(
19197                    verify_current_head(&mut runner.state, &winner, &wait)
19198                        .await
19199                        .unwrap()
19200                );
19201                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19202                runner.state = RunState::load(&runner.state.id).unwrap();
19203                runner.sync_to_base().await.unwrap();
19204                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19205            }
19206        }
19207    }
19208
19209    #[cfg(unix)]
19210    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
19211        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19212        // This is an ordinary gate stop, not an authorized base-budget recovery.
19213        runner.state.prep_complete = Some(true);
19214        runner.state.base_sync = None;
19215        runner.state.base_sync_recovery = Default::default();
19216        runner.state.config.graph.gate_fix_rounds = 1;
19217        let mut review = review_round(true, 0, 1, 1, false, true);
19218        review.head = head.clone();
19219        review.verified_head = Some(head.clone());
19220        runner.state.reviews = vec![review];
19221        runner.state.gate = vec![CommandOutcome {
19222            command: "old gate".into(),
19223            code: Some(1),
19224            output_tail: "old failure".into(),
19225            duration_ms: 0,
19226            resource_blocked: false,
19227            ..Default::default()
19228        }];
19229        runner.state.gate_head = Some(head.clone());
19230        runner.state.gate_ran = true;
19231        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
19232            agent: "fixture".into(),
19233            failed: runner.state.gate.clone(),
19234            notes: "spent".into(),
19235            committed: false,
19236            error: None,
19237        }];
19238        runner.state.land_approval = Some(crate::run::LandApproval {
19239            question: "old approval".into(),
19240            head: head.clone(),
19241        });
19242        runner.state.status = RunStatus::Blocked;
19243        (tmp, runner, head)
19244    }
19245
19246    #[cfg(unix)]
19247    #[tokio::test]
19248    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
19249        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
19250        runner.sync_to_base().await.unwrap();
19251        let winner = runner.state.winner().unwrap().clone();
19252        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
19253        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
19254        assert_ne!(head, base);
19255        runner.state.config.verify.e2e = vec![format!(
19256            "git update-ref refs/remotes/origin/main {head} && false"
19257        )];
19258        let wait = repository_wait(&runner.state, None);
19259        assert!(
19260            !verify_current_head(&mut runner.state, &winner, &wait)
19261                .await
19262                .unwrap()
19263        );
19264        assert_eq!(
19265            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
19266                .await
19267                .unwrap(),
19268            head
19269        );
19270        assert_eq!(
19271            runner
19272                .state
19273                .head_e2e
19274                .as_ref()
19275                .unwrap()
19276                .base_commit
19277                .as_deref(),
19278            Some(base.as_str())
19279        );
19280    }
19281
19282    #[cfg(unix)]
19283    #[tokio::test]
19284    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19285        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19286            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19287            let phases = tmp.path().join("phases");
19288            runner.state.config.verify.e2e = vec![format!(
19289                "echo e2e >> '{}'; {}",
19290                phases.display(),
19291                if e2e_ok {
19292                    "true"
19293                } else {
19294                    "echo new-e2e-failure; false"
19295                }
19296            )];
19297            runner.state.config.verify.gate = vec![format!(
19298                "echo gate >> '{}'; {}",
19299                phases.display(),
19300                if gate_ok {
19301                    "true"
19302                } else {
19303                    "echo new-gate-failure; false"
19304                }
19305            )];
19306            runner.state.save().unwrap();
19307            runner.state = RunState::load(&runner.state.id).unwrap();
19308            runner.sync_to_base().await.unwrap();
19309            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19310            assert_ne!(head, old);
19311            // Reentry after Git updated but before verification was invalidated.
19312            runner.state = RunState::load(&runner.state.id).unwrap();
19313            runner.execute_graph().await.unwrap();
19314            assert_eq!(runner.state.gate_fixes.len(), 1);
19315            assert_eq!(runner.state.reviews.len(), 1);
19316            assert_eq!(runner.state.reviews[0].head, old);
19317            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19318            assert_eq!(runner.state.verification_history.len(), 1);
19319            let history = &runner.state.verification_history[0];
19320            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19321            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19322            assert!(history.archived_at.is_some());
19323            assert_eq!(history.fixes_spent, Some(1));
19324            assert_eq!(history.gate[0].output_tail, "old failure");
19325            let archive_events: Vec<_> = runner
19326                .state
19327                .events
19328                .iter()
19329                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19330                .collect();
19331            assert_eq!(archive_events.len(), 1);
19332            assert!(archive_events[0].message.contains(&short(&old)));
19333            assert!(archive_events[0].message.contains(&short(&head)));
19334            assert!(
19335                archive_events[0]
19336                    .message
19337                    .contains("1 gate-fix round(s) already spent stay spent")
19338            );
19339            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19340            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19341            if e2e_ok {
19342                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19343                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19344            } else {
19345                assert!(!runner.state.gate_ran);
19346            }
19347            assert_eq!(
19348                runner.state.status,
19349                if e2e_ok && gate_ok {
19350                    RunStatus::Ready
19351                } else {
19352                    RunStatus::Blocked
19353                }
19354            );
19355            if !e2e_ok || !gate_ok {
19356                let cause = runner.state.verification_blocking_cause().unwrap();
19357                assert!(cause.contains(&head));
19358                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19359                // A later successful progress event must not become the cause.
19360                runner.state.event("land", "rebased successfully");
19361                let notice = crate::notices::run_ended(&runner.state).unwrap();
19362                assert!(!format!("{notice:?}").contains("rebased successfully"));
19363                assert!(runner.state.merge.is_none());
19364            }
19365            let before = std::fs::read_to_string(&phases).unwrap();
19366            runner.state.save().unwrap();
19367            runner.state = RunState::load(&runner.state.id).unwrap();
19368            runner.review_loop().await.unwrap();
19369            runner.gate().await.unwrap();
19370            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19371            assert_eq!(runner.state.verification_history.len(), 1);
19372            let history = &runner.state.verification_history[0];
19373            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19374            assert!(history.archived_at.is_some());
19375            assert_eq!(history.fixes_spent, Some(1));
19376        }
19377    }
19378
19379    #[cfg(unix)]
19380    #[tokio::test]
19381    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19382        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19383        let marker = tmp.path().join("gate-ran");
19384        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19385        runner.review_loop().await.unwrap();
19386        runner.gate().await.unwrap();
19387        assert_eq!(runner.state.status, RunStatus::Blocked);
19388        assert!(!marker.exists());
19389        assert!(runner.state.verification_history.is_empty());
19390        runner.state.gate_head = None;
19391        runner.gate().await.unwrap();
19392        assert!(marker.exists());
19393        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19394        assert_eq!(runner.state.verification_history.len(), 1);
19395        assert_eq!(runner.state.gate_fixes.len(), 1);
19396    }
19397
19398    #[cfg(unix)]
19399    #[tokio::test]
19400    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19401        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19402        runner.sync_to_base().await.unwrap();
19403        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19404        runner.state.reconcile_verification_head(&head);
19405        // Both crash-before-command and resource wait are unresolved evidence.
19406        for outcomes in [
19407            Vec::new(),
19408            vec![CommandOutcome {
19409                command: "true".into(),
19410                code: None,
19411                output_tail: "cache unavailable".into(),
19412                duration_ms: 0,
19413                resource_blocked: true,
19414                ..Default::default()
19415            }],
19416        ] {
19417            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19418                head.clone(),
19419                false,
19420                outcomes,
19421            ));
19422            runner.state.gate_ran = false;
19423            runner.state.gate.clear();
19424            runner.state.save().unwrap();
19425            runner.state = RunState::load(&runner.state.id).unwrap();
19426            runner.merge().await.unwrap();
19427            assert!(runner.state.merge.is_none());
19428            runner.review_loop().await.unwrap();
19429            runner.gate().await.unwrap();
19430            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19431            assert!(runner.state.gate_allows_progress());
19432            assert_eq!(runner.state.gate_fixes.len(), 1);
19433            assert!(runner.state.merge.is_none());
19434        }
19435        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19436        git::git(
19437            &runner.state.repo,
19438            &["commit", "--allow-empty", "-m", "external update"],
19439        )
19440        .await
19441        .unwrap();
19442        runner.merge().await.unwrap();
19443        assert!(runner.state.merge.is_none());
19444        assert_eq!(runner.state.status, RunStatus::Blocked);
19445    }
19446
19447    #[cfg(unix)]
19448    #[tokio::test]
19449    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19450        for waiting_on_gate in [false, true] {
19451            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19452            runner.sync_to_base().await.unwrap();
19453            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19454            runner.state.reconcile_verification_head(&head);
19455            if waiting_on_gate {
19456                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19457                    head.clone(),
19458                    true,
19459                    Vec::new(),
19460                ));
19461            }
19462            let cache = tmp.path().join("cache");
19463            runner.state.config.verify.e2e =
19464                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19465            runner.state.config.verify.gate = vec!["true".into()];
19466            runner.state.config.graph.timeout_resource_wait = 1;
19467            let owner =
19468                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19469            let guard =
19470                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19471                    crate::cache::AcquireOutcome::Acquired(g) => g,
19472                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19473                };
19474            runner.review_loop().await.unwrap();
19475            runner.gate().await.unwrap();
19476            assert!(!runner.state.gate_ran);
19477            assert_eq!(runner.state.gate_fixes.len(), 1);
19478            assert!(runner.state.resource_block.is_some());
19479            runner.merge().await.unwrap();
19480            assert!(runner.state.merge.is_none());
19481            drop(guard);
19482            runner.state = RunState::load(&runner.state.id).unwrap();
19483            // The driver clears the previous pass's resource stop on resume.
19484            runner.state.resource_block = None;
19485            runner.review_loop().await.unwrap();
19486            runner.gate().await.unwrap();
19487            assert!(runner.state.gate_allows_progress());
19488            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19489            assert_eq!(runner.state.gate_fixes.len(), 1);
19490        }
19491    }
19492
19493    #[cfg(unix)]
19494    #[tokio::test]
19495    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19496        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19497        runner.sync_to_base().await.unwrap();
19498        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19499        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19500        // Verification passes before pre_gate and fails on the mechanically changed head.
19501        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19502        runner.review_loop().await.unwrap();
19503        runner.gate().await.unwrap();
19504        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19505        assert_ne!(before, after);
19506        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19507        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19508        assert!(!runner.state.gate_allows_progress());
19509        runner.merge().await.unwrap();
19510        assert!(runner.state.merge.is_none());
19511        assert!(
19512            runner
19513                .state
19514                .verification_history
19515                .iter()
19516                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19517        );
19518
19519        // An incomplete review is still an independent hold on a changed head.
19520        runner.state.reviews[0].clean = false;
19521        runner.state.reviews[0].answered = 0;
19522        runner.state.config.verify.e2e = vec!["true".into()];
19523        runner.review_loop().await.unwrap();
19524        runner.gate().await.unwrap();
19525        runner.merge().await.unwrap();
19526        assert_eq!(runner.state.status, RunStatus::Blocked);
19527        assert!(runner.state.merge.is_none());
19528        assert!(
19529            runner
19530                .state
19531                .verification_blocking_cause()
19532                .unwrap()
19533                .contains("review blocked")
19534        );
19535    }
19536
19537    #[cfg(unix)]
19538    #[tokio::test]
19539    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19540        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19541        runner.state.gate_head = None;
19542        runner.state.config.verify.gate =
19543            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19544        runner.review_loop().await.unwrap();
19545        runner.gate().await.unwrap();
19546        assert_ne!(
19547            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19548            old
19549        );
19550        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19551        assert!(!runner.state.gate_allows_progress());
19552        assert_eq!(runner.state.status, RunStatus::Blocked);
19553        runner.merge().await.unwrap();
19554        assert!(runner.state.merge.is_none());
19555    }
19556
19557    #[cfg(unix)]
19558    #[tokio::test]
19559    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19560        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19561        let mut old_review = review_round(true, 0, 1, 1, false, true);
19562        old_review.head = head.clone();
19563        old_review.verified_head = Some(head.clone());
19564        runner.state.reviews = vec![old_review];
19565        runner.state.gate = vec![CommandOutcome {
19566            command: "old gate".into(),
19567            code: None,
19568            output_tail: "timed out after 2400s".into(),
19569            duration_ms: 2_400_000,
19570            resource_blocked: false,
19571            ..Default::default()
19572        }];
19573        runner.state.gate_ran = true;
19574        runner.state.gate_head = Some(head.clone());
19575        runner.state.land_approval = Some(crate::run::LandApproval {
19576            question: "old-head-approval".into(),
19577            head: head.clone(),
19578        });
19579        runner.state.authorize_base_sync(&task).unwrap();
19580        runner.sync_to_base().await.unwrap();
19581        assert!(!runner.state.base_sync_blocked());
19582        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19583        assert_ne!(head, fresh);
19584        assert_eq!(runner.state.reviews.len(), 1);
19585        assert!(!runner.state.gate_ran);
19586        let saved = &runner.state.base_sync_recovery.authorizations[0];
19587        assert_eq!(saved.reviews[0].head, head);
19588        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19589        assert!(saved.gate_ran);
19590        assert!(!saved.gate[0].ok());
19591        runner.review_loop().await.unwrap();
19592        runner.gate().await.unwrap();
19593        assert_eq!(runner.state.reviews[0].head, head);
19594        assert_eq!(
19595            runner.state.reviews[0].verified_head.as_deref(),
19596            Some(head.as_str())
19597        );
19598        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19599        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19600        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19601        assert!(runner.state.gate_ran);
19602        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19603        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19604        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19605        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19606        assert_eq!(
19607            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19608            "retained change"
19609        );
19610    }
19611
19612    #[cfg(unix)]
19613    #[tokio::test]
19614    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19615        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19616        let queue = crate::queue::Queue::open();
19617        let mut owner = queue.get(&task).unwrap();
19618        owner.release_operator("test-resume", None);
19619        queue.put(&mut owner).unwrap();
19620        let generation = owner.resumption.as_ref().unwrap().generation;
19621        runner.state.task_instruction = Some(owner.instruction.clone());
19622        runner.state.driver_exited = true;
19623        runner.state.save().unwrap();
19624        let home = crate::run::home();
19625        let _claim = queue.claim(&task).unwrap();
19626        owner.resumption.as_mut().unwrap().at =
19627            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19628        queue.put(&mut owner).unwrap();
19629        assert!(
19630            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19631                .await
19632                .is_err(),
19633            "an approval from before the stop grants nothing"
19634        );
19635        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19636        queue.put(&mut owner).unwrap();
19637        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19638            .await
19639            .unwrap();
19640        assert!(
19641            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19642                .await
19643                .is_err()
19644        );
19645        runner.state = RunState::load(&runner.state.id).unwrap();
19646        assert_eq!(
19647            runner.state.base_sync_recovery.authorizations[0].generation,
19648            Some(generation)
19649        );
19650        runner.sync_to_base().await.unwrap();
19651        let repo = runner.state.repo.clone();
19652        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19653        git::git(&repo, &["checkout", "main"]).await.unwrap();
19654        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19655        git::git(&repo, &["add", "."]).await.unwrap();
19656        git::git(&repo, &["commit", "-m", "move base again"])
19657            .await
19658            .unwrap();
19659        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19660        git::git(&repo, &["checkout", "fix/retained"])
19661            .await
19662            .unwrap();
19663        runner.sync_to_base().await.unwrap();
19664        assert!(!runner.state.base_sync_blocked());
19665        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19666        assert_eq!(runner.state.base_episode_used(), 2);
19667        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19668        assert_ne!(fresh, head);
19669        assert!(!runner.state.base_recovery_pending());
19670        // Even replaying the generation with a later timestamp grants nothing.
19671        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19672        queue.put(&mut owner).unwrap();
19673        assert!(
19674            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19675                .await
19676                .is_err()
19677        );
19678        runner.state = RunState::load(&runner.state.id).unwrap();
19679        runner.sync_to_base().await.unwrap();
19680        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19681        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19682        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19683    }
19684
19685    #[cfg(unix)]
19686    #[tokio::test]
19687    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19688        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19689        runner.state.base_sync = None;
19690        runner.state.status = RunStatus::Blocked;
19691        let mut second = runner.state.candidates[0].clone();
19692        second.label = 'B';
19693        runner.state.candidates.push(second);
19694        assert!(runner.state.votes.is_empty());
19695        assert!(runner.state.deliberation.is_empty());
19696        runner.deliberate().await.unwrap();
19697        runner.vote().await.unwrap();
19698        assert_eq!(runner.state.status, RunStatus::Blocked);
19699        assert!(runner.state.votes.is_empty());
19700        assert!(runner.state.deliberation.is_empty());
19701    }
19702
19703    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19704    /// reads nothing else off it.
19705    fn runner_at(status: RunStatus) -> Runner {
19706        let mut state = RunState::new(
19707            PathBuf::from("/nonexistent/repo"),
19708            "main".to_owned(),
19709            "deadbeef".to_owned(),
19710            "task".to_owned(),
19711            Config::default(),
19712        );
19713        // These fixtures test execution flow, independent of host disk capacity.
19714        state.config.disk.min_free_bytes = 0;
19715        // These fixtures share one home and save concurrently. Short clock
19716        // IDs can collide, making an ownership test read another test's run.
19717        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19718        state.id = format!(
19719            "20000101-000000-{:04x}",
19720            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19721        );
19722        state.status = status;
19723        Runner {
19724            state,
19725            roles: ResolvedRoles {
19726                implementers: Vec::new(),
19727                judges: Vec::new(),
19728                reviewers: Vec::new(),
19729                fixer: None,
19730                conductor: conductor(),
19731                implementer_roster: Vec::new(),
19732                judge_roster: Vec::new(),
19733                reviewer_roster: Vec::new(),
19734            },
19735            sem: Arc::new(Semaphore::new(1)),
19736            pause: Pause::new(),
19737            interrupt: Pause::new(),
19738        }
19739    }
19740
19741    #[tokio::test]
19742    async fn targeted_fix_refuses_independent_ownership_conflicts() {
19743        crate::run::pin_test_home();
19744        let home = crate::run::home();
19745        let mut runner = runner_at(RunStatus::Ready);
19746        runner.state.driver_exited = true;
19747        runner.state.save().unwrap();
19748        let id = runner.state.id.clone();
19749        let path = runner.state.dir().join("run.json");
19750        let ids = ["R1-1-1".into()];
19751        let lease = crate::driver::maintenance(&home, &id).unwrap();
19752        for (guard, expected) in [
19753            (Some(lease), "currently being worked on"),
19754            (None, "ownership is being updated"),
19755        ] {
19756            let owner = if guard.is_none() {
19757                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
19758            } else {
19759                None
19760            };
19761            let before = std::fs::read(&path).unwrap();
19762            let err = runner
19763                .fix_selected(&ids, "ownership conflict", false)
19764                .await
19765                .unwrap_err();
19766            assert!(format!("{err:#}").contains(expected), "{err:#}");
19767            assert_eq!(std::fs::read(&path).unwrap(), before);
19768            assert!(!runner.state.dir().join("fix.lock").exists());
19769            drop(owner);
19770            drop(guard);
19771        }
19772        let mut disk = RunState::load(&id).unwrap();
19773        disk.driver_exited = false;
19774        disk.driver_pid = Some(std::process::id());
19775        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
19776        disk.save().unwrap();
19777        assert_eq!(
19778            disk.liveness_under(&home, false),
19779            crate::run::Liveness::Live
19780        );
19781        let before = std::fs::read(&path).unwrap();
19782        let err = runner
19783            .fix_selected(&ids, "live driver", false)
19784            .await
19785            .unwrap_err();
19786        assert!(
19787            err.to_string().contains("currently being worked on"),
19788            "{err:#}"
19789        );
19790        assert_eq!(std::fs::read(&path).unwrap(), before);
19791        assert!(!runner.state.dir().join("fix.lock").exists());
19792        disk.driver_exited = true;
19793        disk.driver_pid = None;
19794        disk.driver_started_at = None;
19795        disk.status = RunStatus::Reviewing;
19796        disk.save().unwrap();
19797        let before = std::fs::read(&path).unwrap();
19798        let err = runner
19799            .fix_selected(&ids, "stale state", false)
19800            .await
19801            .unwrap_err();
19802        assert!(
19803            err.to_string().contains("run changed since it was loaded"),
19804            "{err:#}"
19805        );
19806        assert_eq!(std::fs::read(&path).unwrap(), before);
19807        assert!(!runner.state.dir().join("fix.lock").exists());
19808        assert!(runner.state.operator_fixes.is_empty());
19809    }
19810
19811    #[tokio::test]
19812    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
19813        use std::future::Future;
19814        use std::task::Poll;
19815
19816        crate::run::pin_test_home();
19817        let home = crate::run::home();
19818        let repo = tempfile::tempdir().unwrap();
19819        let mut runner = runner_at(RunStatus::Ready);
19820        runner.state.repo = repo.path().to_path_buf();
19821        runner.state.driver_exited = true;
19822        runner.state.candidates.push(Candidate {
19823            index: 0,
19824            label: 'A',
19825            agent: "mock".into(),
19826            branch: "magi/test/A".into(),
19827            worktree: repo.path().join("wt"),
19828            summary: String::new(),
19829            stat: String::new(),
19830            files: 0,
19831            commits: 0,
19832            empty: false,
19833            failed: None,
19834            verified_noop: None,
19835            duration_ms: 0,
19836            folded: false,
19837        });
19838        runner.state.tally = Some(Tally {
19839            first_choice: BTreeMap::from([('A', 1)]),
19840            borda: BTreeMap::new(),
19841            winner: 'A',
19842            rankings: 1,
19843            unanimous_initial: true,
19844            deliberated: false,
19845            changed_votes: 0,
19846            unanimous_final: true,
19847            tie_break: None,
19848            judges: 1,
19849            present: 1,
19850            quorum: 1,
19851            met_quorum: true,
19852            uncontested: None,
19853        });
19854        runner.state.save().unwrap();
19855        let id = runner.state.id.clone();
19856        let dir = runner.state.dir();
19857        let before = std::fs::read(dir.join("run.json")).unwrap();
19858        let ids = ["R1-1-1".into()];
19859        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
19860        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
19861            Poll::Pending => Poll::Ready(()),
19862            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
19863        })
19864        .await;
19865        assert!(FixClaim::acquire(&dir).is_err());
19866        assert!(crate::driver::maintenance(&home, &id).is_err());
19867        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
19868        drop(fix);
19869        assert!(FixClaim::acquire(&dir).is_ok());
19870        assert!(crate::driver::maintenance(&home, &id).is_ok());
19871        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
19872    }
19873
19874    #[tokio::test]
19875    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19876        crate::run::pin_test_home();
19877        let temp = tempfile::tempdir().unwrap();
19878        let root = temp.path().canonicalize().unwrap();
19879        let repo = root.join("repo");
19880        std::fs::create_dir(&repo).unwrap();
19881        init_repo(&repo);
19882        git::git(&repo, &["config", "core.autocrlf", "false"])
19883            .await
19884            .unwrap();
19885        let mut runner = runner_at(RunStatus::Blocked);
19886        runner.state.repo = repo.clone();
19887        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19888        runner.state.config.agents = vec![conductor()];
19889        runner.state.config.graph.selected_implementer = Some("conductor".into());
19890        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19891        let (shell, command, setup_output) = if cfg!(windows) {
19892            (
19893                vec!["cmd".into(), "/C".into()],
19894                "echo ready>seat-ready",
19895                "ready\r\n",
19896            )
19897        } else {
19898            (
19899                vec!["sh".into(), "-c".into()],
19900                "printf ready > seat-ready",
19901                "ready",
19902            )
19903        };
19904        runner.state.config.verify.shell = Some(shell);
19905        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19906            run: Some(command.into()),
19907            ..Default::default()
19908        }];
19909        runner.state.save().unwrap();
19910        let path = runner.state.worktree_root().join("judge-1");
19911        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19912            .await
19913            .unwrap();
19914        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19915        git::git(&path, &["add", "."]).await.unwrap();
19916        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19917        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19918            .await
19919            .unwrap();
19920        git::git(&path, &["checkout", "--detach", &head])
19921            .await
19922            .unwrap();
19923        let evidence = crate::fold_evidence::snapshot(
19924            &runner.state,
19925            &crate::run::home().canonicalize().unwrap(),
19926            &head,
19927            64 * 1024 * 1024,
19928        )
19929        .await
19930        .unwrap();
19931        let mut contents = BTreeMap::new();
19932        contents.insert(
19933            repo.join("logs/HEAD"),
19934            format!("{head} {head} fixture\n").into_bytes(),
19935        );
19936        let record = serde_json::json!({
19937            "version":1, "run":runner.state.id, "source":path, "head":head,
19938            "evidence":evidence, "admin":{}, "admin_contents":contents,
19939            "history":{head.clone():evidence}, "phase":"evicted"
19940        });
19941        std::fs::write(
19942            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19943            serde_json::to_vec(&record).unwrap(),
19944        )
19945        .unwrap();
19946        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19947        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19948            .await
19949            .unwrap();
19950        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19951        assert!(
19952            !git::git_raw(&repo, &["cat-file", "-e", &head])
19953                .await
19954                .unwrap()
19955                .ok()
19956        );
19957        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19958        let error = resumed.execute().await.unwrap_err();
19959        assert!(
19960            error
19961                .to_string()
19962                .contains("selected implementation is held"),
19963            "{error:#}"
19964        );
19965        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19966        assert_eq!(
19967            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19968            setup_output
19969        );
19970        assert_eq!(
19971            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19972            "unrelated seat"
19973        );
19974        let error = resumed.execute().await.unwrap_err();
19975        assert!(
19976            error
19977                .to_string()
19978                .contains("selected implementation is held"),
19979            "{error:#}"
19980        );
19981        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19982        git::git(&path, &["add", "."]).await.unwrap();
19983        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19984        let next = git::git(
19985            &path,
19986            &[
19987                "commit-tree",
19988                &next_tree,
19989                "-p",
19990                &head,
19991                "-m",
19992                "next review checkpoint",
19993            ],
19994        )
19995        .await
19996        .unwrap();
19997        git::git(&path, &["checkout", "--detach", &next])
19998            .await
19999            .unwrap();
20000        resumed.state.reviews.push(
20001            serde_json::from_value(serde_json::json!({
20002                "round":1, "head":next, "reviews":[]
20003            }))
20004            .unwrap(),
20005        );
20006        resumed.state.save().unwrap();
20007        let error = resumed.execute().await.unwrap_err();
20008        assert!(
20009            error
20010                .to_string()
20011                .contains("selected implementation is held"),
20012            "{error:#}"
20013        );
20014        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
20015    }
20016
20017    #[tokio::test]
20018    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
20019        crate::run::pin_test_home();
20020        let mut runner = runner_at(RunStatus::Gating);
20021        runner.state.save().unwrap();
20022        let id = runner.state.id.clone();
20023        let passes = runner.state.passes.len();
20024        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20025        let mut claiming = Box::pin(runner.claim_driver(None));
20026        std::future::poll_fn(|cx| {
20027            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
20028            std::task::Poll::Ready(())
20029        })
20030        .await;
20031        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
20032        drop(owner);
20033        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
20034            .await
20035            .unwrap()
20036            .unwrap();
20037        assert_eq!(execution.runner.state.passes.len(), passes + 1);
20038        assert!(execution.runner.state.resource_block.is_none());
20039        assert_eq!(
20040            execution.runner.state.liveness(false),
20041            crate::run::Liveness::Live
20042        );
20043        drop(execution);
20044        assert!(RunState::load(&id).unwrap().driver_exited);
20045    }
20046
20047    #[tokio::test]
20048    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
20049        crate::run::pin_test_home();
20050        let mut runner = runner_at(RunStatus::Gating);
20051        runner.state.save().unwrap();
20052        // run.json can commit, but the subsequent lease metadata write fails.
20053        // Cleanup must run after releasing the short ownership lock.
20054        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
20055        assert!(runner.claim_driver(None).await.is_err());
20056        assert!(runner.state.driver_exited);
20057        assert_eq!(runner.state.driver_pid, None);
20058        let disk = RunState::load(&runner.state.id).unwrap();
20059        assert!(disk.driver_exited);
20060        assert_eq!(disk.driver_pid, None);
20061        assert_eq!(disk.status, RunStatus::Gating);
20062    }
20063
20064    #[tokio::test]
20065    async fn an_early_graph_error_releases_its_driver() {
20066        crate::run::pin_test_home();
20067        let mut runner = runner_at(RunStatus::Blocked);
20068        runner.state.config.graph.selected_implementer = Some("selected".into());
20069        runner.state.save().unwrap();
20070        assert!(runner.execute().await.is_err());
20071        let disk = RunState::load(&runner.state.id).unwrap();
20072        assert!(disk.driver_exited);
20073        assert_eq!(disk.driver_pid, None);
20074        assert_eq!(disk.status, RunStatus::Blocked);
20075    }
20076
20077    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
20078        crate::run::MergeRepair {
20079            question: "repair-question".into(),
20080            head: "old-head".into(),
20081            pr: "https://github.com/o/r/pull/42".into(),
20082            reviews: vec![review_round(false, 1, 1, 1, false, true)],
20083            gate: vec![outcome(Some(0), false)],
20084            gate_head: Some("old-head".into()),
20085            gate_fixes: Vec::new(),
20086            pre_gate: Vec::new(),
20087            phase,
20088            failure: None,
20089        }
20090    }
20091
20092    #[tokio::test]
20093    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
20094        crate::run::pin_test_home();
20095        let mut runner = runner_at(RunStatus::Landing);
20096        runner.state.merge_repairs.push(merge_repair_request(
20097            crate::run::MergeRepairPhase::Requested,
20098        ));
20099        runner.state.save().unwrap();
20100        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
20101        assert!(
20102            runner
20103                .execute()
20104                .await
20105                .unwrap_err()
20106                .to_string()
20107                .contains("already running")
20108        );
20109        assert_eq!(
20110            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20111            crate::run::MergeRepairPhase::Requested
20112        );
20113        drop(claim);
20114        let mut disk = runner.state.clone();
20115        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
20116        disk.save().unwrap();
20117        assert!(
20118            runner
20119                .execute()
20120                .await
20121                .unwrap_err()
20122                .to_string()
20123                .contains("decision changed")
20124        );
20125        assert_eq!(
20126            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20127            crate::run::MergeRepairPhase::Complete
20128        );
20129    }
20130
20131    #[test]
20132    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
20133        crate::run::pin_test_home();
20134        let mut runner = runner_at(RunStatus::Landing);
20135        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
20136        runner.state.reviews = request.reviews.clone();
20137        runner.state.gate = request.gate.clone();
20138        runner.state.gate_ran = true;
20139        runner.state.land_approval = Some(crate::run::LandApproval {
20140            question: "old".into(),
20141            head: "old-head".into(),
20142        });
20143        runner.state.merge_repairs.push(request);
20144        runner.begin_merge_repair_review(0).unwrap();
20145        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
20146        assert!(!runner.state.gate_status().ok());
20147        assert!(runner.state.land_approval.is_none());
20148        let disk = RunState::load(&runner.state.id).unwrap();
20149        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
20150        assert!(disk.merge_repairs[0].gate[0].ok());
20151        assert_eq!(
20152            disk.merge_repairs[0].phase,
20153            crate::run::MergeRepairPhase::Reviewing
20154        );
20155        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
20156        assert!(disk.reviews.is_empty());
20157    }
20158
20159    #[tokio::test]
20160    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
20161        crate::run::pin_test_home();
20162        for phase in [
20163            crate::run::MergeRepairPhase::Fixing,
20164            crate::run::MergeRepairPhase::Requested,
20165        ] {
20166            let mut runner = runner_at(RunStatus::Landing);
20167            runner.state.config.graph.land_rounds = 0;
20168            runner.state.merge_repairs.push(merge_repair_request(phase));
20169            runner.state.save().unwrap();
20170            assert!(!runner.repair_merge_review().await.unwrap());
20171            assert_eq!(runner.state.status, RunStatus::Blocked);
20172            assert_eq!(
20173                runner.state.merge_repairs[0].phase,
20174                crate::run::MergeRepairPhase::Failed
20175            );
20176            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
20177            assert!(
20178                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
20179                    "interrupted"
20180                } else {
20181                    "budget exhausted"
20182                })
20183            );
20184            assert!(runner.state.merge.is_none());
20185        }
20186    }
20187
20188    /// `park_here` folding in the reason `Pause::park_because` recorded -
20189    /// this is what lets an operator reading a run's events tell an
20190    /// interrupt-driven park from an ordinary shutdown park.
20191    #[test]
20192    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
20193        crate::run::pin_test_home();
20194        let mut runner = runner_at(RunStatus::Implementing);
20195        let interrupt = Pause::new();
20196        runner.watch_interrupt(interrupt.clone());
20197
20198        interrupt.park_because("task a1b2 asked to run first");
20199
20200        assert!(runner.park_here().expect("park_here"));
20201        assert!(runner.state.parked);
20202        let last = runner.state.events.last().expect("a park event");
20203        assert_eq!(last.node, "park");
20204        assert!(
20205            last.message.contains("task a1b2 asked to run first"),
20206            "expected the interrupt reason in {:?}",
20207            last.message
20208        );
20209    }
20210
20211    /// The cause is stored on the pass when it parks, and the first cause a
20212    /// shared pause was given is the one that stays.
20213    #[test]
20214    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
20215        crate::run::pin_test_home();
20216        let mut runner = runner_at(RunStatus::Implementing);
20217        runner.state.begin_pass();
20218        let shutdown = Pause::new();
20219        runner.on_pause(shutdown.clone());
20220        let upgrade = ParkCause::Upgrade {
20221            from: "0.121.0".to_owned(),
20222            to: Some("0.121.1".to_owned()),
20223        };
20224        shutdown.park_for(upgrade.clone());
20225        shutdown.park_for(ParkCause::Operator);
20226
20227        assert!(runner.park_here().expect("park_here"));
20228        assert_eq!(
20229            runner.state.passes[0].end,
20230            Some(crate::run::PassEnd::Parked { cause: upgrade })
20231        );
20232        let last = runner.state.events.last().expect("a park event");
20233        assert!(last.message.contains("0.121.0"), "{}", last.message);
20234    }
20235
20236    #[tokio::test]
20237    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
20238        crate::run::pin_test_home();
20239        let mut runner = runner_at(RunStatus::Reviewing);
20240        runner.state.save().unwrap();
20241        let mut execution = runner.claim_driver(None).await.expect("first execution");
20242        assert_eq!(execution.runner.state.passes.len(), 1);
20243        execution
20244            .driver
20245            .finish(&mut execution.runner.state)
20246            .await
20247            .unwrap();
20248    }
20249
20250    #[tokio::test]
20251    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
20252        crate::run::pin_test_home();
20253        let mut runner = runner_at(RunStatus::Reviewing);
20254        runner.state.config.agents = vec![conductor()];
20255        runner.state.config.graph.timeout_resource_wait = 0;
20256        runner.state.save().unwrap();
20257        let id = runner.state.id.clone();
20258        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20259        assert!(runner.claim_driver(None).await.is_err());
20260        drop(owner);
20261        drop(runner);
20262        let mut resumed = Runner::resume(&id).unwrap();
20263        assert_eq!(resumed.state.driver_claimed, Some(false));
20264        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
20265        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
20266        let mut execution = resumed
20267            .claim_driver(None)
20268            .await
20269            .expect("retry initial claim after reload");
20270        assert_eq!(execution.runner.state.driver_claimed, Some(true));
20271        assert_eq!(execution.runner.state.passes.len(), 1);
20272        execution
20273            .driver
20274            .finish(&mut execution.runner.state)
20275            .await
20276            .unwrap();
20277    }
20278
20279    #[tokio::test]
20280    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
20281        crate::run::pin_test_home();
20282        let mut runner = runner_at(RunStatus::Reviewing);
20283        runner.state.config.agents = vec![conductor()];
20284        runner.state.save().unwrap();
20285        let id = runner.state.id.clone();
20286        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20287        let mut resumed = Runner::resume(&id).unwrap();
20288        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20289        assert!(resumed.claim_driver(None).await.is_err());
20290        assert!(RunState::load(&id).unwrap().passes.is_empty());
20291        drop(lease);
20292        let mut execution = resumed.claim_driver(None).await.unwrap();
20293        execution
20294            .driver
20295            .finish(&mut execution.runner.state)
20296            .await
20297            .unwrap();
20298    }
20299
20300    #[tokio::test]
20301    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20302        crate::run::pin_test_home();
20303        let mut runner = runner_at(RunStatus::Reviewing);
20304        let state = &mut runner.state;
20305        state.config.agents = vec![conductor()];
20306        state.driver_claimed = None;
20307        state.driver_pid = Some(std::process::id());
20308        state.driver_started_at = None;
20309        state.begin_pass();
20310        state.save().unwrap();
20311        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20312        std::fs::write(
20313            state.dir().join("driver.json"),
20314            serde_json::to_vec(&serde_json::json!({
20315                "pid": state.driver_pid, "started_at": null,
20316                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20317            }))
20318            .unwrap(),
20319        )
20320        .unwrap();
20321        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20322        drop(lease);
20323        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20324        let mut resumed = Runner::resume(&state.id).unwrap();
20325        assert!(!resumed.state.driver_exited);
20326        let mut execution = resumed
20327            .claim_driver(None)
20328            .await
20329            .expect("lease proves previous execution ended");
20330        assert_eq!(execution.runner.state.passes.len(), 2);
20331        execution
20332            .driver
20333            .finish(&mut execution.runner.state)
20334            .await
20335            .unwrap();
20336    }
20337
20338    #[tokio::test]
20339    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20340        crate::run::pin_test_home();
20341        let mut runner = runner_at(RunStatus::Reviewing);
20342        let mut json = serde_json::to_value(&runner.state).unwrap();
20343        json.as_object_mut().unwrap().remove("driver_claimed");
20344        runner.state = serde_json::from_value(json).unwrap();
20345        assert_eq!(runner.state.driver_claimed, None);
20346        runner.state.save().unwrap();
20347        let mut execution = runner
20348            .claim_driver(None)
20349            .await
20350            .expect("the execution lease, not a missing marker, excludes a second driver");
20351        assert_eq!(execution.runner.state.passes.len(), 1);
20352        execution
20353            .driver
20354            .finish(&mut execution.runner.state)
20355            .await
20356            .unwrap();
20357    }
20358
20359    #[tokio::test]
20360    async fn driver_admission_refuses_a_proven_live_driver() {
20361        crate::run::pin_test_home();
20362        let mut runner = runner_at(RunStatus::Reviewing);
20363        let pid = std::process::id();
20364        runner.state.driver_pid = Some(pid);
20365        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20366        assert!(runner.state.driver_started_at.is_some());
20367        runner.state.save().unwrap();
20368        let error = runner
20369            .claim_driver(None)
20370            .await
20371            .err()
20372            .expect("a live driver must refuse");
20373        assert!(error.to_string().contains("live driver"), "{error:#}");
20374        let saved = RunState::load(&runner.state.id).unwrap();
20375        assert_eq!(saved.driver_pid, Some(pid));
20376        assert_eq!(saved.status, RunStatus::Reviewing);
20377        assert!(saved.passes.is_empty());
20378    }
20379
20380    #[test]
20381    fn parking_resource_halt_persists_the_pass_once() {
20382        crate::run::pin_test_home();
20383        let mut runner = runner_at(RunStatus::Reviewing);
20384        runner.state.begin_pass();
20385        runner.state.resource_block = Some(crate::run::ResourceBlock {
20386            node: "fix".into(),
20387            kind: "shared build cache".into(),
20388            detail: "cancelled".into(),
20389            at: Timestamp::now(),
20390            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20391        });
20392        let cause = ParkCause::Upgrade {
20393            from: "old".into(),
20394            to: Some("new".into()),
20395        };
20396        runner.pause.park_for(cause.clone());
20397        // Both direct fixer exits and graph resource boundaries must complete
20398        // parking, rather than returning a stale Reviewing record.
20399        runner.stop_for_resource().unwrap();
20400        assert!(runner.resource_halt().unwrap());
20401        assert!(runner.park_here().unwrap());
20402        let saved = RunState::load(&runner.state.id).unwrap();
20403        assert!(saved.parked);
20404        assert_eq!(saved.status, RunStatus::Reviewing);
20405        assert!(saved.passes[0].ended_at.is_some());
20406        assert_eq!(
20407            saved.passes[0].end,
20408            Some(crate::run::PassEnd::Parked {
20409                cause: cause.clone()
20410            })
20411        );
20412        assert_eq!(
20413            saved.resource_block.unwrap().cause,
20414            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20415        );
20416        assert_eq!(
20417            saved
20418                .events
20419                .iter()
20420                .filter(|event| event.node == "park")
20421                .count(),
20422            1
20423        );
20424    }
20425
20426    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20427    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20428    /// cleared) must not make a *different* run - one only watching its own,
20429    /// unshared interrupt `Pause` - see itself as parked. If a future change
20430    /// ever collapsed these back into one handle, the interrupt scheduler
20431    /// would park every run for the rest of the daemon's life, not just the
20432    /// one it meant to interrupt.
20433    #[test]
20434    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20435        crate::run::pin_test_home();
20436        let mut runner = runner_at(RunStatus::Implementing);
20437        let shutdown = Pause::new();
20438        runner.on_pause(shutdown.clone());
20439        let interrupt = Pause::new();
20440        runner.watch_interrupt(interrupt.clone());
20441
20442        // Nobody has asked for anything yet.
20443        assert!(!runner.park_here().expect("park_here"));
20444        assert!(!runner.state.parked);
20445
20446        // Only the interrupt handle fires; the shutdown handle stays clear.
20447        interrupt.park_because("test");
20448        assert!(!shutdown.parked());
20449        assert!(runner.park_here().expect("park_here"));
20450    }
20451
20452    /// The property every prior attempt at this feature failed to pin down:
20453    /// asking a run to park while one of its nodes has a real, in-flight
20454    /// async operation running (an agent call, in production) must not cut
20455    /// that operation short. `park_here` is only ever consulted *between*
20456    /// `execute`'s node calls - see its own doc - so nothing inside a node
20457    /// can observe a park request until the node itself returns. This proves
20458    /// that structurally, with real `tokio` concurrency and a channel
20459    /// handshake (never a sleep, which would only prove "usually", not
20460    /// "cannot"): the "node" below reports that it has genuinely started,
20461    /// and only then is the park requested; the node still has to be told to
20462    /// finish before `park_here` is ever called, exactly mirroring every
20463    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20464    /// in `execute`.
20465    #[tokio::test]
20466    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20467        crate::run::pin_test_home();
20468        let mut runner = runner_at(RunStatus::Implementing);
20469        let interrupt = Pause::new();
20470        runner.watch_interrupt(interrupt.clone());
20471
20472        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20473        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20474
20475        // Stands in for one node's in-flight agent call: it proves it has
20476        // genuinely started, then blocks - exactly as a spawned CLI process
20477        // does - until told to finish.
20478        let node = async move {
20479            started_tx.send(()).expect("send started");
20480            finish_rx.await.expect("recv finish");
20481            "node finished"
20482        };
20483
20484        let interrupter = async move {
20485            started_rx.await.expect("recv started");
20486            // The call is now genuinely in flight. Ask it to park.
20487            interrupt.park_because("higher-priority task waiting");
20488            // Nothing the node does can observe this yet - there is no
20489            // check inside it, by construction - so let the executor run
20490            // anything pending and then let the node finish on its own.
20491            tokio::task::yield_now().await;
20492            finish_tx.send(()).expect("send finish");
20493        };
20494
20495        let (node_result, ()) = tokio::join!(node, interrupter);
20496        assert_eq!(
20497            node_result, "node finished",
20498            "the in-flight call ran to completion"
20499        );
20500
20501        // Only now, at the boundary the real `execute` would check right
20502        // after this node, does the park take effect.
20503        assert!(runner.park_here().expect("park_here"));
20504        assert!(runner.state.parked);
20505    }
20506
20507    /// A run parked mid-competition carries every field it had accumulated
20508    /// through the exact same disk round-trip an ordinary resume uses -
20509    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20510    /// Nothing about parking for an interrupt is a special case of that path;
20511    /// this is what proves it rather than assuming it.
20512    #[test]
20513    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20514        crate::run::pin_test_home();
20515        let mut runner = runner_at(RunStatus::Judging);
20516        // `Runner::resume` re-resolves roles from the saved config, which
20517        // refuses an empty roster - give it the same minimal one `conductor`
20518        // itself uses.
20519        runner.state.config.agents = vec![conductor()];
20520        runner.state.candidates = vec![Candidate {
20521            index: 0,
20522            label: 'A',
20523            agent: "alpha".to_owned(),
20524            branch: "magi/x/A".to_owned(),
20525            worktree: PathBuf::from("/nonexistent/worktree"),
20526            summary: "did the thing".to_owned(),
20527            stat: "1 file changed".to_owned(),
20528            files: 1,
20529            commits: 1,
20530            empty: false,
20531            failed: None,
20532            verified_noop: None,
20533            duration_ms: 1234,
20534            folded: false,
20535        }];
20536        let run_id = runner.state.id.clone();
20537
20538        let interrupt = Pause::new();
20539        runner.watch_interrupt(interrupt.clone());
20540        interrupt.park_because("task c3d4 asked to run first");
20541        assert!(runner.park_here().expect("park_here"));
20542
20543        let resumed = Runner::resume(&run_id).expect("resume");
20544        assert_eq!(resumed.state.candidates.len(), 1);
20545        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20546        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20547        assert_eq!(resumed.state.status, runner.state.status);
20548        assert!(
20549            resumed.state.parked,
20550            "still parked until `execute` actually walks the graph again"
20551        );
20552        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20553    }
20554
20555    /// A fresh open question on `run`, stored and handed back for assertions.
20556    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20557        let mut q = ask::Question::new(
20558            run.to_owned(),
20559            "implement".to_owned(),
20560            "impl-A".to_owned(),
20561            "Which storage backend should the cache use?".to_owned(),
20562            String::new(),
20563            vec!["SQLite".to_owned(), "Redis".to_owned()],
20564        );
20565        store.put(&mut q).unwrap();
20566        q
20567    }
20568
20569    #[test]
20570    fn a_failed_runs_open_question_is_abandoned() {
20571        ask_test_home();
20572        let store = ask::Questions::open();
20573        let mut runner = runner_at(RunStatus::Failed);
20574        let run = runner.state.id.clone();
20575        let q = ask_open_question(&store, &run);
20576
20577        runner.settle_questions();
20578
20579        let back = store.get(&q.id).unwrap();
20580        assert!(
20581            !back.status.open(),
20582            "the seat that asked died with the run; nobody is left to read an answer"
20583        );
20584        assert!(
20585            back.detail.contains(&run) && back.detail.contains("failed"),
20586            "the reason names what the run became, not just that it is gone: {}",
20587            back.detail
20588        );
20589    }
20590
20591    #[test]
20592    fn a_merged_runs_open_question_is_abandoned_too() {
20593        ask_test_home();
20594        let store = ask::Questions::open();
20595        // A run that finishes cleanly still leaves nobody to read an answer -
20596        // this is not only a failure-path cleanup.
20597        for status in [RunStatus::Merged, RunStatus::Ready] {
20598            let mut runner = runner_at(status);
20599            let run = runner.state.id.clone();
20600            let q = ask_open_question(&store, &run);
20601
20602            runner.settle_questions();
20603
20604            let back = store.get(&q.id).unwrap();
20605            assert!(
20606                !back.status.open(),
20607                "{status:?} run's question must not outlive the run"
20608            );
20609        }
20610    }
20611
20612    #[test]
20613    fn a_still_resumable_runs_open_question_is_left_alone() {
20614        ask_test_home();
20615        let store = ask::Questions::open();
20616        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20617        // review round and the seat sessions are all still on disk — so a
20618        // question asked mid-round may yet get a real answer from a real
20619        // resume. Sweeping it here would be exactly the failure mode this
20620        // whole feature exists to avoid on the other side.
20621        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20622            let mut runner = runner_at(status);
20623            let run = runner.state.id.clone();
20624            let q = ask_open_question(&store, &run);
20625
20626            runner.settle_questions();
20627
20628            let back = store.get(&q.id).unwrap();
20629            assert!(
20630                back.status.open(),
20631                "{status:?} is still alive; the question must still be waiting"
20632            );
20633        }
20634    }
20635
20636    #[test]
20637    fn settle_questions_never_touches_an_already_answered_question() {
20638        ask_test_home();
20639        let store = ask::Questions::open();
20640        let mut runner = runner_at(RunStatus::Failed);
20641        let run = runner.state.id.clone();
20642        let mut q = ask_open_question(&store, &run);
20643        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20644            .unwrap();
20645        store.put(&mut q).unwrap();
20646
20647        // Called twice, the way a crash-recovered daemon reclaim and the
20648        // graph's own cleanup both can for the same run — `abandon_for_run`
20649        // only ever touches what is still open, so this must be inert both
20650        // times, not merely the second.
20651        runner.settle_questions();
20652        runner.settle_questions();
20653
20654        let back = store.get(&q.id).unwrap();
20655        assert_eq!(
20656            back.status,
20657            ask::QuestionStatus::Answered,
20658            "a real answer is a decision on record, never overwritten by a sweep"
20659        );
20660    }
20661
20662    #[tokio::test]
20663    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20664        let tmp = tempfile::tempdir().unwrap();
20665        let home = tmp.path().join("home");
20666        let repo = tmp.path().join("repo");
20667        std::fs::create_dir(&home).unwrap();
20668        std::fs::create_dir(&repo).unwrap();
20669        init_repo(&repo);
20670
20671        let mut config = Config::default();
20672        config.graph.worktree_root = Some(tmp.path().join("wt"));
20673        config.verify.build_cache = crate::config::BuildCache::Isolated;
20674        let mut state = RunState::new(
20675            repo.clone(),
20676            "main".into(),
20677            "base".into(),
20678            "fold fixture".into(),
20679            config,
20680        );
20681        let root = state.worktree_root();
20682        let mut outputs = Vec::new();
20683        for name in ["idle", "busy"] {
20684            let checkout = root.join(name);
20685            git::worktree_add_detached(&repo, &checkout, "main")
20686                .await
20687                .unwrap();
20688            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20689            let output = target.join("generated");
20690            std::fs::write(&output, name).unwrap();
20691            outputs.push((target, output));
20692        }
20693        let unknown = crate::build_target::root(&home)
20694            .join("00000000-0000-0000-0000-000000000000")
20695            .join("target");
20696        std::fs::create_dir_all(&unknown).unwrap();
20697        let unowned = unknown.join("generated");
20698        std::fs::write(&unowned, "keep").unwrap();
20699        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20700        let crate::cache::AcquireOutcome::Acquired(_lease) =
20701            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20702        else {
20703            panic!("fixture target must be free");
20704        };
20705
20706        fold_run(&mut state, true, &home).await.unwrap();
20707        assert!(!root.exists());
20708        assert!(!outputs[0].1.exists());
20709        assert!(outputs[1].1.is_file());
20710        assert!(unowned.is_file());
20711    }
20712
20713    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20714    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20715    /// without merging, whose winner is still the operator's answer to read.
20716    /// Nothing previously called `fold_run` itself with a real `tally`, so
20717    /// this is the first test to pin down the one distinction the whole
20718    /// automatic-fold feature depends on: the winner's worktree and branch
20719    /// must survive, everything else sharing the run's worktree bay - a
20720    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20721    /// second sweep treats every non-winner directory under the bay alike -
20722    /// must not.
20723    #[tokio::test]
20724    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20725        crate::run::pin_test_home();
20726        let tmp = tempfile::tempdir().expect("tempdir");
20727        let repo = tmp.path().join("repo");
20728        std::fs::create_dir_all(&repo).unwrap();
20729        init_repo(&repo);
20730
20731        let mut config = Config::default();
20732        config.graph.worktree_root = Some(tmp.path().join("wt"));
20733
20734        let mut state = RunState::new(
20735            repo.clone(),
20736            "main".to_owned(),
20737            "deadbeef".to_owned(),
20738            "task".to_owned(),
20739            config,
20740        );
20741        let root = state.worktree_root();
20742        let wt_a = root.join("cand-A");
20743        let wt_b = root.join("cand-B");
20744        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20745            .await
20746            .expect("worktree A");
20747        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20748            .await
20749            .expect("worktree B");
20750
20751        state.candidates = vec![
20752            Candidate {
20753                index: 0,
20754                label: 'A',
20755                agent: "alpha".to_owned(),
20756                branch: "magi/x/A".to_owned(),
20757                worktree: wt_a.clone(),
20758                summary: String::new(),
20759                stat: String::new(),
20760                files: 0,
20761                commits: 0,
20762                empty: false,
20763                failed: None,
20764                verified_noop: None,
20765                duration_ms: 0,
20766                folded: false,
20767            },
20768            Candidate {
20769                index: 1,
20770                label: 'B',
20771                agent: "beta".to_owned(),
20772                branch: "magi/x/B".to_owned(),
20773                worktree: wt_b.clone(),
20774                summary: String::new(),
20775                stat: String::new(),
20776                files: 0,
20777                commits: 0,
20778                empty: false,
20779                failed: None,
20780                verified_noop: None,
20781                duration_ms: 0,
20782                folded: false,
20783            },
20784        ];
20785        state.tally = Some(Tally {
20786            first_choice: BTreeMap::from([('A', 1)]),
20787            borda: BTreeMap::new(),
20788            winner: 'A',
20789            rankings: 1,
20790            unanimous_initial: true,
20791            deliberated: false,
20792            changed_votes: 0,
20793            unanimous_final: true,
20794            tie_break: None,
20795            judges: 1,
20796            present: 1,
20797            quorum: 1,
20798            met_quorum: true,
20799            uncontested: None,
20800        });
20801        state.status = RunStatus::Ready;
20802
20803        fold_run(&mut state, false, &crate::run::home())
20804            .await
20805            .expect("fold_run");
20806
20807        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20808        assert!(
20809            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20810            "the unmerged winner's branch survives"
20811        );
20812        assert!(
20813            !state.candidates[0].folded,
20814            "the winner is not marked folded"
20815        );
20816
20817        assert!(!wt_b.exists(), "the loser's worktree is removed");
20818        assert!(
20819            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20820            "the loser's branch is removed"
20821        );
20822        assert!(state.candidates[1].folded, "the loser is marked folded");
20823    }
20824
20825    #[tokio::test]
20826    #[cfg(unix)]
20827    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20828        use std::os::fd::AsRawFd as _;
20829        use std::time::Duration;
20830
20831        let tmp = tempfile::tempdir().unwrap();
20832        let repo = tmp.path().join("repo");
20833        std::fs::create_dir_all(&repo).unwrap();
20834        init_repo(&repo);
20835        let common = repo.join(".git");
20836        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20837        let home = tmp.path().join("home");
20838        let mut config = Config::default();
20839        config.coordination = crate::config::test_coordination();
20840        config.graph.worktree_root = Some(tmp.path().join("wt"));
20841        config.graph.timeout_resource_wait = 1;
20842        let mut state = RunState::new(
20843            repo.clone(),
20844            "main".into(),
20845            "deadbeef".into(),
20846            "task".into(),
20847            config,
20848        );
20849        let root = state.worktree_root();
20850        let candidate = root.join("cand-A");
20851        let reviewer = root.join("review-1");
20852        let branch = state.branch_for('A');
20853        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20854            .await
20855            .unwrap();
20856        git::worktree_add_detached(&repo, &reviewer, "main")
20857            .await
20858            .unwrap();
20859        git::acquire_worktree_config(&repo).await.unwrap();
20860        state.enabled_worktree_config = true;
20861        state.status = RunStatus::Ready;
20862        state.candidates.push(Candidate {
20863            index: 0,
20864            label: 'A',
20865            agent: "implement".into(),
20866            branch: branch.clone(),
20867            worktree: candidate.clone(),
20868            summary: String::new(),
20869            stat: String::new(),
20870            files: 0,
20871            commits: 0,
20872            empty: false,
20873            failed: None,
20874            verified_noop: None,
20875            duration_ms: 0,
20876            folded: false,
20877        });
20878        state.save_under(&home).unwrap();
20879        let config_before = std::fs::read(common.join("config")).unwrap();
20880        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20881            .await
20882            .unwrap();
20883        // A separate OS handle bypasses the launcher's local gate, exactly as
20884        // an external updater does, and must still prevent all folding work.
20885        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20886        assert_eq!(
20887            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20888            0
20889        );
20890        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20891        assert!(
20892            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20893                .await
20894                .is_err()
20895        );
20896        assert!(candidate.exists());
20897        assert!(reviewer.exists());
20898        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20899        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20900        assert_eq!(
20901            git::git(&repo, &["worktree", "list", "--porcelain"])
20902                .await
20903                .unwrap(),
20904            worktrees_before
20905        );
20906        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20907            .await
20908            .unwrap()
20909            .unwrap_err();
20910        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20911        drop(fold);
20912        assert!(candidate.exists() && reviewer.exists());
20913        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20914        assert_eq!(
20915            state.resource_block.as_ref().unwrap().kind,
20916            "repository coordination"
20917        );
20918        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20919        drop(external);
20920        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20921        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20922            .await
20923            .unwrap()
20924            .unwrap();
20925        drop(fold);
20926        assert!(removed.contains(&branch));
20927        assert!(!root.exists());
20928        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20929        assert!(state.candidates[0].folded);
20930        assert!(!state.enabled_worktree_config);
20931        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20932        let enabled = git::git_raw(
20933            &repo,
20934            &["config", "--local", "--get", "extensions.worktreeConfig"],
20935        )
20936        .await
20937        .unwrap();
20938        assert!(!enabled.ok(), "the last config reference was released");
20939    }
20940
20941    /// A branch handed to a later run is that run's (and its pull request's):
20942    /// folding the run that released it must not delete it.
20943    #[tokio::test]
20944    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20945        let tmp = tempfile::tempdir().expect("tempdir");
20946        let repo = tmp.path().join("repo");
20947        std::fs::create_dir_all(&repo).unwrap();
20948        init_repo(&repo);
20949        let home = tmp.path().join("home");
20950
20951        let mut config = Config::default();
20952        config.graph.worktree_root = Some(tmp.path().join("wt"));
20953        let mut state = RunState::new(
20954            repo.clone(),
20955            "main".to_owned(),
20956            "deadbeef".to_owned(),
20957            "task".to_owned(),
20958            config,
20959        );
20960        // The worktree is already gone (released); the branch survives.
20961        git::git(&repo, &["branch", "magi/x/A", "main"])
20962            .await
20963            .expect("branch");
20964        state.candidates = vec![Candidate {
20965            index: 0,
20966            label: 'A',
20967            agent: "alpha".to_owned(),
20968            branch: "magi/x/A".to_owned(),
20969            worktree: state.worktree_root().join("cand-A"),
20970            summary: String::new(),
20971            stat: String::new(),
20972            files: 0,
20973            commits: 0,
20974            empty: false,
20975            failed: None,
20976            verified_noop: None,
20977            duration_ms: 0,
20978            folded: true,
20979        }];
20980        state.released_to = Some("20260901-000000-new1".to_owned());
20981        state.released_branches = vec!["magi/x/A".to_owned()];
20982
20983        fold_run(&mut state, true, &home).await.expect("fold_run");
20984        state.status = RunStatus::Merged;
20985        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20986        state.merge = Some(crate::run::MergeOutcome {
20987            mode: MergeMode::Pr,
20988            ok: true,
20989            detail: "confirmed merged".into(),
20990            empty: false,
20991        });
20992        fold_run(&mut state, true, &home)
20993            .await
20994            .expect("merged fold");
20995
20996        assert!(
20997            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20998            "the handed-over branch survives a fold"
20999        );
21000    }
21001
21002    /// A winner with nothing ahead of the base is caught before `gh` is ever
21003    /// asked for a pull request, and the message carries what the task's
21004    /// references resolved to.
21005    #[tokio::test]
21006    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
21007        let tmp = tempfile::tempdir().expect("tempdir");
21008        let repo = tmp.path().join("repo");
21009        std::fs::create_dir_all(&repo).unwrap();
21010        init_repo(&repo);
21011        let run = |args: &[&str]| {
21012            let out = std::process::Command::new("git")
21013                .quiet()
21014                .args(args)
21015                .current_dir(&repo)
21016                .output()
21017                .expect("spawn git");
21018            assert!(out.status.success(), "git {args:?}");
21019        };
21020        run(&["branch", "magi/x/A"]);
21021        run(&["checkout", "-q", "-b", "magi/x/B"]);
21022        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
21023        run(&["add", "-A"]);
21024        run(&["commit", "-q", "-m", "work"]);
21025        run(&["checkout", "-q", "main"]);
21026
21027        // A pull request is compared against the remote's base, so the
21028        // fixture needs one. Before it exists nothing can be read, and the
21029        // answer must be "not empty".
21030        let probe = RunState::new(
21031            repo.clone(),
21032            "main".to_owned(),
21033            "deadbeef".to_owned(),
21034            "task".to_owned(),
21035            Config::default(),
21036        );
21037        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
21038        let bare = tmp.path().join("origin.git");
21039        let out = std::process::Command::new("git")
21040            .quiet()
21041            .args(["init", "-q", "--bare"])
21042            .arg(&bare)
21043            .output()
21044            .expect("spawn git");
21045        assert!(out.status.success(), "git init --bare");
21046        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
21047        run(&["push", "-q", "origin", "main"]);
21048
21049        let mut state = RunState::new(
21050            repo.clone(),
21051            "main".to_owned(),
21052            "deadbeef".to_owned(),
21053            "task".to_owned(),
21054            Config::default(),
21055        );
21056        state.seeds = vec![refs::Seed {
21057            token: "magi/27b2/A".to_owned(),
21058            kind: refs::SeedKind::Unresolved,
21059            sha: String::new(),
21060            branch: true,
21061            detail: "no branch or commit named magi/27b2/A".to_owned(),
21062        }];
21063
21064        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
21065        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
21066        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
21067        let detail = empty_candidate_detail(&state, "main");
21068        assert!(detail.starts_with("empty candidate"), "{detail}");
21069        assert!(!detail.contains("magi/27b2/A"), "{detail}");
21070        assert!(detail.contains("--start-from"), "{detail}");
21071    }
21072
21073    /// `status == Ready` used to be read as "this is the harmless
21074    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
21075    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
21076    /// run's PR was closed without merging — and reentering `merge` with
21077    /// `mode` still `Pr` does not know the difference, so it pushed and
21078    /// opened a second pull request. `mode == Local` reproduces the same
21079    /// blind spot without a network call: reentry must not attempt another
21080    /// git merge once this node has already recorded an outcome.
21081    #[tokio::test]
21082    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
21083        let tmp = tempfile::tempdir().expect("tempdir");
21084        let repo = tmp.path().join("repo");
21085        std::fs::create_dir_all(&repo).unwrap();
21086        init_repo(&repo);
21087
21088        let mut config = Config::default();
21089        config.merge.mode = MergeMode::Local;
21090
21091        let mut state = RunState::new(
21092            repo.clone(),
21093            "main".to_owned(),
21094            "deadbeef".to_owned(),
21095            "task".to_owned(),
21096            config,
21097        );
21098        state.candidates = vec![Candidate {
21099            index: 0,
21100            label: 'A',
21101            agent: "alpha".to_owned(),
21102            branch: "does-not-exist".to_owned(),
21103            worktree: repo.clone(),
21104            summary: String::new(),
21105            stat: String::new(),
21106            files: 0,
21107            commits: 0,
21108            empty: false,
21109            failed: None,
21110            verified_noop: None,
21111            duration_ms: 0,
21112            folded: false,
21113        }];
21114        state.tally = Some(Tally {
21115            first_choice: BTreeMap::from([('A', 1)]),
21116            borda: BTreeMap::new(),
21117            winner: 'A',
21118            rankings: 1,
21119            unanimous_initial: true,
21120            deliberated: false,
21121            changed_votes: 0,
21122            unanimous_final: true,
21123            tie_break: None,
21124            judges: 0,
21125            present: 0,
21126            quorum: 0,
21127            met_quorum: true,
21128            uncontested: Some("only candidate A produced a change".to_owned()),
21129        });
21130        state.reviews = vec![ReviewRound {
21131            round: 1,
21132            head: "deadbeef".to_owned(),
21133            verified_head: None,
21134            verified_at: None,
21135            reviews: Vec::new(),
21136            e2e: Vec::new(),
21137            fix: None,
21138            blocking: 0,
21139            answered: 0,
21140            expected: 0,
21141            clean: true,
21142            verify_retried: false,
21143            e2e_deferred: false,
21144            e2e_defer_reason: None,
21145            progressed: false,
21146            vote_split: false,
21147            reconsideration: Vec::new(),
21148            verdict: None,
21149        }];
21150        state.gate = vec![CommandOutcome {
21151            command: "test".to_owned(),
21152            code: Some(0),
21153            output_tail: String::new(),
21154            duration_ms: 0,
21155            resource_blocked: false,
21156            ..Default::default()
21157        }];
21158        state.gate_ran = true;
21159        // Reached its conclusion already — e.g. `land` closing the PR without
21160        // merging it, which (like the honest `MergeMode::None` path) leaves
21161        // `status` at `Ready`. The recorded outcome is what actually marks
21162        // this node done.
21163        state.status = RunStatus::Ready;
21164        state.merge = Some(MergeOutcome {
21165            mode: MergeMode::Local,
21166            ok: false,
21167            detail: "already concluded".to_owned(),
21168            empty: false,
21169        });
21170
21171        let mut runner = Runner {
21172            state,
21173            roles: ResolvedRoles {
21174                implementers: Vec::new(),
21175                judges: Vec::new(),
21176                reviewers: Vec::new(),
21177                fixer: None,
21178                conductor: conductor(),
21179                implementer_roster: Vec::new(),
21180                judge_roster: Vec::new(),
21181                reviewer_roster: Vec::new(),
21182            },
21183            sem: Arc::new(Semaphore::new(1)),
21184            pause: Pause::new(),
21185            interrupt: Pause::new(),
21186        };
21187
21188        runner.merge().await.expect("merge");
21189
21190        assert_eq!(
21191            runner.state.status,
21192            RunStatus::Ready,
21193            "a concluded run's status must not change on reentry"
21194        );
21195        assert_eq!(
21196            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
21197            Some("already concluded"),
21198            "merge must not run again once the node already recorded an outcome"
21199        );
21200    }
21201
21202    /// `gate` leaves `state.gate_ran` false both before it has ever run and
21203    /// when its last attempt was resource-blocked (the shared build cache
21204    /// could not be acquired or confirmed fresh in time - see
21205    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
21206    /// `Vec` this also leaves behind used to read as "nothing failed" and let
21207    /// a run merge a tree the gate never actually checked - exactly the case
21208    /// a contended cache produces on every retry until it clears. `merge`
21209    /// must refuse until `gate` has actually recorded an attempt.
21210    #[tokio::test]
21211    async fn merge_refuses_a_gate_that_has_not_actually_run() {
21212        let tmp = tempfile::tempdir().expect("tempdir");
21213        let repo = tmp.path().join("repo");
21214        std::fs::create_dir_all(&repo).unwrap();
21215        init_repo(&repo);
21216
21217        let mut config = Config::default();
21218        config.merge.mode = MergeMode::Local;
21219
21220        let mut state = RunState::new(
21221            repo.clone(),
21222            "main".to_owned(),
21223            "deadbeef".to_owned(),
21224            "task".to_owned(),
21225            config,
21226        );
21227        state.candidates = vec![Candidate {
21228            index: 0,
21229            label: 'A',
21230            agent: "alpha".to_owned(),
21231            branch: "does-not-exist".to_owned(),
21232            worktree: repo.clone(),
21233            summary: String::new(),
21234            stat: String::new(),
21235            files: 0,
21236            commits: 0,
21237            empty: false,
21238            failed: None,
21239            verified_noop: None,
21240            duration_ms: 0,
21241            folded: false,
21242        }];
21243        state.tally = Some(Tally {
21244            first_choice: BTreeMap::from([('A', 1)]),
21245            borda: BTreeMap::new(),
21246            winner: 'A',
21247            rankings: 1,
21248            unanimous_initial: true,
21249            deliberated: false,
21250            changed_votes: 0,
21251            unanimous_final: true,
21252            tie_break: None,
21253            judges: 0,
21254            present: 0,
21255            quorum: 0,
21256            met_quorum: true,
21257            uncontested: Some("only candidate A produced a change".to_owned()),
21258        });
21259        state.reviews = vec![ReviewRound {
21260            round: 1,
21261            head: "deadbeef".to_owned(),
21262            verified_head: None,
21263            verified_at: None,
21264            reviews: Vec::new(),
21265            e2e: Vec::new(),
21266            fix: None,
21267            blocking: 0,
21268            answered: 0,
21269            expected: 0,
21270            clean: true,
21271            verify_retried: false,
21272            e2e_deferred: false,
21273            e2e_defer_reason: None,
21274            progressed: false,
21275            vote_split: false,
21276            reconsideration: Vec::new(),
21277            verdict: None,
21278        }];
21279        // The point: `gate` has not recorded anything yet.
21280        state.gate = Vec::new();
21281        state.gate_ran = false;
21282        state.status = RunStatus::Gating;
21283
21284        let mut runner = Runner {
21285            state,
21286            roles: ResolvedRoles {
21287                implementers: Vec::new(),
21288                judges: Vec::new(),
21289                reviewers: Vec::new(),
21290                fixer: None,
21291                conductor: conductor(),
21292                implementer_roster: Vec::new(),
21293                judge_roster: Vec::new(),
21294                reviewer_roster: Vec::new(),
21295            },
21296            sem: Arc::new(Semaphore::new(1)),
21297            pause: Pause::new(),
21298            interrupt: Pause::new(),
21299        };
21300
21301        runner.merge().await.expect("merge");
21302
21303        assert!(
21304            runner.state.merge.is_none(),
21305            "an empty gate must never be read as a passing one: {:?}",
21306            runner.state.merge
21307        );
21308    }
21309
21310    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21311    /// commands configured and `merge.mode` is `none` (a review-only run).
21312    /// `gate` must still record a real attempt — zero commands, vacuously
21313    /// passed — rather than leaving `state.gate` empty in a way `merge`
21314    /// cannot tell apart from "never ran"; otherwise the run reaches
21315    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21316    #[tokio::test]
21317    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21318        let tmp = tempfile::tempdir().expect("tempdir");
21319        let repo = tmp.path().join("repo");
21320        std::fs::create_dir_all(&repo).unwrap();
21321        init_repo(&repo);
21322
21323        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21324        let config = Config::default();
21325
21326        let mut state = RunState::new(
21327            repo.clone(),
21328            "main".to_owned(),
21329            "deadbeef".to_owned(),
21330            "task".to_owned(),
21331            config,
21332        );
21333        state.candidates = vec![Candidate {
21334            index: 0,
21335            label: 'A',
21336            agent: "alpha".to_owned(),
21337            branch: "does-not-exist".to_owned(),
21338            worktree: repo.clone(),
21339            summary: String::new(),
21340            stat: String::new(),
21341            files: 0,
21342            commits: 0,
21343            empty: false,
21344            failed: None,
21345            verified_noop: None,
21346            duration_ms: 0,
21347            folded: false,
21348        }];
21349        state.tally = Some(Tally {
21350            first_choice: BTreeMap::from([('A', 1)]),
21351            borda: BTreeMap::new(),
21352            winner: 'A',
21353            rankings: 1,
21354            unanimous_initial: true,
21355            deliberated: false,
21356            changed_votes: 0,
21357            unanimous_final: true,
21358            tie_break: None,
21359            judges: 0,
21360            present: 0,
21361            quorum: 0,
21362            met_quorum: true,
21363            uncontested: Some("only candidate A produced a change".to_owned()),
21364        });
21365        state.reviews = vec![ReviewRound {
21366            round: 1,
21367            head: "deadbeef".to_owned(),
21368            verified_head: None,
21369            verified_at: None,
21370            reviews: Vec::new(),
21371            e2e: Vec::new(),
21372            fix: None,
21373            blocking: 0,
21374            answered: 0,
21375            expected: 0,
21376            clean: true,
21377            verify_retried: false,
21378            e2e_deferred: false,
21379            e2e_defer_reason: None,
21380            progressed: false,
21381            vote_split: false,
21382            reconsideration: Vec::new(),
21383            verdict: None,
21384        }];
21385
21386        let mut runner = Runner {
21387            state,
21388            roles: ResolvedRoles {
21389                implementers: Vec::new(),
21390                judges: Vec::new(),
21391                reviewers: Vec::new(),
21392                fixer: None,
21393                conductor: conductor(),
21394                implementer_roster: Vec::new(),
21395                judge_roster: Vec::new(),
21396                reviewer_roster: Vec::new(),
21397            },
21398            sem: Arc::new(Semaphore::new(1)),
21399            pause: Pause::new(),
21400            interrupt: Pause::new(),
21401        };
21402
21403        runner.gate().await.expect("gate");
21404        assert!(
21405            runner.state.gate_ran,
21406            "zero configured commands is still a real attempt, not an unrun gate"
21407        );
21408        assert!(runner.state.gate.is_empty());
21409        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21410        assert_ne!(
21411            runner.state.status,
21412            RunStatus::Blocked,
21413            "a gate with nothing to check must not read as failed"
21414        );
21415
21416        runner.merge().await.expect("merge");
21417        assert_eq!(
21418            runner.state.status,
21419            RunStatus::Ready,
21420            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21421        );
21422    }
21423
21424    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21425    /// `verify.gate` (so the e2e leg and the final gate never build against
21426    /// different directories). With zero `verify.gate` commands but a
21427    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21428    /// that lease before discovering it had nothing to run - so a repo with
21429    /// no gate commands could come back `resource_blocked` (and therefore
21430    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21431    /// cache, exactly the contention this run's own zero commands could
21432    /// never have touched. `gate` must recognise there is nothing to check
21433    /// before it ever asks for the lease.
21434    #[tokio::test]
21435    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21436        crate::run::pin_test_home();
21437        let home = crate::run::home();
21438
21439        let tmp = tempfile::tempdir().expect("tempdir");
21440        let repo = tmp.path().join("repo");
21441        std::fs::create_dir_all(&repo).unwrap();
21442        init_repo(&repo);
21443        // Unique to this test, so holding its lease cannot collide with
21444        // another test sharing the same process-wide `home`.
21445        let cache_dir = tmp.path().join("target");
21446
21447        let mut config = Config::default();
21448        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21449        // `verify.gate` stays empty (the default). Any accidental cache
21450        // acquisition must report contention immediately, regardless of how
21451        // long unrelated Git subprocesses take under parallel test load.
21452        config.graph.timeout_verify = Some(2);
21453        config.graph.timeout_resource_wait = 0;
21454
21455        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21456        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21457            .expect("no io error acquiring directly")
21458        {
21459            crate::cache::AcquireOutcome::Acquired(g) => g,
21460            crate::cache::AcquireOutcome::Busy(b) => {
21461                panic!("expected the direct acquire to win the lease first: {b:?}")
21462            }
21463        };
21464
21465        let mut state = RunState::new(
21466            repo.clone(),
21467            "main".to_owned(),
21468            "deadbeef".to_owned(),
21469            "task".to_owned(),
21470            config,
21471        );
21472        state.candidates = vec![Candidate {
21473            index: 0,
21474            label: 'A',
21475            agent: "alpha".to_owned(),
21476            branch: "does-not-exist".to_owned(),
21477            worktree: repo.clone(),
21478            summary: String::new(),
21479            stat: String::new(),
21480            files: 0,
21481            commits: 0,
21482            empty: false,
21483            failed: None,
21484            verified_noop: None,
21485            duration_ms: 0,
21486            folded: false,
21487        }];
21488        state.tally = Some(Tally {
21489            first_choice: BTreeMap::from([('A', 1)]),
21490            borda: BTreeMap::new(),
21491            winner: 'A',
21492            rankings: 1,
21493            unanimous_initial: true,
21494            deliberated: false,
21495            changed_votes: 0,
21496            unanimous_final: true,
21497            tie_break: None,
21498            judges: 0,
21499            present: 0,
21500            quorum: 0,
21501            met_quorum: true,
21502            uncontested: Some("only candidate A produced a change".to_owned()),
21503        });
21504        state.reviews = vec![ReviewRound {
21505            round: 1,
21506            head: "deadbeef".to_owned(),
21507            verified_head: None,
21508            verified_at: None,
21509            reviews: Vec::new(),
21510            e2e: Vec::new(),
21511            fix: None,
21512            blocking: 0,
21513            answered: 0,
21514            expected: 0,
21515            clean: true,
21516            verify_retried: false,
21517            e2e_deferred: false,
21518            e2e_defer_reason: None,
21519            progressed: false,
21520            vote_split: false,
21521            reconsideration: Vec::new(),
21522            verdict: None,
21523        }];
21524
21525        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21526        state.reviews[0].e2e = vec![CommandOutcome {
21527            command: state.config.verify.e2e[0].clone(),
21528            code: Some(0),
21529            output_tail: String::new(),
21530            duration_ms: 0,
21531            resource_blocked: false,
21532            ..Default::default()
21533        }];
21534        let mut runner = Runner {
21535            state,
21536            roles: ResolvedRoles {
21537                implementers: Vec::new(),
21538                judges: Vec::new(),
21539                reviewers: Vec::new(),
21540                fixer: None,
21541                conductor: conductor(),
21542                implementer_roster: Vec::new(),
21543                judge_roster: Vec::new(),
21544                reviewer_roster: Vec::new(),
21545            },
21546            sem: Arc::new(Semaphore::new(1)),
21547            pause: Pause::new(),
21548            interrupt: Pause::new(),
21549        };
21550
21551        runner.gate().await.expect("gate");
21552        assert!(runner.state.resource_block.is_none());
21553        assert!(
21554            !runner
21555                .state
21556                .events
21557                .iter()
21558                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21559            "a gate with nothing to run must never request the held cache lease"
21560        );
21561        assert!(
21562            runner.state.gate_ran,
21563            "zero commands is still a real, immediate attempt"
21564        );
21565        assert!(runner.state.gate.is_empty());
21566        assert_ne!(
21567            runner.state.status,
21568            RunStatus::Blocked,
21569            "must not read as resource-blocked on a lease it never asked for"
21570        );
21571    }
21572
21573    /// A separate process carries a live worker's environment throughout all
21574    /// verification entry points; the parallel harness never changes its env.
21575    #[cfg(unix)]
21576    #[tokio::test]
21577    async fn verification_is_standalone_inside_a_live_worker() {
21578        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21579        if std::env::var_os(CHILD).is_none() {
21580            let home = tempfile::tempdir().unwrap();
21581            let generation = crate::worker::pin_current(home.path()).unwrap();
21582            let output = std::process::Command::new(std::env::current_exe().unwrap())
21583                .args([
21584                    "--exact",
21585                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21586                    "--nocapture",
21587                ])
21588                .env(CHILD, "1")
21589                .env("MAGI_HOME", home.path())
21590                .env("MAGI_WORKER_HOME", home.path())
21591                .env("MAGI_WORKER_ID", "abcdef")
21592                .env("MAGI_WORKER_GENERATION", &generation.id)
21593                .env("MAGI_WORKER_EXE", &generation.executable)
21594                .env("MAGI_RUN", "verification-parent")
21595                .env("MAGI_NODE", "gate")
21596                .env("MAGI_SEAT", "worker-fixture")
21597                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21598                .env("MAGI_NO_AUTOUPDATE", "0")
21599                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21600                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21601                .env(
21602                    "VERIFY_EXPECT_TOOLCHAIN",
21603                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21604                )
21605                .env(
21606                    "VERIFY_EXPECT_CACHE",
21607                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21608                )
21609                .output()
21610                .unwrap();
21611            assert!(
21612                output.status.success()
21613                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21614                "{}\n{}",
21615                String::from_utf8_lossy(&output.stdout),
21616                String::from_utf8_lossy(&output.stderr)
21617            );
21618            return;
21619        }
21620        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21621        let home = crate::run::home();
21622        let directory = home.join("workers/jobs/abcdef");
21623        std::fs::create_dir_all(&directory).unwrap();
21624        let job = crate::worker::Job {
21625            id: "abcdef".into(),
21626            sequence: 1,
21627            kind: "task".into(),
21628            key: "task:verification".into(),
21629            payload: serde_json::json!({}),
21630            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21631            version: Some(env!("CARGO_PKG_VERSION").into()),
21632            status: crate::worker::Status::Running,
21633            result: None,
21634            pid: Some(std::process::id()),
21635            created_at: 0,
21636            finished_at: None,
21637        };
21638        std::fs::write(
21639            directory.join("job.json"),
21640            serde_json::to_vec(&job).unwrap(),
21641        )
21642        .unwrap();
21643        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21644        let assert_worker = || {
21645            assert_eq!(
21646                crate::worker::current_job(&home).unwrap().unwrap().id,
21647                job.id
21648            );
21649            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21650            assert_eq!(
21651                crate::worker::helper_executable(&home).unwrap(),
21652                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21653            );
21654            assert!(
21655                crate::updater::Checker::new(&crate::config::Update {
21656                    mode: crate::config::UpdateMode::Notify,
21657                    interval: None,
21658                    auto_restart: false,
21659                })
21660                .is_none(),
21661                "the driver remains pinned, even while tests are standalone"
21662            );
21663        };
21664        assert_worker();
21665        let repo = home.join("repo");
21666        std::fs::create_dir_all(&repo).unwrap();
21667        init_repo(&repo);
21668        // Keep storage, seat/control context, containment and tool lookup.
21669        // No inherited values (or credentials) are printed on success.
21670        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21671            test -z "${MAGI_WORKER_GENERATION+x}" &&
21672            test -z "${MAGI_WORKER_HOME+x}" &&
21673            test -z "${MAGI_WORKER_EXE+x}" &&
21674            test "$MAGI_HOME/repo" -ef . &&
21675            test "$MAGI_RUN" = verification-parent &&
21676            test "$MAGI_NODE" = gate &&
21677            test "$MAGI_SEAT" = worker-fixture &&
21678            test -n "$MAGI_PROCESS_OWNER" &&
21679            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21680            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21681            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21682            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21683        // Negative control: an ordinary child inherits the contamination.
21684        assert!(
21685            !std::process::Command::new("sh")
21686                .args(["-c", probe])
21687                .current_dir(&repo)
21688                .status()
21689                .unwrap()
21690                .success()
21691        );
21692        let unrelated_home = tempfile::tempdir().unwrap();
21693        assert!(
21694            crate::worker::current_job(unrelated_home.path()).is_err(),
21695            "an inherited worker id cannot be resolved in a unit fixture's home"
21696        );
21697        let mut runner = runner_at(RunStatus::Gating);
21698        runner.state.repo = repo.clone();
21699        runner.state.config.disk.min_free_bytes = 0;
21700        runner.state.config.coordination = crate::config::test_coordination();
21701        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21702        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21703        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21704        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21705        let winner = Candidate {
21706            index: 0,
21707            label: 'A',
21708            agent: "fixture".into(),
21709            branch: "main".into(),
21710            worktree: repo.clone(),
21711            summary: String::new(),
21712            stat: String::new(),
21713            files: 0,
21714            commits: 0,
21715            empty: false,
21716            failed: None,
21717            verified_noop: None,
21718            duration_ms: 0,
21719            folded: false,
21720        };
21721        let (e2e, retried, pids) = run_e2e_with_retry(
21722            &mut runner.state,
21723            &["sh".into(), "-c".into()],
21724            &[format!("{probe} && printf initial")],
21725            &repo,
21726            Duration::from_secs(10),
21727            "initial",
21728            None,
21729        )
21730        .await;
21731        assert!(!retried && pids.is_empty());
21732        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21733        assert_eq!(e2e[0].output_tail, "initial");
21734        let gate = runner.run_gate(&winner).await.unwrap();
21735        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21736        // An interrupted repair must recheck e2e from saved state. Landing
21737        // reuses that state and must run both pre-gate and gate again.
21738        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
21739            git::rev_parse(&repo, "HEAD").await.unwrap(),
21740            false,
21741            Vec::new(),
21742        ));
21743        runner.state.save().unwrap();
21744        let mut resumed = RunState::load(&runner.state.id).unwrap();
21745        let wait = crate::repo_lock::WaitPolicy::default();
21746        assert!(matches!(
21747            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21748                .await
21749                .unwrap(),
21750            GateFix::Retry
21751        ));
21752        let saved = RunState::load(&resumed.id).unwrap();
21753        let repair = saved.gate_repair_e2e.unwrap();
21754        assert!(repair.passed);
21755        assert_eq!(repair.outcomes.len(), 1);
21756        assert!(repair.outcomes[0].ok());
21757        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21758            .await
21759            .unwrap();
21760        assert_eq!(landing.len(), 1);
21761        assert!(landing[0].ok(), "{landing:?}");
21762        assert_eq!(
21763            std::fs::read_to_string(repo.join("phases")).unwrap(),
21764            "pre\ngate\ne2e\npre\ngate\n"
21765        );
21766        assert_worker();
21767    }
21768
21769    #[cfg(unix)]
21770    #[tokio::test]
21771    async fn verification_keeps_the_panic_and_the_full_output() {
21772        crate::run::pin_test_home();
21773        let tmp = tempfile::tempdir().unwrap();
21774        let mut config = Config::default();
21775        config.disk.min_free_bytes = 0;
21776        let mut state = RunState::new(
21777            tmp.path().to_owned(),
21778            "main".into(),
21779            "base".into(),
21780            "verification evidence".into(),
21781            config,
21782        );
21783        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21784                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21785                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21786        let mut names = Vec::new();
21787        for _ in 0..2 {
21788            let (outcomes, _) = run_commands(
21789                &mut state,
21790                "gate",
21791                "gate",
21792                0,
21793                &["sh".into(), "-c".into()],
21794                &[script.into()],
21795                tmp.path(),
21796                Duration::from_secs(60),
21797            )
21798            .await;
21799            let tail = &outcomes[0].output_tail;
21800            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21801            assert!(tail.contains("boom assertion"));
21802            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21803            let line = tail.lines().next().unwrap();
21804            names.push(line.to_owned());
21805        }
21806        assert_ne!(names[0], names[1], "the second run must not overwrite");
21807        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21808        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21809        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21810
21811        // Storage failures are evidence too; preserve the command's verdict.
21812        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21813        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21814        let (outcomes, _) = run_commands(
21815            &mut state,
21816            "gate",
21817            "gate",
21818            0,
21819            &["sh".into(), "-c".into()],
21820            &["echo failure-output; exit 7".into()],
21821            tmp.path(),
21822            Duration::from_secs(10),
21823        )
21824        .await;
21825        assert_eq!(outcomes[0].code, Some(7));
21826        assert!(state.events.iter().any(|e| {
21827            e.node == "gate" && e.message.contains("could not save the full gate output:")
21828        }));
21829    }
21830
21831    #[cfg(unix)]
21832    #[tokio::test]
21833    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21834        crate::run::pin_test_home();
21835        let tmp = tempfile::tempdir().unwrap();
21836        let mut config = Config::default();
21837        config.disk.min_free_bytes = 0;
21838        let mut state = RunState::new(
21839            tmp.path().to_owned(),
21840            "main".into(),
21841            "base".into(),
21842            "verification evidence".into(),
21843            config,
21844        );
21845        let (outcomes, pids) = run_commands(
21846            &mut state,
21847            "gate",
21848            "gate",
21849            1,
21850            &["sh".into(), "-c".into()],
21851            &[
21852                "printf before-timeout; exec sleep 30".into(),
21853                "kill -TERM $$".into(),
21854                "exit 7".into(),
21855                "printf success".into(),
21856            ],
21857            tmp.path(),
21858            Duration::from_secs(1),
21859        )
21860        .await;
21861        wait_for_timed_out_children_to_die(&pids).await;
21862        assert_eq!(
21863            pids.len(),
21864            1,
21865            "unleased timeout retains its death-check PID"
21866        );
21867        assert_eq!(outcomes.len(), 4);
21868        assert_eq!(outcomes[0].code, None);
21869        assert!(outcomes[0].output_tail.contains("before-timeout"));
21870        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21871        assert_eq!(outcomes[1].code, None);
21872        assert!(outcomes[1].output_tail.contains("command terminated:"));
21873        assert!(!outcomes[1].output_tail.contains("timed out"));
21874        assert_eq!(outcomes[2].code, Some(7));
21875        assert!(!outcomes[2].output_tail.contains("timed out"));
21876        assert_eq!(outcomes[3].code, Some(0));
21877        assert_eq!(outcomes[3].output_tail, "success");
21878        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21879    }
21880
21881    /// The addendum's second gap: a `verify.gate` command running for real
21882    /// wall-clock time had nothing at all to show for it in `active` before
21883    /// `run_commands` learned to record it — a run could sit in `Gating` for
21884    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21885    /// what was actually happening. Proven with a genuinely still-running
21886    /// command, not just a before/after check on the final state: a poller
21887    /// task reads the same `run.json` `gate()` is writing, the same way the
21888    /// phone or `magi show` would, while the shell command is still blocked
21889    /// on its own release marker.
21890    #[tokio::test]
21891    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21892        crate::run::pin_test_home();
21893
21894        let tmp = tempfile::tempdir().expect("tempdir");
21895        let repo = tmp.path().join("repo");
21896        std::fs::create_dir_all(&repo).unwrap();
21897        init_repo(&repo);
21898
21899        let mut config = Config::default();
21900        config.disk.min_free_bytes = 0;
21901        config.verify.gate = vec![
21902            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21903             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21904                .to_owned(),
21905        ];
21906
21907        let mut state = RunState::new(
21908            repo.clone(),
21909            "main".to_owned(),
21910            "deadbeef".to_owned(),
21911            "task".to_owned(),
21912            config,
21913        );
21914        let run_id = state.id.clone();
21915        state.candidates = vec![Candidate {
21916            index: 0,
21917            label: 'A',
21918            agent: "alpha".to_owned(),
21919            branch: "does-not-exist".to_owned(),
21920            worktree: repo.clone(),
21921            summary: String::new(),
21922            stat: String::new(),
21923            files: 0,
21924            commits: 0,
21925            empty: false,
21926            failed: None,
21927            verified_noop: None,
21928            duration_ms: 0,
21929            folded: false,
21930        }];
21931        state.tally = Some(Tally {
21932            first_choice: BTreeMap::from([('A', 1)]),
21933            borda: BTreeMap::new(),
21934            winner: 'A',
21935            rankings: 1,
21936            unanimous_initial: true,
21937            deliberated: false,
21938            changed_votes: 0,
21939            unanimous_final: true,
21940            tie_break: None,
21941            judges: 0,
21942            present: 0,
21943            quorum: 0,
21944            met_quorum: true,
21945            uncontested: Some("only candidate A produced a change".to_owned()),
21946        });
21947        state.reviews = vec![ReviewRound {
21948            round: 1,
21949            head: "deadbeef".to_owned(),
21950            verified_head: None,
21951            verified_at: None,
21952            reviews: Vec::new(),
21953            e2e: Vec::new(),
21954            fix: None,
21955            blocking: 0,
21956            answered: 0,
21957            expected: 0,
21958            clean: true,
21959            verify_retried: false,
21960            e2e_deferred: false,
21961            e2e_defer_reason: None,
21962            progressed: false,
21963            vote_split: false,
21964            reconsideration: Vec::new(),
21965            verdict: None,
21966        }];
21967
21968        let mut runner = Runner {
21969            state,
21970            roles: ResolvedRoles {
21971                implementers: Vec::new(),
21972                judges: Vec::new(),
21973                reviewers: Vec::new(),
21974                fixer: None,
21975                conductor: conductor(),
21976                implementer_roster: Vec::new(),
21977                judge_roster: Vec::new(),
21978                reviewer_roster: Vec::new(),
21979            },
21980            sem: Arc::new(Semaphore::new(1)),
21981            pause: Pause::new(),
21982            interrupt: Pause::new(),
21983        };
21984
21985        let started_marker = repo.join("started.marker");
21986        let release_marker = repo.join("release.marker");
21987        let observe = async {
21988            loop {
21989                if started_marker.exists()
21990                    && let Ok(s) = crate::run::RunState::load(&run_id)
21991                    && let Some(a) = s.active.get("gate")
21992                {
21993                    std::fs::write(&release_marker, b"go").expect("release marker");
21994                    break a.clone();
21995                }
21996                tokio::time::sleep(Duration::from_millis(50)).await;
21997            }
21998        };
21999        let captured = {
22000            let gate = runner.gate();
22001            tokio::pin!(gate);
22002            let captured = tokio::select! {
22003                observed = observe => observed,
22004                result = &mut gate => panic!(
22005                    "gate exited before its in-flight entry was observed: {result:?}"
22006                ),
22007            };
22008            gate.await.expect("gate");
22009            captured
22010        };
22011
22012        assert_eq!(captured.task.as_deref(), Some("gate"));
22013        assert_eq!(captured.node, "gate");
22014        assert_eq!(captured.index, Some(1));
22015        assert_eq!(captured.total, Some(1));
22016        assert!(
22017            captured
22018                .command
22019                .as_deref()
22020                .is_some_and(|c| c.contains("started.marker")),
22021            "{captured:?}"
22022        );
22023
22024        assert!(
22025            runner.state.active.is_empty(),
22026            "the entry must be cleared once the command actually finished: {:?}",
22027            runner.state.active
22028        );
22029        assert!(runner.state.gate_ran);
22030        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
22031    }
22032
22033    /// The hand-off over a blocking finding a reviewer rejected on leaves a
22034    /// record for `land`; one with only a Minor, or no reject, leaves none.
22035    #[tokio::test]
22036    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
22037        use crate::verdict::{Finding, ReviewVote, Severity};
22038        crate::run::pin_test_home();
22039        let tmp = tempfile::tempdir().expect("tempdir");
22040        let repo = tmp.path().join("repo");
22041        std::fs::create_dir_all(&repo).unwrap();
22042        init_repo(&repo);
22043
22044        for (severity, vote, expect) in [
22045            (Severity::Major, ReviewVote::Reject, true),
22046            (Severity::Minor, ReviewVote::Reject, false),
22047            (Severity::Major, ReviewVote::Approve, false),
22048        ] {
22049            let mut round = review_round(false, 1, 1, 1, false, true);
22050            round.reviews = vec![ReviewRecord {
22051                reviewer: 1,
22052                agent: "alpha".to_owned(),
22053                summary: String::new(),
22054                findings: vec![Finding {
22055                    id: "R1-1-1".to_owned(),
22056                    severity,
22057                    file: None,
22058                    line: None,
22059                    title: "t".to_owned(),
22060                    detail: String::new(),
22061                }],
22062                vote: Some(vote),
22063                failed: None,
22064                duration_ms: 0,
22065                attempts: 0,
22066            }];
22067            let mut state = RunState::new(
22068                repo.clone(),
22069                "main".to_owned(),
22070                "deadbeef".to_owned(),
22071                "task".to_owned(),
22072                Config::default(),
22073            );
22074            state.reviews = vec![round];
22075            let mut runner = Runner {
22076                state,
22077                roles: ResolvedRoles {
22078                    implementers: Vec::new(),
22079                    judges: Vec::new(),
22080                    reviewers: Vec::new(),
22081                    fixer: None,
22082                    conductor: conductor(),
22083                    implementer_roster: Vec::new(),
22084                    judge_roster: Vec::new(),
22085                    reviewer_roster: Vec::new(),
22086                },
22087                sem: Arc::new(Semaphore::new(1)),
22088                pause: Pause::new(),
22089                interrupt: Pause::new(),
22090            };
22091            let shell = runner.state.config.shell();
22092            runner
22093                .stop_reviewing("round budget spent", &shell, &repo)
22094                .await
22095                .expect("stop_reviewing");
22096            assert_eq!(runner.state.status, RunStatus::Gating);
22097            assert_eq!(
22098                runner.state.contested_handoff.is_some(),
22099                expect,
22100                "{severity:?} + {vote:?}"
22101            );
22102        }
22103    }
22104
22105    /// The shape the incident this whole fix responds to actually had: the
22106    /// round budget spent, the last round's own e2e blocked on the shared
22107    /// build cache (held here by a live pid — this test process — exactly
22108    /// `cache`'s own unit tests' pattern for "another owner, still alive"
22109    /// without forking a process). `stop_reviewing` must retry it — not
22110    /// silently leave the round looking untouched (the catch-up-only half of
22111    /// the bug), and not read the contention as a red `e2e` and block the
22112    /// run on it (the other half). Called directly, the same way
22113    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
22114    /// above exercises `gate`, so this never needs a real cargo build to
22115    /// reach: the lease is never released, so `with_cache_lease` never gets
22116    /// past acquiring it into anything that would need a real workspace.
22117    #[tokio::test]
22118    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
22119        crate::run::pin_test_home();
22120        let home = crate::run::home();
22121
22122        let tmp = tempfile::tempdir().expect("tempdir");
22123        let repo = tmp.path().join("repo");
22124        std::fs::create_dir_all(&repo).unwrap();
22125        init_repo(&repo);
22126        let head = crate::git::rev_parse(&repo, "HEAD")
22127            .await
22128            .expect("rev-parse");
22129        // Unique to this test, so holding its lease cannot collide with
22130        // another test sharing the same process-wide `home`.
22131        let cache_dir = tmp.path().join("target");
22132
22133        let mut config = Config::default();
22134        config.verify.e2e = vec![format!(
22135            "CARGO_TARGET_DIR='{}' test -f README.md",
22136            cache_dir.display()
22137        )];
22138        config.graph.review_rounds = 1;
22139        // Bounded so a regression that does start waiting fails the test in
22140        // seconds, not hangs it.
22141        config.graph.timeout_verify = Some(2);
22142        config.graph.timeout_resource_wait = 2;
22143
22144        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22145        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22146            .expect("no io error acquiring directly")
22147        {
22148            crate::cache::AcquireOutcome::Acquired(g) => g,
22149            crate::cache::AcquireOutcome::Busy(b) => {
22150                panic!("expected the direct acquire to win the lease first: {b:?}")
22151            }
22152        };
22153
22154        let mut state = RunState::new(
22155            repo.clone(),
22156            "main".to_owned(),
22157            head.clone(),
22158            "task".to_owned(),
22159            config,
22160        );
22161        state.candidates = vec![Candidate {
22162            index: 0,
22163            label: 'A',
22164            agent: "alpha".to_owned(),
22165            branch: "does-not-exist".to_owned(),
22166            worktree: repo.clone(),
22167            summary: String::new(),
22168            stat: String::new(),
22169            files: 0,
22170            commits: 0,
22171            empty: false,
22172            failed: None,
22173            verified_noop: None,
22174            duration_ms: 0,
22175            folded: false,
22176        }];
22177        state.tally = Some(Tally {
22178            first_choice: BTreeMap::from([('A', 1)]),
22179            borda: BTreeMap::new(),
22180            winner: 'A',
22181            rankings: 1,
22182            unanimous_initial: true,
22183            deliberated: false,
22184            changed_votes: 0,
22185            unanimous_final: true,
22186            tie_break: None,
22187            judges: 0,
22188            present: 0,
22189            quorum: 0,
22190            met_quorum: true,
22191            uncontested: Some("only candidate A produced a change".to_owned()),
22192        });
22193        // The round budget's last round, deferred: `needs_catchup_run`'s
22194        // other trigger. `stop_reviewing`'s retry machinery must treat this
22195        // exactly like a resource-blocked attempt once it actually runs.
22196        state.reviews = vec![ReviewRound {
22197            round: 1,
22198            head: head.clone(),
22199            verified_head: None,
22200            verified_at: None,
22201            reviews: Vec::new(),
22202            e2e: Vec::new(),
22203            fix: None,
22204            blocking: 1,
22205            answered: 1,
22206            expected: 1,
22207            clean: false,
22208            verify_retried: false,
22209            e2e_deferred: true,
22210            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
22211            progressed: false,
22212            vote_split: false,
22213            reconsideration: Vec::new(),
22214            verdict: None,
22215        }];
22216
22217        let mut runner = Runner {
22218            state,
22219            roles: ResolvedRoles {
22220                implementers: Vec::new(),
22221                judges: Vec::new(),
22222                reviewers: Vec::new(),
22223                fixer: None,
22224                conductor: conductor(),
22225                implementer_roster: Vec::new(),
22226                judge_roster: Vec::new(),
22227                reviewer_roster: Vec::new(),
22228            },
22229            sem: Arc::new(Semaphore::new(1)),
22230            pause: Pause::new(),
22231            interrupt: Pause::new(),
22232        };
22233
22234        let shell = runner.state.config.shell();
22235        runner
22236            .stop_reviewing("round budget spent", &shell, &repo)
22237            .await
22238            .expect("stop_reviewing");
22239
22240        let last = runner.state.reviews.last().expect("round record");
22241        assert_eq!(
22242            last.e2e_status(),
22243            E2eStatus::ResourceBlocked,
22244            "the shared cache is still held; the attempt must read as blocked, not deferred or \
22245             failed: {last:?}"
22246        );
22247        assert_eq!(
22248            last.verified_head.as_deref(),
22249            Some(head.as_str()),
22250            "which commit this attempt targeted is known even though nothing finished checking \
22251             it"
22252        );
22253        let first_attempt_at = last
22254            .verified_at
22255            .expect("when this attempt ran is known too");
22256        assert_ne!(
22257            runner.state.status,
22258            RunStatus::Blocked,
22259            "contention is evidence about the machine, not the patch — it must not settle the \
22260             run as blocked: {:?}",
22261            runner.state.status
22262        );
22263        assert!(
22264            !runner
22265                .state
22266                .events
22267                .iter()
22268                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
22269            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
22270            runner.state.events
22271        );
22272
22273        // The cache is still held: a later reentry must retry the same
22274        // round's verification again — not leave it looking exactly as
22275        // untouched as the first blocked attempt, which is indistinguishable
22276        // from never having tried again at all.
22277        runner
22278            .stop_reviewing("round budget spent", &shell, &repo)
22279            .await
22280            .expect("stop_reviewing retry");
22281        assert_eq!(
22282            runner.state.reviews.len(),
22283            1,
22284            "no new round was started: {:?}",
22285            runner.state.reviews
22286        );
22287        let last = runner.state.reviews.last().expect("round record");
22288        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22289        assert!(
22290            last.verified_at.expect("still known") > first_attempt_at,
22291            "a second reentry must be a fresh attempt, not a stale copy of the first"
22292        );
22293        assert_ne!(runner.state.status, RunStatus::Blocked);
22294
22295        held.release();
22296    }
22297
22298    #[cfg(unix)]
22299    #[tokio::test]
22300    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22301        ask_test_home();
22302        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22303            let tmp = tempfile::tempdir().unwrap();
22304            let repo = tmp.path().join("repo");
22305            std::fs::create_dir(&repo).unwrap();
22306            init_repo(&repo);
22307            let run_git = |args: &[&str]| {
22308                let out = std::process::Command::new("git")
22309                    .args(args)
22310                    .current_dir(&repo)
22311                    .output()
22312                    .unwrap();
22313                assert!(
22314                    out.status.success(),
22315                    "{args:?}: {}",
22316                    String::from_utf8_lossy(&out.stderr)
22317                );
22318            };
22319            let origin = tmp.path().join("origin.git");
22320            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22321            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22322            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22323            run_git(&["add", "spec.rs"]);
22324            run_git(&["commit", "-m", "initial spec"]);
22325            run_git(&["push", "origin", "main"]);
22326            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22327            run_git(&["checkout", "-b", "fix/review"]);
22328            std::fs::write(
22329                repo.join("check.rs"),
22330                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22331            )
22332            .unwrap();
22333            run_git(&["add", "check.rs"]);
22334            run_git(&["commit", "-m", "use spec"]);
22335            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22336            run_git(&["checkout", "main"]);
22337            std::fs::write(
22338                repo.join("spec.rs"),
22339                "struct AgentSpec { max_turn_secs: u64 }\n",
22340            )
22341            .unwrap();
22342            run_git(&["add", "spec.rs"]);
22343            run_git(&["commit", "-m", "extend spec"]);
22344            run_git(&["push", "origin", "main"]);
22345            run_git(&["checkout", "fix/review"]);
22346
22347            let mut runner = runner_at(RunStatus::Reviewing);
22348            runner.state.repo = repo.clone();
22349            runner.state.base_commit = base;
22350            runner.state.pr_head = Some("fix/review".into());
22351            runner.state.config.graph.review_rounds = max_rounds;
22352            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22353            runner.state.config.graph.sessions = false;
22354            runner.state.config.disk.min_free_bytes = 0;
22355            runner.state.config.verify.e2e =
22356                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22357            runner.state.candidates = vec![Candidate {
22358                index: 0,
22359                label: 'A',
22360                agent: "fixture".into(),
22361                branch: "fix/review".into(),
22362                worktree: repo.clone(),
22363                summary: String::new(),
22364                stat: String::new(),
22365                files: 1,
22366                commits: 1,
22367                empty: false,
22368                failed: None,
22369                verified_noop: None,
22370                duration_ms: 0,
22371                folded: false,
22372            }];
22373            runner.state.tally = Some(Tally {
22374                first_choice: BTreeMap::new(),
22375                borda: BTreeMap::new(),
22376                winner: 'A',
22377                rankings: 0,
22378                unanimous_initial: true,
22379                deliberated: false,
22380                changed_votes: 0,
22381                unanimous_final: true,
22382                tie_break: None,
22383                judges: 0,
22384                present: 0,
22385                quorum: 0,
22386                met_quorum: true,
22387                uncontested: Some("review-only".into()),
22388            });
22389            let mut last = review_round(false, 0, 1, 1, false, false);
22390            last.head = reviewed.clone();
22391            last.e2e_deferred = true;
22392            last.e2e[0].resource_blocked = true;
22393            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22394            if max_rounds == 1 {
22395                last.e2e.clear();
22396            }
22397            runner.state.reviews = vec![last];
22398            let calls = tmp.path().join("fix-calls");
22399            let mut fixer = spec("repair");
22400            fixer
22401                .env
22402                .insert("FIX_CALLS".into(), calls.display().to_string());
22403            fixer.command = vec!["sh".into(), "-c".into(), r#"
22404                echo fix >> "$FIX_CALLS"
22405                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22406                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22407                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22408                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22409            "#.into()];
22410            let mut reviewer = spec("reviewer");
22411            reviewer.command = vec![
22412                "sh".into(),
22413                "-c".into(),
22414                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22415                    .into(),
22416            ];
22417            runner.roles.fixer = Some(vec![fixer]);
22418            runner.roles.reviewers = vec![reviewer];
22419
22420            runner.sync_to_base().await.unwrap();
22421            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22422            assert_ne!(rebased, reviewed);
22423            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22424            if reentry {
22425                // Simulate a crash after catch-up evidence was saved but before
22426                // dispatching the fixer. No dedicated pending-repair field exists.
22427                let shell = runner.state.config.shell();
22428                runner
22429                    .stop_unresolved_review("deferred verification", &shell, &repo)
22430                    .await
22431                    .unwrap();
22432                assert!(runner.catchup_repairable());
22433                assert!(!calls.exists());
22434                runner.state = RunState::load(&runner.state.id).unwrap();
22435                assert!(runner.catchup_repairable());
22436            }
22437            runner.review_loop().await.unwrap();
22438            let first = &runner.state.reviews[0];
22439            assert_eq!(first.head, reviewed);
22440            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22441            assert!(
22442                first.verify_retried,
22443                "a reproduced build failure gets exactly one retry: {:?}",
22444                first.e2e
22445            );
22446            assert!(first.e2e[0].output_tail.contains("E0063"));
22447            assert!(!runner.catchup_repairable());
22448            if max_rounds == 2 {
22449                assert_eq!(
22450                    runner.state.status,
22451                    RunStatus::Gating,
22452                    "{}",
22453                    crate::report::run(&runner.state)
22454                );
22455                assert_eq!(runner.state.reviews.len(), 2);
22456                assert!(first.fix.as_ref().unwrap().committed);
22457                assert!(runner.state.reviews[1].clean);
22458                assert_eq!(
22459                    runner
22460                        .state
22461                        .reviews
22462                        .iter()
22463                        .filter(|r| r.fix.is_some())
22464                        .count(),
22465                    1
22466                );
22467                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22468                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22469            } else {
22470                assert_eq!(runner.state.status, RunStatus::Blocked);
22471                assert!(first.fix.is_none());
22472                assert!(!calls.exists());
22473                let recovery = crate::recovery::assess(
22474                    "prior",
22475                    Some(&runner.state),
22476                    &runner.landing_base(),
22477                    crate::recovery::Relation::Diverged,
22478                );
22479                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22480                let reasons = recovery.reasons.join("\n");
22481                assert!(
22482                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22483                    "{reasons}"
22484                );
22485                assert!(
22486                    reasons.contains("base sync to")
22487                        && reasons.contains("additional review is required"),
22488                    "{reasons}"
22489                );
22490            }
22491        }
22492    }
22493
22494    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22495    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22496    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22497    /// own top-of-function fast path (`review_conclusion`) correctly reads
22498    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22499    /// own `for` range is empty once the round budget is spent, so
22500    /// `review_loop` must retry the check itself rather than silently doing
22501    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22502    /// above exercises directly, but through `review_loop`'s own entry point
22503    /// this time, proving the wiring between the two rather than just the
22504    /// retry logic in isolation.
22505    #[tokio::test]
22506    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22507        crate::run::pin_test_home();
22508        let home = crate::run::home();
22509
22510        let tmp = tempfile::tempdir().expect("tempdir");
22511        let repo = tmp.path().join("repo");
22512        std::fs::create_dir_all(&repo).unwrap();
22513        init_repo(&repo);
22514        let head = crate::git::rev_parse(&repo, "HEAD")
22515            .await
22516            .expect("rev-parse");
22517        let cache_dir = tmp.path().join("target");
22518
22519        let mut config = Config::default();
22520        config.verify.e2e = vec![format!(
22521            "CARGO_TARGET_DIR='{}' test -f README.md",
22522            cache_dir.display()
22523        )];
22524        config.graph.review_rounds = 1;
22525        config.graph.timeout_verify = Some(2);
22526        config.graph.timeout_resource_wait = 2;
22527
22528        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22529        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22530            .expect("no io error acquiring directly")
22531        {
22532            crate::cache::AcquireOutcome::Acquired(g) => g,
22533            crate::cache::AcquireOutcome::Busy(b) => {
22534                panic!("expected the direct acquire to win the lease first: {b:?}")
22535            }
22536        };
22537
22538        let mut state = RunState::new(
22539            repo.clone(),
22540            "main".to_owned(),
22541            head.clone(),
22542            "task".to_owned(),
22543            config,
22544        );
22545        state.candidates = vec![Candidate {
22546            index: 0,
22547            label: 'A',
22548            agent: "alpha".to_owned(),
22549            branch: "does-not-exist".to_owned(),
22550            worktree: repo.clone(),
22551            summary: String::new(),
22552            stat: String::new(),
22553            files: 0,
22554            commits: 0,
22555            empty: false,
22556            failed: None,
22557            verified_noop: None,
22558            duration_ms: 0,
22559            folded: false,
22560        }];
22561        state.tally = Some(Tally {
22562            first_choice: BTreeMap::from([('A', 1)]),
22563            borda: BTreeMap::new(),
22564            winner: 'A',
22565            rankings: 1,
22566            unanimous_initial: true,
22567            deliberated: false,
22568            changed_votes: 0,
22569            unanimous_final: true,
22570            tie_break: None,
22571            judges: 0,
22572            present: 0,
22573            quorum: 0,
22574            met_quorum: true,
22575            uncontested: Some("only candidate A produced a change".to_owned()),
22576        });
22577        // The exact shape a prior process's `stop_reviewing` would have left
22578        // on disk: the round budget's last round, a real attempt already
22579        // made and already resource-blocked.
22580        state.reviews = vec![ReviewRound {
22581            round: 1,
22582            head: head.clone(),
22583            verified_head: Some(head.clone()),
22584            verified_at: Some(jiff::Timestamp::now()),
22585            reviews: Vec::new(),
22586            e2e: vec![CommandOutcome {
22587                command: format!(
22588                    "CARGO_TARGET_DIR='{}' test -f README.md",
22589                    cache_dir.display()
22590                ),
22591                code: None,
22592                output_tail: "waiting for the shared build cache".to_owned(),
22593                duration_ms: 0,
22594                resource_blocked: true,
22595                ..Default::default()
22596            }],
22597            fix: None,
22598            blocking: 1,
22599            answered: 1,
22600            expected: 1,
22601            clean: false,
22602            verify_retried: false,
22603            e2e_deferred: false,
22604            e2e_defer_reason: None,
22605            progressed: false,
22606            vote_split: false,
22607            reconsideration: Vec::new(),
22608            verdict: None,
22609        }];
22610
22611        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22612        let mut runner = Runner {
22613            state,
22614            roles: ResolvedRoles {
22615                implementers: Vec::new(),
22616                judges: Vec::new(),
22617                reviewers: Vec::new(),
22618                fixer: None,
22619                conductor: conductor(),
22620                implementer_roster: Vec::new(),
22621                judge_roster: Vec::new(),
22622                reviewer_roster: Vec::new(),
22623            },
22624            sem: Arc::new(Semaphore::new(1)),
22625            pause: Pause::new(),
22626            interrupt: Pause::new(),
22627        };
22628
22629        // The lease is still held throughout, so this reentry's own retry is
22630        // also contended — proving `review_loop` actually tried again (not
22631        // that it happened to succeed) is what the timestamp comparison
22632        // below is for.
22633        runner.review_loop().await.expect("review_loop");
22634
22635        assert_eq!(
22636            runner.state.reviews.len(),
22637            1,
22638            "no new round was started on top of the unresolved one: {:?}",
22639            runner.state.reviews
22640        );
22641        let last = &runner.state.reviews[0];
22642        assert_eq!(
22643            last.e2e_status(),
22644            E2eStatus::ResourceBlocked,
22645            "still contended: {last:?}"
22646        );
22647        assert!(
22648            last.verified_at.expect("still known") > first_attempt_at,
22649            "review_loop must have actually retried the check, not left it exactly as found"
22650        );
22651        assert_ne!(
22652            runner.state.status,
22653            RunStatus::Blocked,
22654            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22655            runner.state.status
22656        );
22657
22658        held.release();
22659    }
22660
22661    #[tokio::test]
22662    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22663        crate::run::pin_test_home();
22664        for status in [RunStatus::Blocked, RunStatus::Gating] {
22665            let mut runner = runner_at(status);
22666            runner.state.config.graph.land = true;
22667            runner.state.gate_ran = true;
22668            runner.state.merge = Some(MergeOutcome {
22669                mode: MergeMode::Pr,
22670                ok: false,
22671                detail: "the fixer produced no commit".into(),
22672                empty: false,
22673            });
22674            let url = "https://example.invalid/o/r/pull/1";
22675            runner.state.pr = Some(crate::run::PrRecord {
22676                url: url.into(),
22677                number: 1,
22678                state: "open".into(),
22679                checks: "red".into(),
22680                round: 1,
22681                rounds: 1,
22682                red_at_merge: Vec::new(),
22683            });
22684            runner.state.save().unwrap();
22685            // The nonexistent repository makes observation fail before a forge
22686            // command can run. We still must reach land, rather than silently
22687            // return from the graph with its old gate and merge records.
22688            runner.execute_graph().await.unwrap();
22689            assert_eq!(runner.state.status, RunStatus::Blocked);
22690            assert!(runner.state.land_sync_pending);
22691            assert!(runner.state.events.iter().any(|event|
22692                event.node == "land" && event.message == format!("watching {url}")));
22693            assert_eq!(
22694                runner.state.merge.as_ref().unwrap().detail,
22695                "the fixer produced no commit"
22696            );
22697        }
22698    }
22699
22700    #[tokio::test]
22701    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22702        crate::run::pin_test_home();
22703        let tmp = tempfile::tempdir().expect("tempdir");
22704        let repo = tmp.path().join("repo");
22705        std::fs::create_dir_all(&repo).unwrap();
22706        init_repo(&repo);
22707
22708        let mut config = Config::default();
22709        config.merge.mode = MergeMode::Pr;
22710        config.graph.land = true;
22711        config.graph.land_approval = false;
22712
22713        let mut state = RunState::new(
22714            repo.clone(),
22715            "main".to_owned(),
22716            "deadbeef".to_owned(),
22717            "task".to_owned(),
22718            config,
22719        );
22720        state.candidates = vec![Candidate {
22721            index: 0,
22722            label: 'A',
22723            agent: "alpha".to_owned(),
22724            branch: "does-not-exist".to_owned(),
22725            worktree: repo.clone(),
22726            summary: String::new(),
22727            stat: String::new(),
22728            files: 0,
22729            commits: 0,
22730            empty: false,
22731            failed: None,
22732            verified_noop: None,
22733            duration_ms: 0,
22734            folded: false,
22735        }];
22736        state.tally = Some(Tally {
22737            first_choice: BTreeMap::from([('A', 1)]),
22738            borda: BTreeMap::new(),
22739            winner: 'A',
22740            rankings: 1,
22741            unanimous_initial: true,
22742            deliberated: false,
22743            changed_votes: 0,
22744            unanimous_final: true,
22745            tie_break: None,
22746            judges: 0,
22747            present: 0,
22748            quorum: 0,
22749            met_quorum: true,
22750            uncontested: Some("only candidate A produced a change".to_owned()),
22751        });
22752        state.reviews = vec![ReviewRound {
22753            round: 1,
22754            head: "deadbeef".to_owned(),
22755            verified_head: None,
22756            verified_at: None,
22757            reviews: Vec::new(),
22758            e2e: Vec::new(),
22759            fix: None,
22760            blocking: 0,
22761            answered: 0,
22762            expected: 0,
22763            clean: true,
22764            verify_retried: false,
22765            e2e_deferred: false,
22766            e2e_defer_reason: None,
22767            progressed: false,
22768            vote_split: false,
22769            reconsideration: Vec::new(),
22770            verdict: None,
22771        }];
22772        state.gate = vec![CommandOutcome {
22773            command: "test".to_owned(),
22774            code: Some(0),
22775            output_tail: String::new(),
22776            duration_ms: 0,
22777            resource_blocked: false,
22778            ..Default::default()
22779        }];
22780        state.gate_ran = true;
22781        // A first pass through `merge` already pushed and opened this pull
22782        // request; `status` is `Landing` because a previous call into `land`
22783        // parked or was interrupted before it reached a terminal outcome.
22784        state.status = RunStatus::Landing;
22785        state.merge = Some(MergeOutcome {
22786            mode: MergeMode::Pr,
22787            ok: true,
22788            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22789            empty: false,
22790        });
22791
22792        // The Landing-resume shortcut calls `run_land` directly rather than
22793        // through `merge`, which is exactly the call site that used to skip
22794        // `settle_questions` - see the fixture below.
22795        ask_test_home();
22796        // A real resume loads a persisted run; driver ownership is checked
22797        // against that record before the Landing shortcut is entered.
22798        state.save().expect("save landing run");
22799        let store = ask::Questions::open();
22800        let q = ask_open_question(&store, &state.id);
22801
22802        let mut runner = Runner {
22803            state,
22804            roles: ResolvedRoles {
22805                implementers: Vec::new(),
22806                judges: Vec::new(),
22807                reviewers: Vec::new(),
22808                fixer: None,
22809                conductor: conductor(),
22810                implementer_roster: Vec::new(),
22811                judge_roster: Vec::new(),
22812                reviewer_roster: Vec::new(),
22813            },
22814            sem: Arc::new(Semaphore::new(1)),
22815            pause: Pause::new(),
22816            interrupt: Pause::new(),
22817        };
22818
22819        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22820        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22821        // exactly because `review_loop` would otherwise clobber the marker
22822        // first.
22823        runner.execute().await.expect("execute");
22824
22825        assert_eq!(
22826            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22827            Some("https://example.invalid/x/y/pull/1"),
22828            "reentry must not push again or open a second pull request over the \
22829             one `land` is already watching"
22830        );
22831        assert_ne!(
22832            runner.state.status,
22833            RunStatus::Landing,
22834            "land could not actually reach the fake pull request, so it must \
22835             have given up rather than left the run silently parked forever"
22836        );
22837        // `land` could not reach the fake pull request, so it gave up into
22838        // `Blocked` - still resumable, so the question must not have been
22839        // swept just because this branch now also calls `settle_questions`.
22840        assert_eq!(runner.state.status, RunStatus::Blocked);
22841        assert!(
22842            store.get(&q.id).unwrap().status.open(),
22843            "Blocked is still alive; settle_questions must have been a no-op here"
22844        );
22845    }
22846
22847    fn state_with_round(round: ReviewRound) -> RunState {
22848        let mut s = RunState::new(
22849            PathBuf::from("/repo"),
22850            "main".to_owned(),
22851            "abc1234".to_owned(),
22852            "add retries".to_owned(),
22853            Config::default(),
22854        );
22855        s.reviews = vec![round];
22856        s
22857    }
22858
22859    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22860        crate::verdict::Finding {
22861            id: id.to_owned(),
22862            severity,
22863            file: None,
22864            line: None,
22865            title: title.to_owned(),
22866            detail: String::new(),
22867        }
22868    }
22869
22870    #[test]
22871    fn pr_body_names_open_findings_and_declined_ones() {
22872        let round = ReviewRound {
22873            round: 2,
22874            head: "deadbee".to_owned(),
22875            verified_head: None,
22876            verified_at: None,
22877            reviews: vec![ReviewRecord {
22878                attempts: 0,
22879                reviewer: 1,
22880                agent: "alpha".to_owned(),
22881                summary: String::new(),
22882                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22883                vote: None,
22884                failed: None,
22885                duration_ms: 0,
22886            }],
22887            e2e: vec![CommandOutcome {
22888                command: "cargo test".to_owned(),
22889                code: Some(0),
22890                output_tail: String::new(),
22891                duration_ms: 0,
22892                resource_blocked: false,
22893                ..Default::default()
22894            }],
22895            verify_retried: false,
22896            e2e_deferred: false,
22897            e2e_defer_reason: None,
22898            fix: Some(FixRecord {
22899                agent: "alpha".to_owned(),
22900                addressed: Vec::new(),
22901                rejected: vec![crate::verdict::Rejection {
22902                    id: "R1-1-1".to_owned(),
22903                    why: "not reachable from any caller".to_owned(),
22904                }],
22905                notes: String::new(),
22906                committed: true,
22907                failed: None,
22908                duration_ms: 0,
22909                continuation: None,
22910            }),
22911            blocking: 0,
22912            answered: 1,
22913            expected: 1,
22914            clean: false,
22915            progressed: true,
22916            vote_split: false,
22917            reconsideration: Vec::new(),
22918            verdict: None,
22919        };
22920        let state = state_with_round(round);
22921        let body = pr_message(&state, 'A').body;
22922
22923        assert!(body.contains("add retries"), "the task must still be there");
22924        assert!(body.contains("R2-1-1"), "{body}");
22925        assert!(!body.contains("unused import"), "{body}");
22926        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22927        assert!(
22928            !body.contains("not reachable from any caller"),
22929            "the reason it was declined: {body}"
22930        );
22931    }
22932
22933    #[test]
22934    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22935        let round = ReviewRound {
22936            round: 1,
22937            head: "deadbee".to_owned(),
22938            verified_head: None,
22939            verified_at: None,
22940            reviews: vec![ReviewRecord {
22941                attempts: 0,
22942                reviewer: 1,
22943                agent: "alpha".to_owned(),
22944                summary: String::new(),
22945                findings: Vec::new(),
22946                vote: None,
22947                failed: None,
22948                duration_ms: 0,
22949            }],
22950            e2e: Vec::new(),
22951            verify_retried: false,
22952            e2e_deferred: false,
22953            e2e_defer_reason: None,
22954            fix: None,
22955            blocking: 0,
22956            answered: 1,
22957            expected: 1,
22958            clean: true,
22959            progressed: false,
22960            vote_split: false,
22961            reconsideration: Vec::new(),
22962            verdict: None,
22963        };
22964        let state = state_with_round(round);
22965        let body = pr_message(&state, 'A').body;
22966        assert!(!body.contains("Open review findings"), "{body}");
22967        assert!(!body.contains("Declined"), "{body}");
22968    }
22969
22970    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22971        let mut state = RunState::new(
22972            PathBuf::from("/repo"),
22973            "main".to_owned(),
22974            "abc1234".to_owned(),
22975            instruction.to_owned(),
22976            Config::default(),
22977        );
22978        // These fixtures test execution flow, independent of host disk capacity.
22979        state.config.disk.min_free_bytes = 0;
22980        state.candidates.push(Candidate {
22981            index: 0,
22982            label: 'A',
22983            agent: "alpha".to_owned(),
22984            branch: "magi/x/A".to_owned(),
22985            worktree: PathBuf::from("/wt"),
22986            summary: summary.to_owned(),
22987            stat: String::new(),
22988            files: 1,
22989            commits: 1,
22990            empty: false,
22991            failed: None,
22992            verified_noop: None,
22993            folded: false,
22994            duration_ms: 0,
22995        });
22996        state
22997    }
22998
22999    fn review_state(subjects: &[&str]) -> RunState {
23000        let mut state = state_with_summary(
23001            "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",
23002            "",
23003        );
23004        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23005        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
23006        state
23007    }
23008
23009    /// A branch rebased onto a main that moved past the recorded
23010    /// `base_commit` is titled from its own first commit, never main's.
23011    #[tokio::test]
23012    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
23013        ask_test_home();
23014        let tmp = tempfile::tempdir().unwrap();
23015        let repo = tmp.path().join("repo");
23016        std::fs::create_dir_all(&repo).unwrap();
23017        init_repo(&repo);
23018        let origin = tmp.path().join("origin.git");
23019        let g = |dir: &Path, args: &[&str]| {
23020            let out = std::process::Command::new("git")
23021                .args(args)
23022                .current_dir(dir)
23023                .quiet()
23024                .output()
23025                .expect("spawn git");
23026            assert!(
23027                out.status.success(),
23028                "git {args:?}: {}",
23029                String::from_utf8_lossy(&out.stderr)
23030            );
23031        };
23032        g(
23033            tmp.path(),
23034            &[
23035                "clone",
23036                "--bare",
23037                "-q",
23038                repo.to_str().unwrap(),
23039                origin.to_str().unwrap(),
23040            ],
23041        );
23042        g(
23043            &repo,
23044            &["remote", "add", "origin", origin.to_str().unwrap()],
23045        );
23046        let c1 = git::rev_parse(&repo, "main").await.unwrap();
23047
23048        // Main moves on; the branch is built on top of the new main.
23049        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
23050        g(&repo, &["add", "-A"]);
23051        g(
23052            &repo,
23053            &["commit", "-q", "-m", "chore(deps): update a crate"],
23054        );
23055        g(&repo, &["push", "-q", "origin", "main"]);
23056        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
23057        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23058        g(&repo, &["add", "-A"]);
23059        g(
23060            &repo,
23061            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
23062        );
23063        g(&repo, &["checkout", "-q", "main"]);
23064
23065        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
23066        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
23067        // Without a readable tracking ref the recorded base's merge base is used.
23068        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
23069        assert_eq!(fallback, c1);
23070
23071        let mut state = review_state(&[
23072            "chore(deps): update a crate",
23073            "fix(daemon): apply a chosen action",
23074        ]);
23075        state.repo = repo.clone();
23076        state.base_branch = "main".to_owned();
23077        state.base_commit = c1;
23078        refresh_reviewed_commits(&mut state, "feat/own").await;
23079        assert_eq!(
23080            state.reviewed_commits,
23081            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
23082        );
23083        assert_eq!(
23084            review_title(&state).as_deref(),
23085            Some("fix(daemon): apply a chosen action")
23086        );
23087        assert_eq!(
23088            leaked_subjects(&state, "feat/own").await,
23089            Some(vec!["chore(deps): update a crate".to_owned()])
23090        );
23091        // A stale tracking ref is still used when the fetch fails, but the
23092        // leak list is withheld.
23093        state.config.merge.remote = "nowhere".to_owned();
23094        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
23095    }
23096
23097    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
23098    /// with `origin/main` one commit behind it, and a summarizing agent that
23099    /// prints whatever `reply` holds.
23100    struct SummaryFixture {
23101        _tmp: tempfile::TempDir,
23102        repo: PathBuf,
23103        reply: PathBuf,
23104        runner: Runner,
23105    }
23106
23107    fn summary_fixture() -> SummaryFixture {
23108        ask_test_home();
23109        let tmp = tempfile::tempdir().unwrap();
23110        let repo = tmp.path().join("repo");
23111        std::fs::create_dir_all(&repo).unwrap();
23112        init_repo(&repo);
23113        let origin = tmp.path().join("origin.git");
23114        let g = |args: &[&str]| {
23115            let out = std::process::Command::new("git")
23116                .args(args)
23117                .current_dir(&repo)
23118                .quiet()
23119                .output()
23120                .expect("spawn git");
23121            assert!(
23122                out.status.success(),
23123                "git {args:?}: {}",
23124                String::from_utf8_lossy(&out.stderr)
23125            );
23126        };
23127        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
23128        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
23129        g(&["push", "-q", "origin", "main"]);
23130        g(&["checkout", "-q", "-b", "feat/own"]);
23131        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23132        g(&["add", "-A"]);
23133        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
23134        let reply = tmp.path().join("reply.txt");
23135        std::fs::write(
23136            &reply,
23137            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
23138        )
23139        .unwrap();
23140        let mut runner = runner_at(RunStatus::Gating);
23141        let mut state = review_state(&["feat(own): add the own file"]);
23142        state.repo = repo.clone();
23143        state.base_branch = "main".to_owned();
23144        state.candidates[0].branch = "feat/own".to_owned();
23145        state.candidates[0].worktree = repo.clone();
23146        let mut author = spec("alpha");
23147        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
23148        author
23149            .env
23150            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
23151        state.config.agents = vec![author];
23152        runner.state = state;
23153        SummaryFixture {
23154            _tmp: tmp,
23155            repo,
23156            reply,
23157            runner,
23158        }
23159    }
23160
23161    async fn posted(f: &mut SummaryFixture) -> PrMessage {
23162        let winner = f.runner.state.candidates[0].clone();
23163        f.runner
23164            .guarded_pr_message(&winner, None, true)
23165            .await
23166            .unwrap()
23167            .expect("an English description never parks")
23168    }
23169
23170    fn clean_round_with_minor_findings() -> ReviewRound {
23171        let mut round = passing_round(2, None);
23172        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
23173        round.reviews = vec![ReviewRecord {
23174            attempts: 0,
23175            reviewer: 1,
23176            agent: "alpha".into(),
23177            summary: "内部レビュー".into(),
23178            findings: vec![
23179                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
23180                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
23181            ],
23182            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
23183            failed: None,
23184            duration_ms: 0,
23185        }];
23186        round
23187    }
23188
23189    #[tokio::test]
23190    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
23191        for review_only in [false, true] {
23192            let mut f = summary_fixture();
23193            if !review_only {
23194                f.runner.state.candidates[0].agent = "alpha".into();
23195            }
23196            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
23197            assert!(f.runner.state.reviews[0].clean);
23198            assert!(f.runner.state.reviews[0].fix.is_none());
23199            assert!(f.runner.state.open_findings().is_empty());
23200            assert_eq!(
23201                crate::pr_outcome::required_finding_ids(&f.runner.state),
23202                ["R2-1-1", "R2-1-2"]
23203            );
23204            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23205            let evidence = crate::pr_outcome::summary_evidence(
23206                &f.runner.state,
23207                crate::pr_outcome::FinalHead::At(&head),
23208            );
23209            assert!(
23210                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
23211            );
23212            // The ordinary reply omits both IDs: no cached description is adopted.
23213            let omitted = posted(&mut f).await;
23214            assert!(omitted.body.contains("No description"));
23215            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
23216            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
23217            assert!(f.runner.state.change_summary.is_none());
23218            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();
23219            let described = posted(&mut f).await;
23220            assert!(described.body.contains("improve documentation for callers"));
23221            assert!(described.body.contains("remaining edge case"));
23222            assert!(described.body.contains("## Open review findings"));
23223            assert!(!described.body.contains("未修正"));
23224        }
23225    }
23226
23227    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
23228        let mut f = summary_fixture();
23229        if !review_only {
23230            f.runner.state.candidates[0].agent = "alpha".into();
23231        }
23232        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23233        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
23234        fixed
23235            .fix
23236            .as_mut()
23237            .unwrap()
23238            .rejected
23239            .push(crate::verdict::Rejection {
23240                id: "R1-1-1".into(),
23241                why: "呼び出されないコードのため辞退".into(),
23242            });
23243        let mut clean = clean_round_with_minor_findings();
23244        clean.verified_head = Some(head.clone());
23245        f.runner.state.reviews = vec![fixed, clean];
23246        ok_gate(&mut f.runner.state, Some(&head));
23247        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
23248        f.runner.state.config.agents.push(scripted("beta", reply));
23249        f.runner.state.config.roles.language_judge =
23250            Some(crate::config::AgentChoice::One("beta".into()));
23251        f
23252    }
23253
23254    #[tokio::test]
23255    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
23256        for review_only in [false, true] {
23257            let mut f = rewrite_fixture_with_findings(review_only,
23258                "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;
23259            let m = posted(&mut f).await;
23260            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23261            let expected =
23262                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
23263            assert!(m.body.contains(&expected));
23264            assert!(m.body.contains("## Review rounds"));
23265            assert!(
23266                m.body
23267                    .contains("Gate (`verify.gate`): passed on the final commit")
23268            );
23269            assert!(
23270                m.body
23271                    .contains("Tests (`verify.e2e`): passed on the final commit")
23272            );
23273            let c = f.runner.state.change_summary.as_ref().unwrap();
23274            assert!(
23275                m.body
23276                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
23277            );
23278            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23279            assert!(crate::pr_outcome::covers_required_findings(
23280                &f.runner.state,
23281                &m.body
23282            ));
23283            assert!(m.body.contains("documentation remains incomplete"));
23284            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23285            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23286            assert!(f.runner.state.github_text.is_none());
23287        }
23288    }
23289
23290    #[tokio::test]
23291    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23292        for review_only in [false, true] {
23293            for reply in [
23294                "TITLE: fix: public description\nA short English description.",
23295                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23296            ] {
23297                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23298                let winner = f.runner.state.candidates[0].clone();
23299                let posted = f
23300                    .runner
23301                    .guarded_pr_message(&winner, None, true)
23302                    .await
23303                    .unwrap();
23304                assert!(posted.is_none());
23305                assert!(f.runner.state.parked);
23306                let withheld = f.runner.state.github_text.as_ref().unwrap();
23307                assert!(
23308                    withheld.rewrite.is_none(),
23309                    "an incomplete rewrite must not be selectable"
23310                );
23311                let q = ask::Questions::open()
23312                    .get(withheld.question.as_ref().unwrap())
23313                    .unwrap();
23314                assert!(
23315                    !q.choices
23316                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23317                );
23318                assert!(
23319                    q.detail.contains("R1-1-1")
23320                        && q.detail.contains("R2-1-1")
23321                        && q.detail.contains("R2-1-2")
23322                );
23323            }
23324        }
23325    }
23326
23327    #[tokio::test]
23328    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23329        for review_only in [false, true] {
23330            let mut f = summary_fixture();
23331            if !review_only {
23332                f.runner.state.candidates[0].agent = "alpha".into();
23333            }
23334            f.runner.state.instruction = "内部タスクの説明".into();
23335            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23336            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23337            f.runner.state.reviews = vec![
23338                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23339                round_with_notes(2, Some("二回目の内部修正報告です。")),
23340                passing_round(3, Some(&head)),
23341            ];
23342            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23343            ok_gate(&mut f.runner.state, Some(&head));
23344            let captured = f.repo.join("public-prompt.txt");
23345            let author = &mut f.runner.state.config.agents[0];
23346            author.command = vec![
23347                "sh".into(),
23348                "-c".into(),
23349                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23350            ];
23351            author.env.insert(
23352                "PROMPT_FILE".into(),
23353                captured.to_string_lossy().into_owned(),
23354            );
23355            let m = posted(&mut f).await;
23356            assert!(m.body.contains("Adds `own.txt`"));
23357            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23358            assert!(m.body.contains("R1-1-1"));
23359            assert!(
23360                m.body
23361                    .contains("Gate (`verify.gate`): passed on the final commit")
23362            );
23363            assert!(
23364                m.body
23365                    .contains("Tests (`verify.e2e`): passed on the final commit")
23366            );
23367            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23368            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23369            let prompt = std::fs::read_to_string(captured).unwrap();
23370            assert!(prompt.contains(&format!(
23371                "git diff {} {head}",
23372                f.runner.state.change_summary.as_ref().unwrap().base
23373            )));
23374            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23375            assert_eq!(
23376                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23377                "二回目の内部修正報告です。"
23378            );
23379        }
23380    }
23381
23382    #[tokio::test]
23383    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23384        for review_only in [false, true] {
23385            let mut f = summary_fixture();
23386            if !review_only {
23387                f.runner.state.candidates[0].agent = "alpha".into();
23388            }
23389            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23390            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23391            std::fs::write(&f.reply, "no usable description").unwrap();
23392            let failed = posted(&mut f).await;
23393            assert!(
23394                failed
23395                    .body
23396                    .contains("No description of what this change does could be generated")
23397            );
23398            assert!(failed.body.is_ascii());
23399            assert!(f.runner.state.github_text.is_none());
23400            assert!(f.runner.state.change_summary.is_none());
23401            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23402            let evidence = crate::pr_outcome::summary_evidence(
23403                &f.runner.state,
23404                crate::pr_outcome::FinalHead::At(&head),
23405            );
23406            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23407            assert!(
23408                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23409                    .exists()
23410            );
23411            f.runner.state =
23412                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23413            std::fs::write(
23414                &f.reply,
23415                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23416            )
23417            .unwrap();
23418            let retried = posted(&mut f).await;
23419            assert!(retried.body.contains("Adds the committed own file."));
23420            assert_eq!(
23421                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23422                "日本語の修正報告"
23423            );
23424        }
23425    }
23426
23427    #[tokio::test]
23428    async fn same_head_verification_and_findings_invalidate_public_prose() {
23429        let mut f = summary_fixture();
23430        posted(&mut f).await;
23431        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23432        let original = f
23433            .runner
23434            .state
23435            .change_summary
23436            .as_ref()
23437            .unwrap()
23438            .evidence
23439            .clone();
23440        ok_gate(&mut f.runner.state, Some(&head));
23441        std::fs::write(
23442            &f.reply,
23443            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23444        )
23445        .unwrap();
23446        let verified = posted(&mut f).await;
23447        assert!(verified.body.contains("now verified"));
23448        assert_ne!(
23449            f.runner.state.change_summary.as_ref().unwrap().evidence,
23450            original
23451        );
23452        let mut round = round_with_notes(1, Some("内部報告"));
23453        round.reviews.push(ReviewRecord {
23454            attempts: 0,
23455            reviewer: 1,
23456            agent: "alpha".into(),
23457            summary: "内部レビュー".into(),
23458            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23459            vote: None,
23460            failed: None,
23461            duration_ms: 0,
23462        });
23463        round
23464            .fix
23465            .as_mut()
23466            .unwrap()
23467            .rejected
23468            .push(crate::verdict::Rejection {
23469                id: "R1-1-1".into(),
23470                why: "呼び出し元から到達できない".into(),
23471            });
23472        f.runner.state.reviews = vec![round];
23473        // A description omitting the required ID is unusable, even with a title.
23474        let omitted = posted(&mut f).await;
23475        assert!(omitted.body.contains("No description"));
23476        assert!(omitted.body.contains("R1-1-1"));
23477        assert!(!omitted.body.contains("到達"));
23478        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();
23479        let described = posted(&mut f).await;
23480        assert!(described.body.contains("unreachable from callers"));
23481        assert!(described.body.contains("R1-1-1"));
23482        assert!(!described.body.contains("到達"));
23483        let evidence = f
23484            .runner
23485            .state
23486            .change_summary
23487            .as_ref()
23488            .unwrap()
23489            .evidence
23490            .clone();
23491        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23492        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23493        assert!(posted(&mut f).await.body.contains("rationale updated"));
23494        assert_ne!(
23495            f.runner.state.change_summary.as_ref().unwrap().evidence,
23496            evidence
23497        );
23498        // Old serialized summaries have no evidence fingerprint and must regenerate.
23499        f.runner
23500            .state
23501            .change_summary
23502            .as_mut()
23503            .unwrap()
23504            .evidence
23505            .clear();
23506        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23507        assert!(posted(&mut f).await.body.contains("current specification"));
23508    }
23509
23510    #[tokio::test]
23511    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23512        let mut f = summary_fixture();
23513        let m = posted(&mut f).await;
23514        assert_eq!(m.title, "feat(own): add the own file");
23515        assert!(
23516            m.body
23517                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23518            "{}",
23519            m.body
23520        );
23521        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23522        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23523        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23524        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23525        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23526        let kept = f.runner.state.change_summary.as_ref().unwrap();
23527        assert_eq!(
23528            (kept.head.as_str(), kept.base.as_str()),
23529            (head.as_str(), base.as_str())
23530        );
23531        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23532    }
23533
23534    #[tokio::test]
23535    async fn review_only_summary_receives_the_configured_github_language() {
23536        let mut f = summary_fixture();
23537        f.runner.state.config.graph.github_language = "ja".into();
23538        let captured = f.repo.join("summary-prompt.txt");
23539        let author = &mut f.runner.state.config.agents[0];
23540        author.command = vec![
23541            "sh".into(),
23542            "-c".into(),
23543            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23544        ];
23545        author.env.insert(
23546            "PROMPT_FILE".into(),
23547            captured.to_string_lossy().into_owned(),
23548        );
23549        std::fs::write(
23550            &f.reply,
23551            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23552        )
23553        .unwrap();
23554        let m = posted(&mut f).await;
23555        let prompt = std::fs::read_to_string(captured).unwrap();
23556        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23557        assert!(!prompt.contains("in English"));
23558        assert_eq!(m.title, "feat(own): ファイルを追加");
23559        assert!(m.body.contains("own.txt を追加します。"));
23560    }
23561
23562    #[tokio::test]
23563    async fn review_fixes_come_after_the_whole_change_summary() {
23564        let mut f = summary_fixture();
23565        f.runner.state.reviews = vec![
23566            round_with_notes(1, Some("handled the PATH case")),
23567            round_with_notes(2, None),
23568        ];
23569        let m = posted(&mut f).await;
23570        let summary = m.body.find("## Summary").expect("summary");
23571        let fixes = m.body.find("## Review rounds").expect("review rounds");
23572        assert!(summary < fixes, "{}", m.body);
23573        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23574        assert!(m.body.contains("## Final verification"), "{}", m.body);
23575    }
23576
23577    #[tokio::test]
23578    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23579        let mut f = summary_fixture();
23580        let first = posted(&mut f).await;
23581        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23582        // The same head reuses the record: a different reply is not read.
23583        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23584        let again = posted(&mut f).await;
23585        assert_eq!((again.title, again.body), (first.title, first.body));
23586
23587        let g = |args: &[&str]| {
23588            let out = std::process::Command::new("git")
23589                .args(args)
23590                .current_dir(&f.repo)
23591                .quiet()
23592                .output()
23593                .expect("spawn git");
23594            assert!(out.status.success(), "git {args:?}");
23595        };
23596        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23597        g(&["add", "-A"]);
23598        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23599        let second = posted(&mut f).await;
23600        let kept = f.runner.state.change_summary.clone().unwrap();
23601        assert_ne!(kept.head, first_head);
23602        assert!(second.body.contains("Not read yet."), "{}", second.body);
23603        assert!(!second.body.contains("so the first summary is read"));
23604        assert_eq!(second.title, "feat(own): other");
23605    }
23606
23607    #[tokio::test]
23608    async fn an_unavailable_summary_is_stated_and_never_invented() {
23609        let mut f = summary_fixture();
23610        std::fs::write(&f.reply, "no title line here").unwrap();
23611        let m = posted(&mut f).await;
23612        assert!(
23613            m.body
23614                .contains("No description of what this change does could be generated"),
23615            "{}",
23616            m.body
23617        );
23618        assert!(m.body.contains("internal reports remain in local records"));
23619        assert!(f.runner.state.change_summary.is_none());
23620        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23621        // A preview asks nobody and claims nothing.
23622        let winner = f.runner.state.candidates[0].clone();
23623        let preview = f
23624            .runner
23625            .guarded_pr_message(&winner, None, false)
23626            .await
23627            .unwrap()
23628            .unwrap();
23629        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23630    }
23631
23632    #[test]
23633    fn pr_message_review_single_commit_uses_its_subject() {
23634        let state = review_state(&["feat(nats): per-role user"]);
23635        let m = pr_message(&state, 'A');
23636        assert_eq!(m.title, "feat(nats): per-role user");
23637        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23638        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23639    }
23640
23641    #[test]
23642    fn pr_message_review_multi_commit_takes_the_oldest() {
23643        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23644        let m = pr_message(&state, 'A');
23645        assert_eq!(m.title, "feat: the change");
23646        for s in ["feat: the change", "fix: typo", "fix: again"] {
23647            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23648        }
23649    }
23650
23651    #[test]
23652    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23653        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23654            let mut state = review_state(&[first, "fix: later fixup"]);
23655            state.candidates[0].branch = "機能/ログイン".to_owned();
23656            let m = pr_message(&state, 'A');
23657            assert!(
23658                m.title.starts_with("chore: land candidate A of run"),
23659                "{}",
23660                m.title
23661            );
23662        }
23663    }
23664
23665    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23666        BranchFacts {
23667            commits: commits
23668                .iter()
23669                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23670                .collect(),
23671            stat: stat.to_owned(),
23672        }
23673    }
23674
23675    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23676        let mut r = review_round(true, 0, 1, 1, true, true);
23677        r.round = round;
23678        r.fix = notes.map(|n| FixRecord {
23679            agent: "fixer".to_owned(),
23680            addressed: Vec::new(),
23681            rejected: Vec::new(),
23682            notes: n.to_owned(),
23683            committed: true,
23684            failed: None,
23685            duration_ms: 0,
23686            continuation: None,
23687        });
23688        r
23689    }
23690
23691    #[test]
23692    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23693        let state = review_state(&["ignored"]);
23694        let f = facts(
23695            &[
23696                (
23697                    "fix(login): resolve PATH on macOS",
23698                    "Login shells skip rc files.",
23699                ),
23700                ("fix: address review", ""),
23701            ],
23702            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23703        );
23704        let m = pr_message_with(&state, 'A', Some(&f));
23705        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23706        assert!(
23707            m.body
23708                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23709            "{}",
23710            m.body
23711        );
23712        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23713        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23714        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23715        for banned in [
23716            "Review the work already",
23717            "no task statement",
23718            "Original task",
23719        ] {
23720            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23721        }
23722        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23723    }
23724
23725    #[test]
23726    fn pr_message_review_truncates_a_huge_first_commit_body() {
23727        let state = review_state(&["ignored"]);
23728        let f = facts(
23729            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23730            "s",
23731        );
23732        let m = pr_message_with(&state, 'A', Some(&f));
23733        assert!(m.body.len() < 30_000, "{}", m.body.len());
23734        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23735        assert!(
23736            m.body.contains("- ... 1 more commit(s)"),
23737            "{}",
23738            m.body.len()
23739        );
23740        assert!(m.body.ends_with("magi:candidate-a\n"));
23741    }
23742
23743    #[test]
23744    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23745        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23746        assert_eq!(m.title, "feat: x");
23747        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23748        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23749        assert!(!m.body.contains("no task statement"), "{}", m.body);
23750    }
23751
23752    #[test]
23753    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23754        let mut state = review_state(&["日本語の件名"]);
23755        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23756        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23757        state.candidates[0].branch = "機能/ログイン".to_owned();
23758        assert!(
23759            pr_message(&state, 'A')
23760                .title
23761                .starts_with("chore: land candidate A")
23762        );
23763    }
23764
23765    #[test]
23766    fn pr_message_review_fixes_survive_a_clean_final_round() {
23767        let mut state = review_state(&["feat: x"]);
23768        state.reviews = vec![
23769            round_with_notes(1, Some("handled the PATH case")),
23770            round_with_notes(2, None),
23771        ];
23772        let body = pr_message(&state, 'A').body;
23773        assert!(
23774            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23775            "{body}"
23776        );
23777        assert!(body.contains("### Round 1"), "{body}");
23778
23779        state.reviews = vec![
23780            round_with_notes(1, Some("first fix")),
23781            round_with_notes(2, Some("")),
23782            round_with_notes(3, Some("second fix")),
23783            round_with_notes(4, None),
23784        ];
23785        let body = pr_message(&state, 'A').body;
23786        assert!(
23787            body.contains("### Round 1") && !body.contains("first fix"),
23788            "{body}"
23789        );
23790        assert!(
23791            body.contains("### Round 3") && !body.contains("second fix"),
23792            "{body}"
23793        );
23794        assert!(body.contains("### Round 2"), "{body}");
23795    }
23796
23797    const FINAL: &str = "abcdef1234567890";
23798
23799    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23800        let mut r = round_with_notes(round, None);
23801        r.verified_head = verified.map(str::to_owned);
23802        r
23803    }
23804
23805    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23806        state.gate = vec![CommandOutcome {
23807            command: "gate".to_owned(),
23808            code: Some(0),
23809            output_tail: String::new(),
23810            duration_ms: 0,
23811            resource_blocked: false,
23812            ..Default::default()
23813        }];
23814        state.gate_ran = true;
23815        state.gate_head = head.map(str::to_owned);
23816    }
23817
23818    fn body_at(state: &RunState) -> String {
23819        pr_message_raw(
23820            state,
23821            'A',
23822            None,
23823            crate::pr_outcome::FinalHead::At(FINAL),
23824            ChangeNote::NotAsked,
23825        )
23826        .body
23827    }
23828
23829    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23830
23831    #[test]
23832    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23833        let mut state = review_state(&["feat: x"]);
23834        state.reviews = vec![
23835            round_with_notes(1, Some(SANDBOXED)),
23836            passing_round(2, Some(FINAL)),
23837        ];
23838        ok_gate(&mut state, Some(FINAL));
23839        let body = body_at(&state);
23840        assert!(!body.contains("Handled the PATH case."), "{body}");
23841        assert!(!body.contains("could not commit"), "{body}");
23842        assert!(!body.contains("could not run"), "{body}");
23843        assert!(
23844            body.contains("The fix is committed on the branch"),
23845            "{body}"
23846        );
23847        assert!(!body.contains("sandbox"), "{body}");
23848        assert!(
23849            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23850            "{body}"
23851        );
23852        assert!(
23853            body.contains("Gate (`verify.gate`): passed on the final commit"),
23854            "{body}"
23855        );
23856        // The raw report is untouched in the record.
23857        assert!(
23858            state.reviews[0]
23859                .fix
23860                .as_ref()
23861                .unwrap()
23862                .notes
23863                .contains("could not commit")
23864        );
23865    }
23866
23867    #[test]
23868    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23869        let mut state = review_state(&["feat: x"]);
23870        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23871        r1.fix.as_mut().unwrap().committed = false;
23872        let mut r2 = passing_round(2, Some(FINAL));
23873        r2.e2e[0].code = Some(1);
23874        state.reviews = vec![r1, r2];
23875        let body = body_at(&state);
23876        assert!(!body.contains("could not commit"), "{body}");
23877        assert!(!body.contains("could not run"), "{body}");
23878        assert!(body.contains("This round produced no commit"), "{body}");
23879        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23880        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23881        assert!(!body.contains("passed"), "{body}");
23882    }
23883
23884    #[test]
23885    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23886        let mut state = review_state(&["feat: x"]);
23887        state.reviews = vec![
23888            round_with_notes(1, Some(SANDBOXED)),
23889            passing_round(2, Some("0123456789abcdef")),
23890        ];
23891        ok_gate(&mut state, Some("0123456789abcdef"));
23892        let body = body_at(&state);
23893        assert!(!body.contains("HTTP tests could not run"), "{body}");
23894        // The commit claim is still settled by the structured record.
23895        assert!(!body.contains("could not commit"), "{body}");
23896        assert!(
23897            body.contains("passed on an earlier commit (`0123456`)"),
23898            "{body}"
23899        );
23900        assert!(!body.contains("passed on the final commit"), "{body}");
23901
23902        // A gate recorded before `gate_head` existed is "not recorded".
23903        ok_gate(&mut state, None);
23904        let body = body_at(&state);
23905        assert!(
23906            body.contains("passed on a commit that was not recorded"),
23907            "{body}"
23908        );
23909    }
23910
23911    #[test]
23912    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23913        let state = state_with_summary(
23914            "add retries to the client",
23915            "TITLE: feat: retries\n\nDid it.",
23916        );
23917        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23918        assert_eq!(m.title, "feat: retries");
23919        assert!(
23920            m.body.contains("<summary>Original task</summary>"),
23921            "{}",
23922            m.body
23923        );
23924        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23925        assert!(
23926            m.body
23927                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23928            "{}",
23929            m.body
23930        );
23931    }
23932
23933    #[test]
23934    fn pr_message_review_bounds_a_long_english_subject() {
23935        let long = format!("feat: {}", "word ".repeat(100));
23936        let m = pr_message(&review_state(&[&long]), 'A');
23937        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23938        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23939    }
23940
23941    #[test]
23942    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23943        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23944        let m = pr_message(&state, 'A');
23945        assert_eq!(m.title, "add retries");
23946        assert!(m.body.contains("<summary>Original task</summary>"));
23947        assert!(!m.body.contains("Commits under review"));
23948        assert_eq!(landing_subject_source(&state), state.instruction);
23949    }
23950
23951    #[test]
23952    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23953        let state = review_state(&["feat: the change", "fix: typo"]);
23954        let source = landing_subject_source(&state);
23955        assert_eq!(land::merge_subject("", &source), "feat: the change");
23956        assert_eq!(
23957            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23958            "feat: the change"
23959        );
23960        // An operator's rename still wins.
23961        assert_eq!(
23962            land::merge_subject("feat: renamed by hand", &source),
23963            "feat: renamed by hand"
23964        );
23965        let blank = review_state(&["日本語"]);
23966        assert!(
23967            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23968        );
23969    }
23970
23971    #[test]
23972    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23973        let state = review_state(&["feat: the change"]);
23974        let source = landing_subject_source(&state);
23975        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23976        assert_eq!(
23977            land::merge_subject(landing_title(&state, old), &source),
23978            "feat: the change"
23979        );
23980        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23981        let task = state_with_summary("add retries", "");
23982        assert_eq!(landing_title(&task, old), old);
23983    }
23984
23985    #[test]
23986    fn pr_message_describes_the_change_not_the_task() {
23987        let state = state_with_summary(
23988            "今回やってほしいこと: results projector を直す",
23989            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23990        );
23991        let m = pr_message(&state, 'A');
23992        assert_eq!(m.title, "fix(web): batch the runs list reads");
23993        assert!(
23994            m.body.starts_with("## Summary\n\n- reads run.json once"),
23995            "{}",
23996            m.body
23997        );
23998        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23999        let task_at = m.body.find("今回やってほしいこと").unwrap();
24000        let details_at = m.body.find("<details>").unwrap();
24001        assert!(
24002            details_at < task_at,
24003            "the task lives inside <details>: {}",
24004            m.body
24005        );
24006        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
24007        assert!(m.body.contains("magi:candidate-a"));
24008    }
24009
24010    #[test]
24011    fn pr_message_falls_back_to_the_task_without_a_title_line() {
24012        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
24013        let m = pr_message(&state, 'A');
24014        assert_eq!(m.title, "add retries");
24015        assert!(
24016            m.body.contains("## Summary\n\n- did some things"),
24017            "{}",
24018            m.body
24019        );
24020
24021        let none = RunState::new(
24022            PathBuf::from("/repo"),
24023            "main".to_owned(),
24024            "abc1234".to_owned(),
24025            "add retries".to_owned(),
24026            Config::default(),
24027        );
24028        let m = pr_message(&none, 'A');
24029        assert_eq!(m.title, "add retries");
24030        assert!(!m.body.contains("## Summary"), "{}", m.body);
24031    }
24032
24033    #[test]
24034    fn pr_message_refuses_the_candidate_commit_subject() {
24035        for bad in [
24036            "TITLE: magi: candidate A (uncommitted work)",
24037            "TITLE: chore: stuff (uncommitted work)",
24038            "TITLE:   ",
24039        ] {
24040            let state = state_with_summary("add retries", bad);
24041            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
24042        }
24043    }
24044
24045    #[test]
24046    fn pr_message_bounds_a_very_long_task_and_title() {
24047        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
24048        let state = state_with_summary(&long, "- nothing");
24049        let m = pr_message(&state, 'A');
24050        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24051        assert!(!m.title.contains('\n'));
24052
24053        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
24054        let m = pr_message(&state, 'A');
24055        assert!(m.title.starts_with("feat: "));
24056        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24057        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
24058    }
24059
24060    fn long_title_of(instruction: &str) -> String {
24061        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
24062    }
24063
24064    #[test]
24065    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
24066        let first = "Make the landing path keep a readable title for long tasks";
24067        let line = format!(
24068            "{first}. {}",
24069            "And then keep going with more words ".repeat(20)
24070        );
24071        let t = long_title_of(&line);
24072        assert_eq!(t, first);
24073        assert!(!t.starts_with("chore: land"));
24074    }
24075
24076    #[test]
24077    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
24078        let line = "word ".repeat(200);
24079        let t = long_title_of(&line);
24080        assert!(t.ends_with("word..."), "{t}");
24081        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
24082    }
24083
24084    #[test]
24085    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
24086        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
24087            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
24088        }
24089    }
24090
24091    #[test]
24092    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
24093        let mut state = state_with_summary("再試行を追加する", "- nothing");
24094        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
24095        state.config.graph.github_language = "ja".into();
24096        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
24097    }
24098
24099    #[test]
24100    fn pr_message_title_limit_is_exact() {
24101        let at = "a".repeat(PR_TITLE_MAX);
24102        assert_eq!(long_title_of(&at), at);
24103        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
24104        assert!(over.ends_with("..."), "{over}");
24105        assert_eq!(over.chars().count(), PR_TITLE_MAX);
24106    }
24107
24108    #[test]
24109    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
24110        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
24111        let t = long_title_of(&line);
24112        assert!(t.ends_with("..."), "{t}");
24113        assert!(t.is_ascii(), "{t}");
24114    }
24115
24116    #[test]
24117    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
24118        let line = format!(
24119            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
24120            "plus more filler words ".repeat(20)
24121        );
24122        let t = long_title_of(&line);
24123        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
24124    }
24125
24126    #[test]
24127    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
24128        let line = format!("\n\n# {}", "title words ".repeat(40));
24129        let state = state_with_summary(&line, "- nothing");
24130        let m = pr_message(&state, 'A');
24131        assert!(m.title.starts_with("title words"), "{}", m.title);
24132        assert_eq!(
24133            land::merge_subject(&m.title, &landing_subject_source(&state)),
24134            m.title
24135        );
24136        // An operator's rename wins untouched.
24137        assert_eq!(
24138            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
24139            "feat: renamed by hand"
24140        );
24141    }
24142
24143    #[tokio::test]
24144    async fn github_text_rewrite_is_bounded_and_falls_back() {
24145        crate::run::pin_test_home();
24146        for (reply, accepted) in [
24147            (
24148                "TITLE: fix: retries\nAdd retries for failed requests.",
24149                true,
24150            ),
24151            (
24152                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
24153                false,
24154            ),
24155            (
24156                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
24157                true,
24158            ),
24159            (
24160                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
24161                true,
24162            ),
24163            (
24164                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
24165                true,
24166            ),
24167            (
24168                "TITLE: fix: retries\n日本語の説明です。 token=secret",
24169                false,
24170            ),
24171            ("TITLE: fix: retries\n", false),
24172        ] {
24173            let dir = tempfile::tempdir().unwrap();
24174            let mut runner = runner_at(RunStatus::Gating);
24175            runner.state = state_with_summary(
24176                "add retries",
24177                "TITLE: fix: retries\n日本語の説明を書きます。",
24178            );
24179            runner.state.repo = dir.path().to_owned();
24180            runner.state.candidates[0].worktree = dir.path().to_owned();
24181            let mut author = spec("alpha");
24182            author.command = vec![
24183                "sh".into(),
24184                "-c".into(),
24185                "printf '%s' \"$REWRITE_REPLY\"".into(),
24186            ];
24187            author.env.insert("REWRITE_REPLY".into(), reply.into());
24188            runner.state.config.agents = vec![author];
24189            seed_public_summary(&mut runner);
24190            let winner = runner.state.candidates[0].clone();
24191            let first = runner
24192                .guarded_pr_message(&winner, None, true)
24193                .await
24194                .unwrap();
24195            let message = if accepted {
24196                first.expect("a passing rewrite never asks")
24197            } else {
24198                // Withheld: the run parks on a question and posts nothing yet.
24199                assert!(first.is_none());
24200                assert!(runner.state.parked);
24201                let store = ask::Questions::open();
24202                let asked: Vec<_> = store
24203                    .list()
24204                    .into_iter()
24205                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24206                    .collect();
24207                assert_eq!(asked.len(), 1);
24208                assert!(!asked[0].detail.contains("secret"));
24209                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
24210                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
24211                assert_eq!(
24212                    asked[0]
24213                        .choices
24214                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
24215                    rewrite.is_some()
24216                );
24217                // Silence: the question lapses and the neutral text is used,
24218                // without a second rewrite call or a second question.
24219                store
24220                    .update(&asked[0].id, |q| {
24221                        q.abandon("test");
24222                        Ok(())
24223                    })
24224                    .unwrap();
24225                let again = runner
24226                    .guarded_pr_message(&winner, None, true)
24227                    .await
24228                    .unwrap()
24229                    .expect("an abandoned question falls back");
24230                let n = store
24231                    .list()
24232                    .into_iter()
24233                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24234                    .count();
24235                assert_eq!(n, 1, "asked once per rejected text");
24236                again
24237            };
24238            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
24239            assert!(!message.body.contains("secret"));
24240            assert!(!message.body.contains("prefix"));
24241            assert!(!message.title.contains("secret"));
24242            assert_eq!(
24243                message.body.contains("Add retries for failed requests."),
24244                accepted
24245            );
24246            assert_eq!(
24247                runner.state.seats["github-text-rewrite"].turns, 1,
24248                "only one rewrite invocation"
24249            );
24250            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
24251            if accepted {
24252                assert!(runner.state.github_text.is_none());
24253                assert!(!runner.state.parked);
24254                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
24255                assert!(message.body.contains("## Final verification"));
24256                assert!(message.body.contains("Evidence: final diff"));
24257                assert!(
24258                    message
24259                        .body
24260                        .contains(&format!("magi:run/{}", runner.state.id))
24261                );
24262            }
24263            if !accepted {
24264                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24265                assert!(
24266                    message
24267                        .body
24268                        .contains(&format!("magi:run/{}", runner.state.id))
24269                );
24270            }
24271        }
24272    }
24273
24274    fn scripted(id: &str, reply: &str) -> AgentSpec {
24275        let mut a = spec(id);
24276        a.command = vec![
24277            "sh".into(),
24278            "-c".into(),
24279            "printf '%s' \"$REWRITE_REPLY\"".into(),
24280        ];
24281        a.env.insert("REWRITE_REPLY".into(), reply.into());
24282        a
24283    }
24284
24285    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24286    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24287
24288    /// Gate tests inject generated public output, not internal reports.
24289    fn seed_public_summary(runner: &mut Runner) {
24290        let repo = &runner.state.repo;
24291        let g = |args: &[&str]| {
24292            let out = std::process::Command::new("git")
24293                .args(args)
24294                .current_dir(repo)
24295                .quiet()
24296                .output()
24297                .unwrap();
24298            assert!(out.status.success(), "git {args:?}");
24299            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24300        };
24301        g(&["init", "-q", "-b", "main"]);
24302        g(&[
24303            "-c",
24304            "user.name=Test",
24305            "-c",
24306            "user.email=test@example.invalid",
24307            "commit",
24308            "-q",
24309            "--allow-empty",
24310            "-m",
24311            "feat: fixture",
24312        ]);
24313        let head = g(&["rev-parse", "HEAD"]);
24314        g(&["update-ref", "refs/remotes/origin/main", &head]);
24315        let evidence = crate::pr_outcome::summary_evidence(
24316            &runner.state,
24317            crate::pr_outcome::FinalHead::At(&head),
24318        );
24319        let generated = &runner.state.candidates[0].summary;
24320        runner.state.change_summary = Some(crate::run::ChangeSummary {
24321            base: head.clone(),
24322            head,
24323            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24324            title: summary_title(generated).unwrap(),
24325            body: summary_without_title(generated),
24326        });
24327    }
24328
24329    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24330        let mut runner = runner_at(RunStatus::Gating);
24331        runner.state = state_with_summary("add retries", JA_SUMMARY);
24332        if review_only {
24333            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24334        }
24335        runner.state.repo = dir.to_owned();
24336        runner.state.candidates[0].worktree = dir.to_owned();
24337        runner.state.config.agents = agents;
24338        seed_public_summary(&mut runner);
24339        runner
24340    }
24341
24342    fn gate_questions(runner: &Runner) -> usize {
24343        ask::Questions::open()
24344            .list()
24345            .into_iter()
24346            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24347            .count()
24348    }
24349
24350    #[tokio::test]
24351    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24352        crate::run::pin_test_home();
24353        let dir = tempfile::tempdir().unwrap();
24354        let mut runner = rewrite_runner(
24355            dir.path(),
24356            true,
24357            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24358        );
24359        runner.state.config.roles.language_judge =
24360            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24361        let winner = runner.state.candidates[0].clone();
24362        let msg = runner
24363            .guarded_pr_message(&winner, None, true)
24364            .await
24365            .unwrap()
24366            .expect("an English rewrite posts without asking");
24367        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24368        assert!(msg.body.contains("<details>kept</details>"));
24369        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24370        assert_eq!(gate_questions(&runner), 0);
24371        assert!(runner.state.github_text.is_none());
24372        assert!(!runner.state.seats.contains_key("impl-A"));
24373        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24374    }
24375
24376    #[tokio::test]
24377    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24378        crate::run::pin_test_home();
24379        let dir = tempfile::tempdir().unwrap();
24380        let mut runner = rewrite_runner(
24381            dir.path(),
24382            false,
24383            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24384        );
24385        runner.state.config.roles.language_judge =
24386            Some(crate::config::AgentChoice::One("beta".into()));
24387        runner.state.seats.insert(
24388            "impl-A".into(),
24389            SeatState::new("impl-A", "alpha", runner.state.seed),
24390        );
24391        let winner = runner.state.candidates[0].clone();
24392        let msg = runner
24393            .guarded_pr_message(&winner, None, true)
24394            .await
24395            .unwrap()
24396            .expect("rewritten");
24397        assert!(msg.body.contains("<details>kept</details>"));
24398        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24399        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24400        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24401    }
24402
24403    #[tokio::test]
24404    async fn rewrite_reuses_a_resumable_implementer_session() {
24405        crate::run::pin_test_home();
24406        let dir = tempfile::tempdir().unwrap();
24407        let mut runner = rewrite_runner(
24408            dir.path(),
24409            false,
24410            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24411        );
24412        runner.state.config.roles.language_judge =
24413            Some(crate::config::AgentChoice::One("beta".into()));
24414        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24415        seat.turns = 1;
24416        runner.state.seats.insert("impl-A".into(), seat);
24417        let winner = runner.state.candidates[0].clone();
24418        runner
24419            .guarded_pr_message(&winner, None, true)
24420            .await
24421            .unwrap()
24422            .expect("rewritten");
24423        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24424        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24425    }
24426
24427    #[tokio::test]
24428    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24429        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24430        // session, was out of quota, and nothing else was asked.
24431        crate::run::pin_test_home();
24432        let dir = tempfile::tempdir().unwrap();
24433        let mut exhausted = spec("alpha");
24434        exhausted.command = vec!["false".into()];
24435        let mut runner = rewrite_runner(
24436            dir.path(),
24437            false,
24438            vec![exhausted, scripted("beta", EN_REWRITE)],
24439        );
24440        // The implementer's own agent is in the role too: it is not asked twice.
24441        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24442            "alpha".into(),
24443            "beta".into(),
24444        ]));
24445        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24446        seat.turns = 1;
24447        runner.state.seats.insert("impl-A".into(), seat);
24448        let winner = runner.state.candidates[0].clone();
24449        let msg = runner
24450            .guarded_pr_message(&winner, None, true)
24451            .await
24452            .unwrap()
24453            .expect("the role rewrites after the implementer fails");
24454        assert!(msg.body.contains("`src/net.rs`"));
24455        assert_eq!(
24456            runner.state.seats["impl-A"].turns, 2,
24457            "the implementer was tried once"
24458        );
24459        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24460        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24461    }
24462
24463    #[tokio::test]
24464    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24465        crate::run::pin_test_home();
24466        let dir = tempfile::tempdir().unwrap();
24467        let mut broken = spec("bad");
24468        broken.command = vec!["false".into()];
24469        let mut runner = rewrite_runner(
24470            dir.path(),
24471            true,
24472            vec![
24473                broken,
24474                scripted("noformat", "Add retries."),
24475                scripted("good", EN_REWRITE),
24476            ],
24477        );
24478        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24479            "bad".into(),
24480            "noformat".into(),
24481            "good".into(),
24482        ]));
24483        let winner = runner.state.candidates[0].clone();
24484        let msg = runner
24485            .guarded_pr_message(&winner, None, true)
24486            .await
24487            .unwrap()
24488            .expect("the third agent rewrites");
24489        assert!(msg.body.contains("`src/net.rs`"));
24490        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24491        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24492    }
24493
24494    #[tokio::test]
24495    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24496        crate::run::pin_test_home();
24497        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24498        for (agents, role, saved) in [
24499            (
24500                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24501                Some("beta"),
24502                true,
24503            ),
24504            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24505            (Vec::new(), None, false),
24506        ] {
24507            let dir = tempfile::tempdir().unwrap();
24508            let mut runner = rewrite_runner(dir.path(), true, agents);
24509            runner.state.config.roles.language_judge =
24510                role.map(|r| crate::config::AgentChoice::One(r.into()));
24511            let winner = runner.state.candidates[0].clone();
24512            let first = runner
24513                .guarded_pr_message(&winner, None, true)
24514                .await
24515                .unwrap();
24516            assert!(first.is_none(), "withheld text parks the run");
24517            assert!(runner.state.parked);
24518            assert_eq!(gate_questions(&runner), 1);
24519            let g = runner.state.github_text.as_ref().unwrap();
24520            assert_eq!(g.rewrite.is_some(), saved);
24521            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24522        }
24523    }
24524
24525    #[tokio::test]
24526    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24527        crate::run::pin_test_home();
24528        let dir = tempfile::tempdir().unwrap();
24529        let mut runner = runner_at(RunStatus::Gating);
24530        runner.state =
24531            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24532        runner.state.repo = dir.path().to_owned();
24533        runner.state.candidates[0].worktree = dir.path().to_owned();
24534        let mut author = spec("alpha");
24535        author.command = vec![
24536            "sh".into(),
24537            "-c".into(),
24538            "printf '%s' \"$REWRITE_REPLY\"".into(),
24539        ];
24540        author.env.insert(
24541            "REWRITE_REPLY".into(),
24542            format!(
24543                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24544                "English sentence. ".repeat(600)
24545            ),
24546        );
24547        runner.state.config.agents = vec![author];
24548        seed_public_summary(&mut runner);
24549        let winner = runner.state.candidates[0].clone();
24550        assert!(
24551            runner
24552                .guarded_pr_message(&winner, None, true)
24553                .await
24554                .unwrap()
24555                .is_none()
24556        );
24557        let record = runner.state.github_text.clone().unwrap();
24558        let rewrite = record.rewrite.clone().unwrap();
24559        assert_eq!(rewrite.failed, ["body-language"]);
24560        assert!(
24561            rewrite
24562                .body
24563                .ends_with(&format!("magi:run/{}", runner.state.id))
24564        );
24565        let store = ask::Questions::open();
24566        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24567        assert!(
24568            q.choices
24569                .contains(&crate::github_text::USE_REWRITE.to_owned())
24570        );
24571        for label in [
24572            "ORIGINAL",
24573            "FALLBACK",
24574            "REWRITE",
24575            "Rules still failed: body-language",
24576            "truncated",
24577        ] {
24578            assert!(q.detail.contains(label), "{label}");
24579        }
24580        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24581            &runner.state,
24582            &crate::github_text::artifact_name(&record.fingerprint),
24583        ))
24584        .unwrap();
24585        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24586        // Restart from serialized state, then retry after a bad owner title.
24587        runner.state =
24588            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24589        store
24590            .update(&q.id, |q| {
24591                q.say("まだ日本語")?;
24592                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24593            })
24594            .unwrap();
24595        assert!(
24596            runner
24597                .guarded_pr_message(&winner, None, true)
24598                .await
24599                .unwrap()
24600                .is_none()
24601        );
24602        let retry = runner.state.github_text.as_ref().unwrap();
24603        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24604        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24605        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24606        assert!(
24607            q.posting_comparison
24608                .as_ref()
24609                .unwrap()
24610                .matches_detail(&q.detail)
24611        );
24612        store
24613            .update(&q.id, |q| {
24614                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24615            })
24616            .unwrap();
24617        let message = runner
24618            .guarded_pr_message(&winner, None, true)
24619            .await
24620            .unwrap()
24621            .unwrap();
24622        assert_eq!(message.title, rewrite.title);
24623        assert_eq!(message.body, rewrite.body);
24624        assert_eq!(
24625            runner.state.github_text.as_ref().unwrap().choice,
24626            Some(GithubTextChoice::Rewrite)
24627        );
24628        let again = runner
24629            .guarded_pr_message(&winner, None, true)
24630            .await
24631            .unwrap()
24632            .unwrap();
24633        assert_eq!(again.title, message.title);
24634        assert_eq!(again.body, message.body);
24635        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24636        assert!(
24637            !runner
24638                .state
24639                .events
24640                .iter()
24641                .any(|e| e.message.contains(&rewrite.title)
24642                    || e.message.contains("English sentence."))
24643        );
24644    }
24645
24646    #[tokio::test]
24647    async fn historical_posting_reply_never_expires_into_fallback() {
24648        crate::run::pin_test_home();
24649        let dir = tempfile::tempdir().unwrap();
24650        let mut runner = runner_at(RunStatus::Gating);
24651        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24652        runner.state.repo = dir.path().to_owned();
24653        runner.state.candidates[0].worktree = dir.path().to_owned();
24654        seed_public_summary(&mut runner);
24655        let winner = runner.state.candidates[0].clone();
24656        assert!(
24657            runner
24658                .guarded_pr_message(&winner, None, true)
24659                .await
24660                .unwrap()
24661                .is_none()
24662        );
24663        let id = runner
24664            .state
24665            .github_text
24666            .as_ref()
24667            .unwrap()
24668            .question
24669            .clone()
24670            .unwrap();
24671        let store = ask::Questions::open();
24672        let mut q = store.get(&id).unwrap();
24673        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24674        q.answer(ask::Answer::Choice(
24675            crate::github_text::POST_ORIGINAL.into(),
24676        ))
24677        .unwrap();
24678        q.answer_delivered = true;
24679        store.put(&mut q).unwrap();
24680        let source = std::fs::read(store.path_of(&id)).unwrap();
24681        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24682        std::fs::create_dir_all(&migration).unwrap();
24683        std::fs::write(
24684            migration.join("state.json"),
24685            serde_json::to_vec(&serde_json::json!({
24686                "schema": 1, "sources": [id], "pending": [id]
24687            }))
24688            .unwrap(),
24689        )
24690        .unwrap();
24691        for _ in 0..2 {
24692            assert!(
24693                runner
24694                    .guarded_pr_message(&winner, None, true)
24695                    .await
24696                    .unwrap()
24697                    .is_none()
24698            );
24699            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24700            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24701        }
24702        let home = crate::run::home();
24703        crate::task_chat::sweep(
24704            &crate::queue::Queue::at(home.join("queue")),
24705            &crate::talk::Talks::at(home.join("talks")),
24706            &store,
24707            &home,
24708        );
24709        let outbox = crate::task_inquiry::Outbox::at(&home);
24710        outbox
24711            .update_decision(&id, |d| {
24712                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24713                d.source_answer_at = q.answered_at;
24714                Ok(true)
24715            })
24716            .unwrap();
24717        outbox
24718            .settle(
24719                &id,
24720                "owner-chat",
24721                "Owner confirms no publication remains necessary",
24722                None,
24723            )
24724            .unwrap();
24725        assert!(
24726            runner
24727                .guarded_pr_message(&winner, None, true)
24728                .await
24729                .unwrap()
24730                .is_none()
24731        );
24732        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24733        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24734    }
24735
24736    #[tokio::test]
24737    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24738        crate::run::pin_test_home();
24739        let dir = tempfile::tempdir().unwrap();
24740        let mut runner = runner_at(RunStatus::Gating);
24741        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24742        runner.state.repo = dir.path().to_owned();
24743        runner.state.candidates[0].worktree = dir.path().to_owned();
24744        seed_public_summary(&mut runner);
24745        let winner = runner.state.candidates[0].clone();
24746        assert!(
24747            runner
24748                .guarded_pr_message(&winner, None, true)
24749                .await
24750                .unwrap()
24751                .is_none()
24752        );
24753        let record = runner.state.github_text.as_ref().unwrap();
24754        assert!(record.rewrite.is_none());
24755        // Records written before the additive field deserialize with no rewrite.
24756        let mut old = serde_json::to_value(record).unwrap();
24757        old.as_object_mut().unwrap().remove("rewrite");
24758        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24759        assert!(old.rewrite.is_none());
24760        let id = record.question.clone().unwrap();
24761        ask::Questions::open()
24762            .update(&id, |q| {
24763                q.choices.push(crate::github_text::USE_REWRITE.into());
24764                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24765            })
24766            .unwrap();
24767        let message = runner
24768            .guarded_pr_message(&winner, None, true)
24769            .await
24770            .unwrap()
24771            .unwrap();
24772        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24773        assert_eq!(
24774            runner.state.github_text.as_ref().unwrap().choice,
24775            Some(GithubTextChoice::Fallback)
24776        );
24777    }
24778
24779    #[tokio::test]
24780    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24781        crate::run::pin_test_home();
24782        let dir = tempfile::tempdir().unwrap();
24783        let mut runner = runner_at(RunStatus::Gating);
24784        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24785        runner.state.repo = dir.path().to_owned();
24786        runner.state.candidates[0].worktree = dir.path().to_owned();
24787        seed_public_summary(&mut runner);
24788        let winner = runner.state.candidates[0].clone();
24789        assert!(
24790            runner
24791                .guarded_pr_message(&winner, None, true)
24792                .await
24793                .unwrap()
24794                .is_none()
24795        );
24796        let store = ask::Questions::open();
24797        let find = |run: &str| {
24798            store
24799                .list()
24800                .into_iter()
24801                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24802                .unwrap()
24803        };
24804        let run = runner.state.id.clone();
24805        let q = find(&run);
24806        let fp = runner
24807            .state
24808            .github_text
24809            .as_ref()
24810            .unwrap()
24811            .fingerprint
24812            .clone();
24813        let name = crate::github_text::artifact_name(&fp);
24814        let path = crate::run::artifact_path(&runner.state, &name);
24815        assert!(q.detail.contains(&path.display().to_string()));
24816        assert!(q.detail.contains("title-language: title"));
24817        let saved = std::fs::read_to_string(&path).expect("artifact written");
24818        assert!(saved.contains("日本語のタイトル"));
24819        assert!(q.cwd.is_none());
24820        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24821        // A bad replacement is refused and asked about once more.
24822        let say = |id: &str, text: &str, choice: &str| {
24823            store
24824                .update(id, |q| {
24825                    q.thread.push(ask::Turn {
24826                        who: ask::Who::Operator,
24827                        body: text.to_owned(),
24828                        at: jiff::Timestamp::now(),
24829                        note: None,
24830                    });
24831                    q.answer(ask::Answer::Choice(choice.to_owned()))
24832                })
24833                .unwrap();
24834        };
24835        say(&q.id, "まだ日本語", "use my text");
24836        assert!(
24837            runner
24838                .guarded_pr_message(&winner, None, true)
24839                .await
24840                .unwrap()
24841                .is_none()
24842        );
24843        let second = find(&run);
24844        assert_ne!(second.id, q.id);
24845        assert!(second.detail.contains("did not pass"));
24846        // The retry still compares the original text; the rejected
24847        // replacement is named by category only.
24848        assert!(second.detail.contains("日本語のタイトル"));
24849        assert!(!second.detail.contains("まだ日本語"));
24850        assert!(second.detail.contains(&path.display().to_string()));
24851        say(&second.id, "fix: retry failed requests", "use my text");
24852        let message = runner
24853            .guarded_pr_message(&winner, None, true)
24854            .await
24855            .unwrap()
24856            .expect("a vetted replacement is posted");
24857        assert_eq!(message.title, "fix: retry failed requests");
24858        assert_eq!(
24859            runner
24860                .state
24861                .github_text
24862                .as_ref()
24863                .unwrap()
24864                .chosen_title
24865                .as_deref(),
24866            Some("fix: retry failed requests")
24867        );
24868        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24869        // Resumed again: the saved decision is applied, nothing is re-asked.
24870        let again = runner
24871            .guarded_pr_message(&winner, None, true)
24872            .await
24873            .unwrap()
24874            .unwrap();
24875        assert_eq!(again.title, message.title);
24876        assert_eq!(
24877            store
24878                .list()
24879                .into_iter()
24880                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24881                .count(),
24882            2
24883        );
24884    }
24885
24886    #[test]
24887    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24888        // What magi itself writes stays English under any configured language,
24889        // so a future localisation of these headings fails here. (The agents'
24890        // own text is also checked by the posting gate.)
24891        let mut state = state_with_summary(
24892            "add retries",
24893            "TITLE: fix(web): batch reads\n- reads run.json once",
24894        );
24895        state.config.graph.language = "ja".to_owned();
24896        let m = pr_message(&state, 'A');
24897        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24898        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24899
24900        // The task is the operator's own text: it goes in untouched, and the
24901        // fallback title (no summary) may be in its language too.
24902        let task = "今回やってほしいこと: results projector を直す";
24903        let mut state = state_with_summary(task, "- no title line");
24904        state.config.graph.language = "ja".to_owned();
24905        let m = pr_message(&state, 'A');
24906        assert_eq!(
24907            m.title,
24908            format!("chore: land candidate A of run {}", state.id)
24909        );
24910        assert!(
24911            m.body.contains(&format!(
24912                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24913            )),
24914            "{}",
24915            m.body
24916        );
24917    }
24918
24919    #[test]
24920    fn pr_message_scrubs_home_paths_and_addresses() {
24921        let state = state_with_summary(
24922            "fix it in /Users/someone/src/x",
24923            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24924        );
24925        let m = pr_message(&state, 'A');
24926        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24927            assert!(!m.body.contains(leak), "{}", m.body);
24928        }
24929        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24930    }
24931
24932    #[test]
24933    fn pr_message_survives_a_task_that_closes_details() {
24934        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24935        let m = pr_message(&state, 'A');
24936        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24937    }
24938
24939    #[test]
24940    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24941        let cmd = manual_merge_command(
24942            MergeStyle::Squash,
24943            Path::new("/repo"),
24944            "b",
24945            "fix: \"quoted\" $(x) `y`\n\nbody",
24946        );
24947        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24948    }
24949
24950    #[test]
24951    fn manual_merge_command_matches_the_configured_style() {
24952        let repo = Path::new("/repo");
24953        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24954
24955        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24956        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24957
24958        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24959        assert_eq!(
24960            squash,
24961            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24962             \"Merge magi run 0832 (candidate A)\""
24963        );
24964
24965        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24966        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24967    }
24968
24969    #[test]
24970    fn a_nudge_gets_a_quarter_of_the_budget() {
24971        // The judge and implement budgets magi ships with.
24972        assert_eq!(retry_budget(secs(1200), true), secs(300));
24973        assert_eq!(retry_budget(secs(3600), true), secs(900));
24974    }
24975
24976    #[test]
24977    fn a_resent_prompt_keeps_the_whole_budget() {
24978        // The seat kept no context, so the retry is the original job again and
24979        // shortening it would only guarantee a second failure.
24980        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24981        assert_eq!(retry_budget(secs(60), false), secs(60));
24982    }
24983
24984    #[test]
24985    fn the_floor_never_exceeds_the_original_budget() {
24986        // A short configured timeout must not be *raised* by the floor: the
24987        // operator asked for a bound, and a retry may not outlast the attempt
24988        // it is retrying.
24989        assert_eq!(retry_budget(secs(60), true), secs(60));
24990        assert_eq!(retry_budget(secs(480), true), secs(120));
24991        assert_eq!(retry_budget(secs(0), true), secs(0));
24992    }
24993
24994    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24995        agent::CommandEvidence {
24996            id: "item1".to_owned(),
24997            description: "cargo test".to_owned(),
24998            exit_code,
24999            result_summary: String::new(),
25000            source: "codex".to_owned(),
25001        }
25002    }
25003
25004    #[test]
25005    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
25006        // No evidence is not the same fact as unconfirmed evidence: a
25007        // backend with no adapter, or a reply that ran no commands at all,
25008        // must not be misread as carrying a dangling job.
25009        assert!(!has_unconfirmed_command(&[]));
25010    }
25011
25012    #[test]
25013    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
25014        // Deliberately not a check on the exit code's *value*: a fixer
25015        // legitimately runs something that fails mid-iteration before it
25016        // succeeds, and that must never by itself reopen a valid report.
25017        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
25018        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
25019        assert!(!has_unconfirmed_command(&[
25020            evidence(Some(0)),
25021            evidence(Some(101))
25022        ]));
25023    }
25024
25025    #[test]
25026    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
25027        assert!(has_unconfirmed_command(&[
25028            evidence(Some(0)),
25029            evidence(None)
25030        ]));
25031    }
25032
25033    #[test]
25034    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
25035        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25036        assert_eq!(
25037            verified_noop_claim(true, &[], text).as_deref(),
25038            Some("already fixed by b32cfc4, on main.")
25039        );
25040    }
25041
25042    #[test]
25043    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
25044        // A timeout or a bad exit code reads as the ordinary loss it is,
25045        // whatever the reply's own prose claims.
25046        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25047        assert!(verified_noop_claim(false, &[], text).is_none());
25048    }
25049
25050    #[test]
25051    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
25052        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25053        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
25054        // A confirmed command alongside the marker is fine.
25055        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
25056    }
25057
25058    #[test]
25059    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
25060        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
25061    }
25062
25063    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
25064    /// pair, in order, labelled A, B, C, ...
25065    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
25066        runner.state.candidates = shape
25067            .iter()
25068            .enumerate()
25069            .map(|(i, &(empty, verified))| Candidate {
25070                index: i,
25071                label: (b'A' + i as u8) as char,
25072                agent: "sonnet".to_owned(),
25073                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
25074                worktree: PathBuf::from(format!("/wt/{i}")),
25075                summary: String::new(),
25076                stat: String::new(),
25077                files: 0,
25078                commits: 0,
25079                empty,
25080                failed: None,
25081                verified_noop: verified.map(str::to_owned),
25082                duration_ms: 0,
25083                folded: false,
25084            })
25085            .collect();
25086    }
25087
25088    #[test]
25089    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
25090        ask_test_home();
25091        let mut runner = runner_at(RunStatus::Implementing);
25092        set_candidates(
25093            &mut runner,
25094            &[
25095                (true, Some("already on main at b32cfc4")),
25096                (true, Some("same fix, see the existing test")),
25097            ],
25098        );
25099
25100        runner
25101            .after_implement()
25102            .expect("a verified no-op is not an error");
25103
25104        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
25105    }
25106
25107    #[test]
25108    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
25109        ask_test_home();
25110        let mut runner = runner_at(RunStatus::Implementing);
25111        // Candidate A declares a verified no-op; candidate B simply wrote
25112        // nothing and said nothing about why. One candidate's claim is not
25113        // the whole run's agreement.
25114        set_candidates(
25115            &mut runner,
25116            &[(true, Some("already on main at b32cfc4")), (true, None)],
25117        );
25118
25119        let err = runner
25120            .after_implement()
25121            .expect_err("an unverified empty candidate must still fail the run");
25122
25123        assert!(
25124            err.to_string().contains("no candidate produced a change"),
25125            "{err}"
25126        );
25127        assert_eq!(runner.state.status, RunStatus::Failed);
25128    }
25129
25130    #[test]
25131    fn after_implement_still_fails_an_ordinary_all_empty_run() {
25132        ask_test_home();
25133        let mut runner = runner_at(RunStatus::Implementing);
25134        set_candidates(&mut runner, &[(true, None), (true, None)]);
25135
25136        let err = runner
25137            .after_implement()
25138            .expect_err("no candidate declared anything; this is an ordinary failure");
25139
25140        assert!(
25141            err.to_string().contains("no candidate produced a change"),
25142            "{err}"
25143        );
25144        assert_eq!(runner.state.status, RunStatus::Failed);
25145    }
25146}
25147
25148/// A graft rollback whose restore could not be confirmed (see
25149/// [`Runner::graft`]).
25150#[derive(Debug)]
25151struct GraftRestoreFailed(String);
25152
25153impl std::fmt::Display for GraftRestoreFailed {
25154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25155        write!(
25156            f,
25157            "could not restore the winner to its pre-graft commit: {}",
25158            self.0
25159        )
25160    }
25161}
25162
25163impl std::error::Error for GraftRestoreFailed {}
25164
25165/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
25166/// not the agent: they never draw on an agent's own timeout, and running out of
25167/// them never reads as an agent failure.
25168#[cfg(test)]
25169mod resource_wait_tests {
25170    use super::*;
25171    use std::collections::BTreeMap;
25172
25173    fn sh(id: &str, script: &str) -> AgentSpec {
25174        AgentSpec {
25175            id: id.to_owned(),
25176            kind: crate::config::AgentKind::Command,
25177            model: None,
25178            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
25179            extra_args: Vec::new(),
25180            env: BTreeMap::new(),
25181            prompt_delivery: None,
25182            max_turn_secs: None,
25183        }
25184    }
25185
25186    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
25187        SeatJob {
25188            seat: SeatState::new("impl-A", &spec.id, 1),
25189            spec,
25190            cwd: dir.to_path_buf(),
25191            prompt: "do it".to_owned(),
25192            timeout,
25193            allow_write: true,
25194            sessions: false,
25195            artifacts: dir.join("art"),
25196            stem: "impl-A".to_owned(),
25197            handover: None,
25198        }
25199    }
25200
25201    fn state(resource_wait_secs: u64) -> RunState {
25202        let mut config = Config::default();
25203        config.graph.timeout_resource_wait = resource_wait_secs;
25204        RunState::new(
25205            PathBuf::from("/repo"),
25206            "main".to_owned(),
25207            "abc1234".to_owned(),
25208            "task".to_owned(),
25209            config,
25210        )
25211    }
25212
25213    fn hold(cache: &Path) -> crate::cache::Guard {
25214        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
25215        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
25216            crate::cache::AcquireOutcome::Acquired(g) => g,
25217            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
25218        }
25219    }
25220
25221    async fn run(
25222        jobs: Vec<SeatJob>,
25223        sem: Arc<Semaphore>,
25224        cache: Option<&Path>,
25225        st: &mut RunState,
25226    ) -> Vec<(usize, SeatState, AgentOutcome)> {
25227        let prompts = Prompts::default();
25228        let ctx = WaveCtx {
25229            run: "r",
25230            node: "implement",
25231            prompts: &prompts,
25232            cache,
25233            round: None,
25234            carry_seats: false,
25235            pauses: None,
25236        };
25237        wave(jobs, sem, &ctx, st, 0).await
25238    }
25239
25240    #[tokio::test]
25241    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
25242        crate::run::pin_test_home();
25243        let home = crate::run::home();
25244        let tmp = tempfile::tempdir().unwrap();
25245        let repo = tmp.path().join("repo");
25246        let checkout = tmp.path().join("checkout");
25247        std::fs::create_dir(&repo).unwrap();
25248        git::git(&repo, &["init"]).await.unwrap();
25249        git::git(
25250            &repo,
25251            &[
25252                "-c",
25253                "user.name=Fixture",
25254                "-c",
25255                "user.email=fixture@example.invalid",
25256                "commit",
25257                "--allow-empty",
25258                "-m",
25259                "initial",
25260            ],
25261        )
25262        .await
25263        .unwrap();
25264        git::worktree_add_detached(&repo, &checkout, "HEAD")
25265            .await
25266            .unwrap();
25267        let target = crate::build_target::resolve(&home, &checkout).unwrap();
25268        let target_lease = hold(&target);
25269        let shared = tmp.path().join("unrelated");
25270        let _shared_lease = hold(&shared);
25271        let mut st = state(0);
25272        st.repo = repo.clone();
25273        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
25274        st.config.verify.e2e = vec![format!(
25275            "CARGO_TARGET_DIR='{}' cargo test",
25276            git::path_arg(&shared)
25277        )];
25278        let config = tmp.path().join("config.toml");
25279        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
25280        let prompts = Prompts::default();
25281        let run_id = st.id.clone();
25282        let ctx = WaveCtx {
25283            run: &run_id,
25284            node: "implement",
25285            prompts: &prompts,
25286            cache: None,
25287            round: None,
25288            carry_seats: false,
25289            pauses: None,
25290        };
25291        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
25292        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
25293        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25294        assert_eq!(results[0].1.turns, 0);
25295        let saved = RunState::load_under(&run_id, &home).unwrap();
25296        let block = saved.resource_block.unwrap();
25297        assert!(matches!(
25298            block.cause,
25299            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
25300                if actual == &target
25301        ));
25302        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
25303        let mut task = crate::queue::Task::new(
25304            "build".into(),
25305            "build".into(),
25306            repo,
25307            crate::queue::Source::Human,
25308        );
25309        task.runs.push(run_id);
25310        task.hold_machine(Some(format!(
25311            "{}{}",
25312            crate::cache::RESOURCE_HOLD,
25313            block.description()
25314        )));
25315        queue.put(&mut task).unwrap();
25316        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
25317        let triage =
25318            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
25319        let pending = triage();
25320        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
25321        assert_eq!(
25322            queue.get(&task.id).unwrap().status,
25323            crate::queue::TaskStatus::Held
25324        );
25325        drop(target_lease);
25326        assert_eq!(triage().resumed, vec![task.id.clone()]);
25327        assert_eq!(
25328            queue.get(&task.id).unwrap().status,
25329            crate::queue::TaskStatus::Queued
25330        );
25331        assert!(crate::cache::in_use(&home, &shared));
25332    }
25333
25334    #[tokio::test]
25335    async fn verification_cache_wait_preserves_the_command_budget() {
25336        crate::run::pin_test_home();
25337        let tmp = tempfile::tempdir().unwrap();
25338        let cache = tmp.path().join("target");
25339        let guard = hold(&cache);
25340        let release = tokio::spawn(async move {
25341            tokio::time::sleep(Duration::from_millis(100)).await;
25342            guard.release();
25343        });
25344        let mut st = state(10);
25345        let budget = Duration::from_millis(50);
25346        let wait = repository_wait(&st, None);
25347        let (outcomes, _) = with_cache_lease(
25348            &mut st,
25349            Some(&cache),
25350            "gate",
25351            "gate",
25352            tmp.path(),
25353            "abc1234",
25354            budget,
25355            "test gate",
25356            &wait,
25357            |_, available| async move {
25358                assert_eq!(
25359                    available, budget,
25360                    "contention must not shorten verification"
25361                );
25362                (Vec::new(), false, Vec::new())
25363            },
25364        )
25365        .await
25366        .unwrap();
25367        release.await.unwrap();
25368        assert!(outcomes.is_empty(), "{outcomes:?}");
25369        assert!(
25370            st.events
25371                .iter()
25372                .any(|event| event.message.contains("waiting for"))
25373        );
25374        assert!(st.resource_wait.is_none());
25375        // The verification body no longer owns the lease after returning.
25376        hold(&cache).release();
25377    }
25378
25379    #[tokio::test]
25380    async fn verification_cache_wait_expires_without_starting_commands() {
25381        crate::run::pin_test_home();
25382        let tmp = tempfile::tempdir().unwrap();
25383        let cache = tmp.path().join("target");
25384        let _held = hold(&cache);
25385        let mut st = state(0);
25386        let wait = repository_wait(&st, None);
25387        let (outcomes, _) = with_cache_lease(
25388            &mut st,
25389            Some(&cache),
25390            "gate",
25391            "gate",
25392            tmp.path(),
25393            "abc1234",
25394            Duration::from_secs(60),
25395            "test gate",
25396            &wait,
25397            |_, _| async { panic!("commands must not start without the cache lease") },
25398        )
25399        .await
25400        .unwrap();
25401        assert_eq!(outcomes.len(), 1);
25402        assert!(outcomes[0].resource_blocked);
25403        assert!(st.resource_wait.is_none());
25404        assert!(matches!(
25405            st.resource_block.unwrap().cause,
25406            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25407        ));
25408    }
25409
25410    #[tokio::test]
25411    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25412        crate::run::pin_test_home();
25413        let tmp = tempfile::tempdir().unwrap();
25414        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25415        let cache = tmp.path().join("cache");
25416        let mut state = state(21600);
25417        let wait = repository_wait(&state, None);
25418        let (outcomes, _) = with_cache_lease(
25419            &mut state,
25420            Some(&cache),
25421            "gate",
25422            "gate",
25423            tmp.path(),
25424            "head",
25425            Duration::from_secs(60),
25426            "gate",
25427            &wait,
25428            |_, _| async { panic!("freshness failure must not start verification") },
25429        )
25430        .await
25431        .unwrap();
25432        assert_eq!(outcomes.len(), 1);
25433        assert!(outcomes[0].resource_blocked);
25434        let block = state.resource_block.unwrap();
25435        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25436        assert!(!block.description().contains("timed out"));
25437    }
25438
25439    #[tokio::test]
25440    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25441        crate::run::pin_test_home();
25442        let tmp = tempfile::tempdir().unwrap();
25443        let cache = tmp.path().join("cache");
25444        let _held = hold(&cache);
25445        let mut state = state(21600);
25446        let pause = Pause::new();
25447        let interrupt = Pause::new();
25448        let cause = ParkCause::Operator;
25449        pause.park_for(cause.clone());
25450        let prompts = Prompts::default();
25451        let ctx = WaveCtx {
25452            run: "test",
25453            node: "fix",
25454            prompts: &prompts,
25455            cache: Some(&cache),
25456            round: None,
25457            carry_seats: false,
25458            pauses: Some((&pause, &interrupt)),
25459        };
25460        let result = wave(
25461            vec![job(
25462                sh("writer", "exit 99"),
25463                tmp.path(),
25464                Duration::from_secs(1),
25465            )],
25466            Arc::new(Semaphore::new(1)),
25467            &ctx,
25468            &mut state,
25469            0,
25470        )
25471        .await;
25472        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
25473        assert_eq!(result[0].1.turns, 0);
25474        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25475        assert_eq!(
25476            state.resource_block.unwrap().cause,
25477            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
25478        );
25479        assert!(state.active.is_empty());
25480    }
25481
25482    #[tokio::test]
25483    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
25484        crate::run::pin_test_home();
25485        let tmp = tempfile::tempdir().unwrap();
25486        let cache = tmp.path().join("target-a");
25487        let guard = hold(&cache);
25488        // Held for longer than the agent's whole 1s budget.
25489        tokio::spawn(async move {
25490            tokio::time::sleep(Duration::from_millis(1500)).await;
25491            guard.release();
25492        });
25493        let mut st = state(60);
25494        let results = run(
25495            vec![job(
25496                sh("alpha", "echo ok"),
25497                tmp.path(),
25498                Duration::from_secs(1),
25499            )],
25500            Arc::new(Semaphore::new(1)),
25501            Some(&cache),
25502            &mut st,
25503        )
25504        .await;
25505        assert!(
25506            matches!(results[0].2, AgentOutcome::Ok(_)),
25507            "the wait must not be charged to the agent"
25508        );
25509        assert!(st.resource_block.is_none());
25510        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25511        assert!(st.resource_wait.is_none() && st.active.is_empty());
25512    }
25513
25514    #[tokio::test]
25515    #[cfg(unix)]
25516    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
25517        use std::os::fd::AsRawFd as _;
25518        crate::run::pin_test_home();
25519        let tmp = tempfile::tempdir().unwrap();
25520        crate::git::git(tmp.path(), &["init"]).await.unwrap();
25521        let common = tmp.path().join(".git");
25522        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
25523        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
25524        assert_eq!(
25525            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
25526            0
25527        );
25528        let mut st = state(1);
25529        st.config.coordination = crate::config::test_coordination();
25530        let mut reader = job(
25531            sh("reader", "echo must-not-run"),
25532            tmp.path(),
25533            Duration::from_secs(30),
25534        );
25535        reader.allow_write = false;
25536        let results = run(
25537            vec![reader.clone()],
25538            Arc::new(Semaphore::new(1)),
25539            None,
25540            &mut st,
25541        )
25542        .await;
25543        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25544        assert_eq!(results[0].1.turns, 0);
25545        assert!(FailClass::of(&results[0].2).is_none());
25546        assert_eq!(
25547            st.resource_block.as_ref().unwrap().kind,
25548            "repository coordination"
25549        );
25550        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25551        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25552        drop(external);
25553        let editor = crate::repo_lock::SeatLease::for_checkout(
25554            tmp.path(),
25555            true,
25556            crate::config::test_coordination().as_ref(),
25557        )
25558        .await
25559        .unwrap();
25560        let pause = Pause::new();
25561        let interrupt = Pause::new();
25562        let prompts = Prompts::default();
25563        let ctx = WaveCtx {
25564            run: "r",
25565            node: "review",
25566            prompts: &prompts,
25567            cache: None,
25568            round: None,
25569            carry_seats: false,
25570            pauses: Some((&pause, &interrupt)),
25571        };
25572        let (results, ()) = tokio::join!(
25573            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25574            async {
25575                tokio::time::sleep(Duration::from_millis(50)).await;
25576                pause.park();
25577            }
25578        );
25579        assert!(
25580            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25581        );
25582        assert_eq!(results[0].1.turns, 0);
25583        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25584        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25585        drop(editor);
25586    }
25587
25588    #[tokio::test]
25589    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25590        crate::run::pin_test_home();
25591        let tmp = tempfile::tempdir().unwrap();
25592        let cache = tmp.path().join("target-b");
25593        let _held = hold(&cache);
25594        let mut st = state(1);
25595        let results = run(
25596            vec![job(
25597                sh("alpha", "echo ok"),
25598                tmp.path(),
25599                Duration::from_secs(1),
25600            )],
25601            Arc::new(Semaphore::new(1)),
25602            Some(&cache),
25603            &mut st,
25604        )
25605        .await;
25606        let (_, seat, out) = &results[0];
25607        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25608        assert!(wave_blocked(&results));
25609        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25610        assert_eq!(seat.turns, 0, "nothing was asked");
25611        assert!(
25612            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25613            "no agent was spawned"
25614        );
25615        assert!(FailClass::of(out).is_none(), "not a failure class");
25616        let block = st.resource_block.as_ref().expect("recorded for the resume");
25617        assert_eq!(block.kind, "shared build cache");
25618        assert!(matches!(
25619            block.cause,
25620            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25621        ));
25622        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25623        assert!(st.active.is_empty());
25624    }
25625
25626    #[tokio::test]
25627    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25628        crate::run::pin_test_home();
25629        let tmp = tempfile::tempdir().unwrap();
25630        let mut st = state(1);
25631        let results = run(
25632            vec![job(
25633                sh("alpha", "echo ok"),
25634                tmp.path(),
25635                Duration::from_secs(1),
25636            )],
25637            Arc::new(Semaphore::new(0)),
25638            None,
25639            &mut st,
25640        )
25641        .await;
25642        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25643        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25644        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25645    }
25646
25647    #[tokio::test]
25648    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25649        crate::run::pin_test_home();
25650        let tmp = tempfile::tempdir().unwrap();
25651        let mut st = state(60);
25652        let results = run(
25653            vec![job(
25654                sh("alpha", "sleep 30"),
25655                tmp.path(),
25656                Duration::from_secs(1),
25657            )],
25658            Arc::new(Semaphore::new(1)),
25659            None,
25660            &mut st,
25661        )
25662        .await;
25663        let out = &results[0].2;
25664        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25665        let class = FailClass::of(out).expect("a failure");
25666        assert_eq!(class, FailClass::Timeout);
25667        assert!(should_hand_over(None, &class), "existing handover policy");
25668        assert!(st.resource_block.is_none());
25669    }
25670}