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        let base_commit = self.state.base_commit.clone();
3326        let blind_cfg = self.state.config.blind.clone();
3327        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3328        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3329            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3330                // Executed turns interrupted by disk pressure already carry
3331                // a preservation barrier from wave. Admission-only waits do
3332                // not. Keep the interrupted seat's session for recovery too.
3333                if self
3334                    .state
3335                    .candidate_preservation
3336                    .contains_key(&self.state.candidates[i].label)
3337                {
3338                    self.state.seats.insert(seat.key.clone(), seat);
3339                }
3340                continue;
3341            }
3342            let seat_key = seat.key.clone();
3343            // A quota fallback (`resume_seat_handovers`) may have handed this
3344            // seat to a different agent than the one `prep` recorded on the
3345            // candidate; the stats tables and any later fixer-defaults-to-
3346            // winner's-author lookup must credit whoever actually answered —
3347            // unless every fallback also quota'd out, in which case nobody
3348            // actually answered and crediting the last agent tried would
3349            // erase every earlier agent's own quota loss from the stats
3350            // tables instead of just this one seat's.
3351            let agent = seat.agent.clone();
3352            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3353            self.state.seats.insert(seat.key.clone(), seat);
3354            let label = self.state.candidates[i].label;
3355            let worktree = self.state.candidates[i].worktree.clone();
3356            self.state.interrupted_implementations.remove(&label);
3357
3358            let (sanitized_summary, duration, failed, verified_claim) = match out {
3359                AgentOutcome::Ok(o) => {
3360                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3361                    let failed = (!o.usable()).then(|| {
3362                        if o.timed_out {
3363                            "agent timed out".to_owned()
3364                        } else {
3365                            format!(
3366                                "agent exited with {}",
3367                                crate::notices::exit_status(o.exit_code)
3368                            )
3369                        }
3370                    });
3371                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3372                    let verified_claim = match verified_noop_claim_in_worktree(
3373                        failed.is_none(),
3374                        &o.commands,
3375                        &text,
3376                        &worktree,
3377                        &base_commit,
3378                    )
3379                    .await
3380                    {
3381                        NoopClaimVerdict::Accepted => {
3382                            if matches!(
3383                                verdict::parse_verified_noop(&sanitized_summary),
3384                                Some(Ok(_))
3385                            ) {
3386                                Some(sanitized_summary.clone())
3387                            } else {
3388                                rejected_noops.push((
3389                                    label,
3390                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3391                                ));
3392                                None
3393                            }
3394                        }
3395                        NoopClaimVerdict::Rejected(reason) => {
3396                            rejected_noops.push((label, reason));
3397                            None
3398                        }
3399                        NoopClaimVerdict::Absent => None,
3400                    };
3401                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3402                }
3403                // Left un-resumed by `resume_undelivered` (a dirty tree
3404                // already rescues the work, or there was no session left to
3405                // resume into) — reported like the ordinary failure it is,
3406                // never as if `o.text` (the CLI's raw error JSON) were an
3407                // answer.
3408                AgentOutcome::Dropped(o) => {
3409                    let why = o
3410                        .dropped
3411                        .as_ref()
3412                        .map(|d| d.why.as_str())
3413                        .unwrap_or("the CLI ended the stream without delivering its answer");
3414                    (
3415                        String::new(),
3416                        o.duration_ms,
3417                        Some(format!("the CLI dropped the stream ({why})")),
3418                        None,
3419                    )
3420                }
3421                AgentOutcome::Quota(o) => {
3422                    self.state.quota.push(QuotaLoss::from_report(
3423                        seat_key,
3424                        "implement",
3425                        o.quota.as_ref(),
3426                    ));
3427                    (
3428                        String::new(),
3429                        o.duration_ms,
3430                        Some("rate limited (quota); produced no change".to_owned()),
3431                        None,
3432                    )
3433                }
3434                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3435                    (String::new(), 0, Some(e), None)
3436                }
3437            };
3438
3439            // Save every completed turn before any fallible Git operation. A failed
3440            // rescue must not erase the reply or prevent collection of other seats.
3441            let c = &mut self.state.candidates[i];
3442            if !exhausted_the_fallback_chain {
3443                c.agent = agent;
3444            }
3445            c.summary = sanitized_summary;
3446            c.duration_ms = duration;
3447            c.failed = failed;
3448            c.verified_noop = verified_claim;
3449            self.state
3450                .candidate_preservation
3451                .insert(label, "awaiting persistence".to_owned());
3452        }
3453        self.state.save()?;
3454        self.persist_candidates().await?;
3455
3456        let mut recorded_rejection = false;
3457        for (label, reason) in rejected_noops {
3458            if self.state.interrupted_implementations.contains(&label) {
3459                continue;
3460            }
3461            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3462                && c.empty
3463            {
3464                c.verified_noop = None;
3465                c.failed
3466                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3467                self.state.event(
3468                    "implement",
3469                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3470                );
3471                recorded_rejection = true;
3472            }
3473        }
3474        if recorded_rejection {
3475            self.state.save()?;
3476        }
3477
3478        if resource_blocked {
3479            return self.stop_for_resource();
3480        }
3481        if selected_failed {
3482            self.state.status = RunStatus::Blocked;
3483            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3484            self.state.save()?;
3485            bail!(
3486                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3487            );
3488        }
3489        self.after_implement()
3490    }
3491
3492    /// Retry only persistence after a completed implementation turn.
3493    async fn persist_candidates(&mut self) -> Result<()> {
3494        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3495        for label in labels {
3496            let i = self
3497                .state
3498                .candidates
3499                .iter()
3500                .position(|c| c.label == label)
3501                .context("pending candidate is missing")?;
3502            let c = self.state.candidates[i].clone();
3503            let interrupted = self.state.interrupted_implementations.contains(&label);
3504            let result = async {
3505                let wait = crate::repo_lock::WaitPolicy::new(
3506                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3507                    || false,
3508                );
3509                let _coordination =
3510                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3511                // Best effort evidence requires no index writes. A successful snapshot
3512                // never authorizes removal of a tree whose rescue failed.
3513                if let Err(e) = git::snapshot_uncommitted(
3514                    &c.worktree,
3515                    &self
3516                        .state
3517                        .dir()
3518                        .join("artifacts")
3519                        .join(format!("candidate-{label}-recovery")),
3520                )
3521                .await
3522                {
3523                    self.state.event(
3524                        "preserve",
3525                        format!("candidate {label} snapshot incomplete: {e:#}"),
3526                    );
3527                }
3528                let rescued = git::rescue_commit(
3529                    &c.worktree,
3530                    &format!("magi: candidate {label} (uncommitted work)"),
3531                )
3532                .await?;
3533                self.state.note_withheld("implement", &rescued.withheld);
3534                let base = &self.state.base_commit;
3535                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3536                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3537                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3538                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3539                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3540                if c.empty && commits > 0 && !patch.trim().is_empty()
3541                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3542                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3543                        || self.state.tally.is_some())
3544                {
3545                    // Keep the old classification and pending marker so every
3546                    // retry stops too. Retain decisions as recovery evidence;
3547                    // only a supported recovery operation may replace them.
3548                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3549                }
3550                let c = &mut self.state.candidates[i];
3551                c.commits = commits;
3552                c.stat = stat;
3553                c.files = files;
3554                let no_changes = commits == 0 || patch.trim().is_empty();
3555                c.empty = no_changes && !interrupted;
3556                if interrupted && no_changes {
3557                    c.failed = None;
3558                    c.verified_noop = None;
3559                }
3560                if !c.empty {
3561                    c.failed = None;
3562                    c.verified_noop = None;
3563                }
3564                self.state.event(
3565                    "preserve",
3566                    format!("candidate {label}: {files} files, {commits} commits"),
3567                );
3568                Ok::<_, anyhow::Error>(())
3569            }
3570            .await;
3571            match result {
3572                Ok(()) => {
3573                    self.state.candidate_preservation.remove(&label);
3574                    if !interrupted || self.state.candidates[i].files > 0 {
3575                        self.state.interrupted_implementations.remove(&label);
3576                    }
3577                }
3578                Err(e) => {
3579                    let reason = format!("candidate {label} preservation failed: {e:#}");
3580                    self.state.event("preserve", &reason);
3581                    self.state.candidate_preservation.insert(label, reason);
3582                }
3583            }
3584            if self.state.candidate_preservation.is_empty()
3585                && self.state.status == RunStatus::Blocked
3586                && self.state.candidates.iter().all(|c| c.failed.is_none())
3587            {
3588                // Persist the recovered phase with the cleared pending marker;
3589                // a crash between saves must not turn this into a selected-seat
3590                // failure hold on the next resume.
3591                self.state.status = RunStatus::Implementing;
3592                self.state.event(
3593                    "preserve",
3594                    "candidate persistence recovered; implementation can continue",
3595                );
3596            }
3597            self.state.save()?;
3598        }
3599        if !self.state.candidate_preservation.is_empty() {
3600            self.state.status = RunStatus::Blocked;
3601            self.state.save()?;
3602            bail!(
3603                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3604            );
3605        }
3606        Ok(())
3607    }
3608
3609    /// Ask again, once, for work a CLI did and then failed to hand over.
3610    ///
3611    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3612    /// status with an empty response and a usage report showing output tokens,
3613    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3614    /// seven minutes and 14,267 output tokens that arrived as an empty
3615    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3616    ///
3617    /// Two conditions, and both matter:
3618    ///
3619    /// - **Only when the tree is untouched.** Often the agent has already
3620    ///   written its files and only the closing message was lost; the rescue
3621    ///   commit below picks that up and there is nothing to ask for. Re-asking
3622    ///   then would pay for a second implementation of work already on disk.
3623    /// - **Once.** A CLI that drops one stream can drop the next, and this
3624    ///   node is the most expensive in the graph.
3625    ///
3626    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3627    /// dropped reply still carried its `conversation_id`, so the seat is asked
3628    /// to finish what it was doing rather than sent the whole task again. It
3629    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3630    /// node's - for the same reason a re-ranked judge does: restating finished
3631    /// work is not the work.
3632    ///
3633    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3634    /// same way until it resets, while an abandoned conversation is still
3635    /// there to be picked up.
3636    async fn resume_undelivered(
3637        &mut self,
3638        results: &mut [(usize, SeatState, AgentOutcome)],
3639        sent: &[SeatJob],
3640        prompts: &Prompts,
3641        run_id: &str,
3642    ) {
3643        for (wi, seat, out) in results.iter_mut() {
3644            let Some(dropped) = (match &*out {
3645                AgentOutcome::Dropped(o) => o.dropped.clone(),
3646                _ => None,
3647            }) else {
3648                continue;
3649            };
3650            let Some(job) = sent.get(*wi) else { continue };
3651            // Already on disk? Then only the closing message was lost.
3652            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3653                self.state.event(
3654                    "implement",
3655                    format!(
3656                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3657                         work is in the tree",
3658                        seat.key, dropped.output_tokens, dropped.why
3659                    ),
3660                );
3661                continue;
3662            }
3663            // The re-ask only makes sense as a resume: `resume_after_drop`
3664            // says nothing about the task, trusting the seat to still hold it.
3665            // Without a session to resume — sessions disabled, or this CLI's
3666            // drop shape happened not to carry a session id — that prompt
3667            // would open a brand-new conversation with no context at all,
3668            // which is worse than leaving this as the ordinary failure it
3669            // already is.
3670            if !has_context(&job.spec, seat, job.sessions) {
3671                self.state.event(
3672                    "implement",
3673                    format!(
3674                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3675                         is no session left to resume",
3676                        seat.key, dropped.output_tokens, dropped.why
3677                    ),
3678                );
3679                continue;
3680            }
3681            self.state.event(
3682                "implement",
3683                format!(
3684                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3685                     conversation",
3686                    seat.key, dropped.output_tokens, dropped.why
3687                ),
3688            );
3689            let mut retry = job.clone();
3690            retry.seat = seat.clone();
3691            retry.prompt = prompt::resume_after_drop(&dropped.why);
3692            retry.timeout = retry_budget(job.timeout, true);
3693            retry.stem = format!("{}-resume", job.stem);
3694            let cache = self.state.config.cache_dir();
3695            let ctx = WaveCtx {
3696                carry_seats: false,
3697                pauses: Some((&self.pause, &self.interrupt)),
3698                run: run_id,
3699                node: "implement",
3700                prompts,
3701                cache: cache.as_deref(),
3702                round: None,
3703            };
3704            let (resumed_seat, resumed) =
3705                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3706            *seat = resumed_seat;
3707            *out = resumed;
3708        }
3709    }
3710
3711    /// Fall an implement seat through to the next untried agent in the
3712    /// implementer roster when it lost to quota — or, since the handover was
3713    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3714    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3715    /// quota path itself being unchanged — instead of leaving the
3716    /// seat's loss final the moment one agent's account runs dry.
3717    ///
3718    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3719    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3720    /// truncates to the single slot rotation picked, so a solo task whose one
3721    /// implementer hits quota mid-run used to have nothing else to try. This
3722    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3723    /// unrotated roster — which is the only place the *other* candidates in
3724    /// the machine's roster still exist once `implementers` has been cut down
3725    /// to size.
3726    ///
3727    /// Walks forward from just past the seat's own original position in the
3728    /// roster, never wrapping back to the front: a later candidate slot (say
3729    /// `beta`, the roster's second entry) must fall through to the *next*
3730    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3731    /// almost certainly a different candidate's own agent already — and once
3732    /// the roster's tail is exhausted there is nothing left to fall through
3733    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3734    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3735    /// let this retry that id forever. The loop keeps falling through until
3736    /// an attempt lands something other than `Quota` or the roster's tail
3737    /// runs out of untried ids, at which point the seat is left exactly as
3738    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3739    /// `QuotaLoss` recorded, the candidate failed/empty.
3740    ///
3741    /// `sent` is taken mutably and updated with the fallback agent's spec:
3742    /// `resume_unconfirmed_commands`, which runs after this and also reads
3743    /// `sent`, must see whichever agent actually ended up answering the seat
3744    /// — reading the stale, original spec there would check session
3745    /// eligibility against the wrong CLI and could hand a fallback agent's
3746    /// session id to the agent that just lost the seat to quota.
3747    ///
3748    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3749    /// — `self.seat` only reuses state when the agent id is unchanged, so
3750    /// handing it a different id already gets this for free. Reusing the old
3751    /// seat would resume a different CLI's session as if it were a
3752    /// continuation of this one.
3753    ///
3754    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3755    /// a quota loss cuts an agent off mid-turn, so anything already in the
3756    /// tree is unfinished work, not a completed candidate a re-ask would pay
3757    /// for twice. A dirty tree is rescued into a commit first (the same
3758    /// neutral-identity rescue `implement`'s own outcome loop gives every
3759    /// candidate) so the next agent starts clean.
3760    ///
3761    /// The new agent gets the implementer's full prompt and full
3762    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3763    /// it has no session and no context, and is implementing the task from
3764    /// nothing, unlike a resumed drop which is only restating work already
3765    /// done.
3766    ///
3767    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3768    /// `implement` event, never into `self.state.quota` — that is what
3769    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3770    /// go unspent, and a seat that ultimately recovered on its second or
3771    /// third agent is not the stalled panel that check exists to catch. Only
3772    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3773    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3774    /// outcome loop already has — this helper never pushes to it itself.
3775    async fn resume_seat_handovers(
3776        &mut self,
3777        results: &mut [(usize, SeatState, AgentOutcome)],
3778        sent: &mut [SeatJob],
3779        prompts: &Prompts,
3780        run_id: &str,
3781    ) -> Result<()> {
3782        let instruction = seeded_instruction(&self.state);
3783        let language = self.state.config.graph.language.clone();
3784        let github_language = self.state.config.graph.github_language.clone();
3785        let brief = self
3786            .state
3787            .advice
3788            .as_ref()
3789            .and_then(|a| a.synthesis.as_deref())
3790            .map(str::to_owned);
3791        let attachments = self.state.attachments.clone();
3792        for (wi, seat, out) in results.iter_mut() {
3793            // Who holds the other candidate seats of this wave right now
3794            // (earlier handovers already written back to `sent`).
3795            let others: BTreeSet<String> = sent
3796                .iter()
3797                .enumerate()
3798                .filter(|(j, _)| j != wi)
3799                .map(|(_, j)| j.spec.id.clone())
3800                .collect();
3801            let Some(job) = sent.get_mut(*wi) else {
3802                continue;
3803            };
3804            // Where the seat's own original agent sits in the roster — the
3805            // fallback walk starts just past here, never at the front, so a
3806            // later candidate slot's quota loss does not fall back onto an
3807            // earlier slot's own agent.
3808            let start = self
3809                .roles
3810                .implementer_roster
3811                .iter()
3812                .position(|s| s.id == job.spec.id)
3813                .unwrap_or(0);
3814            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3815            let mut fallback_attempt = 0usize;
3816            let mut prev: Option<FailClass> = None;
3817            while let Some(cur) = FailClass::of(&*out) {
3818                if !should_hand_over(prev.as_ref(), &cur) {
3819                    break;
3820                }
3821                let Some(next) =
3822                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3823                        .cloned()
3824                else {
3825                    break;
3826                };
3827                tried.insert(next.id.clone());
3828                fallback_attempt += 1;
3829
3830                let coordination = self.coordinate(&job.cwd).await?;
3831                if let Ok(r) = git::rescue_commit(
3832                    &job.cwd,
3833                    &format!(
3834                        "magi: candidate {} (uncommitted work before {} fallback)",
3835                        seat.key,
3836                        if cur == FailClass::Quota {
3837                            "quota"
3838                        } else {
3839                            "handover"
3840                        }
3841                    ),
3842                )
3843                .await
3844                {
3845                    self.state.note_withheld("implement", &r.withheld);
3846                }
3847                drop(coordination);
3848
3849                record_handover(
3850                    &mut self.state,
3851                    "implement",
3852                    &seat.key,
3853                    &seat.agent,
3854                    &next.id,
3855                    &cur,
3856                    &fail_reason(&*out),
3857                );
3858                prev = Some(cur.clone());
3859
3860                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3861                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3862                // Kept in sync on `sent` itself, not just the local retry: a
3863                // later helper (`resume_unconfirmed_commands`) reads `sent`
3864                // after this one returns and must see whichever agent is now
3865                // occupying the seat, not the one that just quota'd out —
3866                // otherwise it would judge session/continuation eligibility
3867                // by the wrong CLI and could resend a fallback's session id
3868                // to the agent that lost it the seat in the first place.
3869                job.spec = next.clone();
3870                let mut retry = job.clone();
3871                retry.seat = new_seat;
3872                retry.prompt = prompt::implement_in(
3873                    &instruction,
3874                    &job.cwd.to_string_lossy(),
3875                    &language,
3876                    &github_language,
3877                    brief.as_deref(),
3878                    &attachments,
3879                );
3880                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3881                let cache = self.state.config.cache_dir();
3882                let ctx = WaveCtx {
3883                    carry_seats: false,
3884                    pauses: Some((&self.pause, &self.interrupt)),
3885                    run: run_id,
3886                    node: "implement",
3887                    prompts,
3888                    cache: cache.as_deref(),
3889                    round: None,
3890                };
3891                let (fallback_seat, fallback_out) = run_one(
3892                    retry,
3893                    Arc::clone(&self.sem),
3894                    &ctx,
3895                    &mut self.state,
3896                    fallback_attempt,
3897                )
3898                .await;
3899                *seat = fallback_seat;
3900                *out = fallback_out;
3901            }
3902        }
3903        Ok(())
3904    }
3905
3906    /// Ask an implement seat's own CLI to confirm what it started, once, when
3907    /// its reply reported a command whose completion status it never
3908    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3909    /// that does and does not mean.
3910    ///
3911    /// The completion contract this task asks for, extended to `implement`
3912    /// with the same signal `continue_fix_report` reads for the fixer,
3913    /// rather than a keyword search over the reply or a hard requirement on
3914    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3915    /// a candidate's CLI turn ended cleanly while a test run it had started
3916    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3917    /// named in it at all is untouched by this: `commands` is empty, so
3918    /// there is nothing to be unconfirmed.
3919    ///
3920    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3921    /// this is not about recovering edits that might already be on disk, it
3922    /// is about a result the seat itself never vouched for, which resuming
3923    /// asks for regardless of what the tree already holds. Bounded to one
3924    /// attempt for the same reason `resume_undelivered` is — this is the
3925    /// most expensive node in the graph — and a seat that still cannot
3926    /// confirm on that attempt is left as whatever its (possibly still
3927    /// unconfirmed) reply says; this does not invent a new "failed" reason
3928    /// for a candidate that otherwise produced a real, committed change.
3929    async fn resume_unconfirmed_commands(
3930        &mut self,
3931        results: &mut [(usize, SeatState, AgentOutcome)],
3932        sent: &[SeatJob],
3933        prompts: &Prompts,
3934        run_id: &str,
3935    ) {
3936        for (wi, seat, out) in results.iter_mut() {
3937            let AgentOutcome::Ok(o) = &*out else {
3938                continue;
3939            };
3940            if !has_unconfirmed_command(&o.commands) {
3941                continue;
3942            }
3943            let Some(job) = sent.get(*wi) else { continue };
3944            if !has_context(&job.spec, seat, job.sessions) {
3945                self.state.event(
3946                    "implement",
3947                    format!(
3948                        "{}: the reply named a command whose own CLI never confirmed the exit \
3949                         status of, but there is no session left to resume",
3950                        seat.key
3951                    ),
3952                );
3953                continue;
3954            }
3955            self.state.event(
3956                "implement",
3957                format!(
3958                    "{}: the reply named a command whose own CLI never confirmed the exit \
3959                     status of; resuming the conversation",
3960                    seat.key
3961                ),
3962            );
3963            let mut retry = job.clone();
3964            retry.seat = seat.clone();
3965            retry.prompt = prompt::resume_incomplete(
3966                "a command in your last reply had no confirmed exit status",
3967            );
3968            retry.timeout = retry_budget(job.timeout, true);
3969            retry.stem = format!("{}-confirm", job.stem);
3970            let cache = self.state.config.cache_dir();
3971            let ctx = WaveCtx {
3972                carry_seats: false,
3973                pauses: Some((&self.pause, &self.interrupt)),
3974                run: run_id,
3975                node: "implement",
3976                prompts,
3977                cache: cache.as_deref(),
3978                round: None,
3979            };
3980            let (resumed_seat, resumed) =
3981                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3982            *seat = resumed_seat;
3983            *out = resumed;
3984        }
3985    }
3986
3987    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3988    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3989    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3990    /// that motivated this.
3991    ///
3992    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3993    /// own nudge loop already covers for judge/review/vote seats, and not a
3994    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3995    /// implement seats: here the CLI turn genuinely finished while the node's
3996    /// own work — the fixer's account of what it did — had not. Gated purely
3997    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3998    /// reply, never on any wording in it, so a fixer whose valid, first-try
3999    /// `FixReport` happens to mention having waited on a background test is
4000    /// never resumed — the `Ok(report)` branch at the call site returns
4001    /// before this is ever invoked.
4002    ///
4003    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4004    /// attempt ([`retry_budget`]), nothing attempted once the session is
4005    /// gone, and a quota hit ends the loop immediately rather than retrying a
4006    /// rate limit that fails the same way again.
4007    async fn continue_fix_report(
4008        &mut self,
4009        mut seat: SeatState,
4010        parse_err: String,
4011        job: &SeatJob,
4012        prompts: &Prompts,
4013        run_id: &str,
4014        round: usize,
4015    ) -> (
4016        SeatState,
4017        Option<FixReport>,
4018        Option<String>,
4019        ContinuationRecord,
4020    ) {
4021        let mut last_err = parse_err;
4022        let mut cumulative_wait_ms = 0u64;
4023        let mut attempts = 0usize;
4024        loop {
4025            if !has_context(&job.spec, &seat, job.sessions) {
4026                self.state.event(
4027                    "fix",
4028                    format!(
4029                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4030                         session left to resume into"
4031                    ),
4032                );
4033                let outcome = if attempts == 0 {
4034                    ContinuationOutcome::NoSession
4035                } else {
4036                    ContinuationOutcome::Exhausted
4037                };
4038                return (
4039                    seat,
4040                    None,
4041                    Some(format!("unparsable fix report: {last_err}")),
4042                    ContinuationRecord {
4043                        attempts,
4044                        cumulative_wait_ms,
4045                        outcome,
4046                    },
4047                );
4048            }
4049            if attempts >= MAX_FIX_CONTINUATIONS {
4050                self.state.event(
4051                    "fix",
4052                    format!(
4053                        "round {round}: fixer's reply still had no adoption report after \
4054                         {attempts} continuation(s) ({last_err}); giving up"
4055                    ),
4056                );
4057                return (
4058                    seat,
4059                    None,
4060                    Some(format!(
4061                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4062                    )),
4063                    ContinuationRecord {
4064                        attempts,
4065                        cumulative_wait_ms,
4066                        outcome: ContinuationOutcome::Exhausted,
4067                    },
4068                );
4069            }
4070            attempts += 1;
4071            self.state.event(
4072                "fix",
4073                format!(
4074                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4075                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4076                ),
4077            );
4078            let mut retry = job.clone();
4079            retry.seat = seat.clone();
4080            retry.prompt = prompt::resume_incomplete(&last_err);
4081            retry.timeout = retry_budget(job.timeout, true);
4082            retry.stem = format!("{}-continue{attempts}", job.stem);
4083            let cache = self.state.config.cache_dir();
4084            let ctx = WaveCtx {
4085                carry_seats: false,
4086                pauses: Some((&self.pause, &self.interrupt)),
4087                run: run_id,
4088                node: "fix",
4089                prompts,
4090                cache: cache.as_deref(),
4091                round: Some(round),
4092            };
4093            let (resumed_seat, resumed_out) = run_one(
4094                retry,
4095                Arc::clone(&self.sem),
4096                &ctx,
4097                &mut self.state,
4098                attempts,
4099            )
4100            .await;
4101            seat = resumed_seat;
4102            match resumed_out {
4103                AgentOutcome::Ok(o) => {
4104                    cumulative_wait_ms += o.duration_ms;
4105                    match verdict::extract_json::<FixReport>(&o.text) {
4106                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4107                            self.state.event(
4108                                "fix",
4109                                format!(
4110                                    "round {round}: fixer's adoption report recovered after \
4111                                     {attempts} continuation(s)"
4112                                ),
4113                            );
4114                            return (
4115                                seat,
4116                                Some(report),
4117                                None,
4118                                ContinuationRecord {
4119                                    attempts,
4120                                    cumulative_wait_ms,
4121                                    outcome: ContinuationOutcome::Resumed,
4122                                },
4123                            );
4124                        }
4125                        // The report parsed, but this same reply's own
4126                        // CommandEvidence — the identical record `state.jobs`
4127                        // renders — names a command whose CLI never
4128                        // confirmed an exit status. Read together, that is
4129                        // not a resolved answer: keep nudging rather than
4130                        // accept a report standing next to a command the
4131                        // seat's own CLI cannot vouch for.
4132                        Ok(_) => {
4133                            last_err = "the reply parsed, but it reported a command whose own CLI \
4134                                 never confirmed an exit status"
4135                                .to_owned();
4136                        }
4137                        Err(e) => last_err = e.to_string(),
4138                    }
4139                }
4140                AgentOutcome::Quota(o) => {
4141                    cumulative_wait_ms += o.duration_ms;
4142                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4143                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4144                    self.state.quota.push(loss);
4145                    self.state.event(
4146                        "fix",
4147                        format!(
4148                            "round {round}: continuation rate limited (quota); not retrying now"
4149                        ),
4150                    );
4151                    return (
4152                        seat,
4153                        None,
4154                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4155                        ContinuationRecord {
4156                            attempts,
4157                            cumulative_wait_ms,
4158                            outcome: ContinuationOutcome::QuotaLost,
4159                        },
4160                    );
4161                }
4162                AgentOutcome::Dropped(o) => {
4163                    cumulative_wait_ms += o.duration_ms;
4164                    let why = o
4165                        .dropped
4166                        .as_ref()
4167                        .map(|d| d.why.as_str())
4168                        .unwrap_or("the CLI ended the stream without delivering its answer");
4169                    last_err = format!("the CLI dropped the stream ({why})");
4170                }
4171                AgentOutcome::Failed(e) => last_err = e,
4172                // The continuation was never started; the report stays lost
4173                // and the caller records that, without any handover.
4174                AgentOutcome::ResourceBlocked(e) => {
4175                    return (
4176                        seat,
4177                        None,
4178                        Some(format!("the continuation was not started: {e}")),
4179                        ContinuationRecord {
4180                            attempts: attempts.saturating_sub(1),
4181                            cumulative_wait_ms,
4182                            outcome: ContinuationOutcome::NoSession,
4183                        },
4184                    );
4185                }
4186            }
4187        }
4188    }
4189
4190    fn after_implement(&mut self) -> Result<()> {
4191        if !self.state.candidate_preservation.is_empty() {
4192            bail!("candidate preservation incomplete; judging is unsafe");
4193        }
4194        // Scan every candidate patch once the set is complete.
4195        if self.state.leaks.is_empty() {
4196            let cfg = self.state.config.blind.clone();
4197            let mut leaks = Vec::new();
4198            for c in &self.state.candidates {
4199                let Some(patch) =
4200                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4201                else {
4202                    continue;
4203                };
4204                leaks.extend(blind::scan(
4205                    &format!("candidate {} patch", c.label),
4206                    &patch,
4207                    &cfg.vendor_tokens,
4208                ));
4209            }
4210            if !leaks.is_empty() {
4211                let summary = leaks
4212                    .iter()
4213                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4214                    .collect::<Vec<_>>()
4215                    .join(", ");
4216                match cfg.on_leak {
4217                    LeakPolicy::Fail => {
4218                        self.state.status = RunStatus::Failed;
4219                        self.state
4220                            .event("blind", format!("vendor text in a patch: {summary}"));
4221                        self.state.leaks = leaks;
4222                        self.state.save()?;
4223                        self.settle_questions();
4224                        bail!(
4225                            "blind.on_leak = \"fail\" and vendor text reached a \
4226                             judged patch: {summary}"
4227                        );
4228                    }
4229                    LeakPolicy::Redact => self.state.event(
4230                        "blind",
4231                        format!("redacting vendor text for judging: {summary}"),
4232                    ),
4233                    LeakPolicy::Warn => self.state.event(
4234                        "blind",
4235                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4236                    ),
4237                }
4238                self.state.leaks = leaks;
4239            }
4240        }
4241
4242        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4243        // incomplete or inconsistent saved state cannot bypass the strict contract.
4244        let mut invalidated = Vec::new();
4245        for c in &mut self.state.candidates {
4246            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4247                c.verified_noop = None;
4248                if c.empty && c.failed.is_none() {
4249                    c.failed = Some(
4250                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4251                            .to_owned(),
4252                    );
4253                }
4254                invalidated.push(c.label);
4255            }
4256        }
4257        for label in invalidated {
4258            self.state.event(
4259                "implement",
4260                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4261            );
4262        }
4263
4264        if self.state.viable().is_empty() {
4265            if self.state.all_candidates_verified_noop() {
4266                // Every candidate agreed, with evidence the adoption guard
4267                // accepted, that nothing belongs in this worktree. That is
4268                // not the same fact as a candidate that simply failed to
4269                // write anything, and settling it as an ordinary `Failed`
4270                // (see `SCHEMA`'s doc for schema 10) is what let two of
4271                // task 391f's attempts burn a retry each re-discovering the
4272                // same already-landed fix. Terminal either way, so `judge`
4273                // must never run over an empty candidate set — unlike the
4274                // `Failed` branch below this returns `Ok`, not an error:
4275                // nothing here failed.
4276                self.state.status = RunStatus::VerifiedNoop;
4277                self.state.save()?;
4278                self.settle_questions();
4279                return Ok(());
4280            }
4281            self.state.status = RunStatus::Failed;
4282            self.state.save()?;
4283            self.settle_questions();
4284            bail!("no candidate produced a change; nothing to judge");
4285        }
4286        self.state.status = RunStatus::Judging;
4287        self.state.save()?;
4288        Ok(())
4289    }
4290
4291    // --------------------------------------------------------------- judge
4292
4293    async fn judge(&mut self) -> Result<()> {
4294        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4295        // agent files with `magi task add` name the run that paid for it. The
4296        // prompt overlay is cloned alongside it because the waves borrow it
4297        // while `self` is mutably borrowed by the node's own bookkeeping.
4298        let run_id = self.state.id.clone();
4299        let prompts = self.state.config.prompts.clone();
4300        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4301            return Ok(());
4302        }
4303        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4304        if viable.len() == 1 {
4305            // Recorded so this is a one-time event: `judgements` stays empty
4306            // either way, which without this flag is indistinguishable from
4307            // "not yet judged" on the next reentry — and status is left
4308            // untouched, so a later node's conclusion (e.g. `Blocked` after
4309            // the review budget ran out) survives a resume instead of being
4310            // clobbered back to `Judging` by this node running again.
4311            self.state.judge_skipped = true;
4312            self.state.event(
4313                "judge",
4314                format!(
4315                    "only candidate {} produced a change; judging skipped",
4316                    viable[0].label
4317                ),
4318            );
4319            self.state.save()?;
4320            return Ok(());
4321        }
4322        self.state.status = RunStatus::Judging;
4323
4324        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4325        let language = self.state.config.graph.language.clone();
4326        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4327        let sessions = self.state.config.graph.sessions;
4328        let artifacts = agent::artifacts_dir(&self.state.dir());
4329        let root = self.state.worktree_root();
4330        let base_short = short(&self.state.base_commit);
4331
4332        let mut jobs = Vec::new();
4333        let mut orders = Vec::new();
4334        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4335            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4336            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4337            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4338            let seat_key = format!("judge-{}", j + 1);
4339            let seat = self.seat(&seat_key, &spec.id);
4340            jobs.push(SeatJob {
4341                prompt: prompt::judge(
4342                    &self.state.instruction,
4343                    &views,
4344                    self.roles.judges.len(),
4345                    &base_short,
4346                    &language,
4347                ),
4348                spec,
4349                seat,
4350                cwd: root.join(format!("judge-{}", j + 1)),
4351                timeout,
4352                allow_write: false,
4353                sessions,
4354                artifacts: artifacts.clone(),
4355                stem: format!("judge-{}", j + 1),
4356                handover: None,
4357            });
4358        }
4359
4360        self.state.event(
4361            "judge",
4362            format!(
4363                "{} judges ranking {} candidates blind",
4364                jobs.len(),
4365                viable.len()
4366            ),
4367        );
4368        let labels_for_check = labels.clone();
4369        let mut quota_losses = Vec::new();
4370        let cache = self.state.config.cache_dir();
4371        let ctx = WaveCtx {
4372            carry_seats: false,
4373            pauses: Some((&self.pause, &self.interrupt)),
4374            run: &run_id,
4375            node: "judge",
4376            prompts: &prompts,
4377            cache: cache.as_deref(),
4378            round: None,
4379        };
4380        let results = ask_json_wave::<Ranking>(
4381            jobs,
4382            Arc::clone(&self.sem),
4383            self.state.config.graph.retries,
4384            &self.roles.judge_roster,
4385            &ctx,
4386            &mut quota_losses,
4387            &mut self.state,
4388            &move |r: &Ranking| r.validate(&labels_for_check),
4389        )
4390        .await;
4391        if self.state.resource_block.is_some() {
4392            return self.stop_for_resource();
4393        }
4394        self.state.quota.extend(quota_losses);
4395
4396        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4397            let agent_id = seat.agent.clone();
4398            self.state.seats.insert(seat.key.clone(), seat);
4399            let mut record = Judgement {
4400                judge: j + 1,
4401                seat: format!("judge-{}", j + 1),
4402                agent: agent_id,
4403                ranking: Vec::new(),
4404                reasons: BTreeMap::new(),
4405                confidence: None,
4406                strengths: BTreeMap::new(),
4407                order: orders[j].clone(),
4408                failed: None,
4409                duration_ms: 0,
4410            };
4411            match res {
4412                Ok((ranking, out)) => {
4413                    record.ranking = ranking.normalized();
4414                    record.reasons = ranking.reasons;
4415                    record.strengths = ranking.strengths;
4416                    record.confidence = ranking.confidence;
4417                    record.duration_ms = out.duration_ms;
4418                    self.state.event(
4419                        "judge",
4420                        format!(
4421                            "judge {} ranked {}",
4422                            j + 1,
4423                            record.ranking.iter().collect::<String>()
4424                        ),
4425                    );
4426                }
4427                Err(e) => {
4428                    record.failed = Some(e.to_string());
4429                    self.state
4430                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4431                }
4432            }
4433            self.state.judgements.push(record);
4434            self.state.save()?;
4435        }
4436        Ok(())
4437    }
4438
4439    // ---------------------------------------------------------- deliberate
4440
4441    async fn deliberate(&mut self) -> Result<()> {
4442        if self.hold_base_sync().await? {
4443            return Ok(());
4444        }
4445        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4446        // agent files with `magi task add` name the run that paid for it. The
4447        // prompt overlay is cloned alongside it because the waves borrow it
4448        // while `self` is mutably borrowed by the node's own bookkeeping.
4449        let run_id = self.state.id.clone();
4450        let prompts = self.state.config.prompts.clone();
4451        let rounds = self.state.config.graph.deliberate_rounds;
4452        // Resume unfinished rounds after an outage, but never reopen a tally.
4453        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4454            return Ok(());
4455        }
4456        let tops: Vec<char> = self
4457            .state
4458            .judgements
4459            .iter()
4460            .filter_map(|j| j.ranking.first().copied())
4461            .collect();
4462        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4463            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4464                self.state.event(
4465                    "deliberate",
4466                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4467                );
4468            }
4469            self.state.status = RunStatus::Voting;
4470            self.state.save()?;
4471            return Ok(());
4472        }
4473
4474        self.state.status = RunStatus::Deliberating;
4475        self.state.event(
4476            "deliberate",
4477            format!(
4478                "split: first choices were {} — opening {rounds} round(s)",
4479                tops.iter().collect::<String>()
4480            ),
4481        );
4482
4483        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4484        let language = self.state.config.graph.language.clone();
4485        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4486        let sessions = self.state.config.graph.sessions;
4487        let artifacts = agent::artifacts_dir(&self.state.dir());
4488        let root = self.state.worktree_root();
4489        let base_short = short(&self.state.base_commit);
4490
4491        // Judges argue in sequence so that a turn can answer the one before it;
4492        // that is the difference between deliberation and three parallel
4493        // monologues.
4494        for round in self.state.deliberation.len() + 1..=rounds {
4495            let mut turns: Vec<DeliberationTurn> = Vec::new();
4496            let mut round_losses = Vec::new();
4497            let mut asked = 0;
4498            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4499                if self.state.judgements[j].failed.is_some() {
4500                    continue;
4501                }
4502                let seat_key = format!("judge-{}", j + 1);
4503                let spec = self.occupant(&seat_key, spec);
4504                let mut seat = self.seat(&seat_key, &spec.id);
4505                let transcript = self.transcript(&turns, j);
4506                let build = |context: Option<&str>| {
4507                    prompt::deliberate(
4508                        &self.state.instruction,
4509                        context,
4510                        &transcript,
4511                        round,
4512                        rounds,
4513                        &language,
4514                    )
4515                };
4516                let block = self.candidate_block(&viable, &base_short);
4517                let full = build(Some(&block));
4518                let text = if has_context(&spec, &seat, sessions) {
4519                    build(None)
4520                } else {
4521                    full.clone()
4522                };
4523                let job = SeatJob {
4524                    spec,
4525                    seat: seat.clone(),
4526                    prompt: text,
4527                    cwd: root.join(format!("judge-{}", j + 1)),
4528                    timeout,
4529                    allow_write: false,
4530                    sessions,
4531                    artifacts: artifacts.clone(),
4532                    stem: format!("delib-{round}-judge-{}", j + 1),
4533                    handover: Some(full),
4534                };
4535                let cache = self.state.config.cache_dir();
4536                let ctx = WaveCtx {
4537                    carry_seats: false,
4538                    pauses: Some((&self.pause, &self.interrupt)),
4539                    run: &run_id,
4540                    node: "deliberate",
4541                    prompts: &prompts,
4542                    cache: cache.as_deref(),
4543                    round: None,
4544                };
4545                // A turn is never nudged (`retries` 0): a failed seat is
4546                // handed to the next roster agent, which gets the full
4547                // context. An empty answer is a turn, not a failure.
4548                let mut losses = Vec::new();
4549                asked += 1;
4550                let mut results = ask_wave_with::<String>(
4551                    vec![job],
4552                    Arc::clone(&self.sem),
4553                    0,
4554                    &self.roles.judge_roster,
4555                    &ctx,
4556                    &mut losses,
4557                    &mut self.state,
4558                    &|text: &str| {
4559                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4560                    },
4561                )
4562                .await;
4563                if self.state.resource_block.is_some() {
4564                    return self.stop_for_resource();
4565                }
4566                round_losses.extend(losses.iter().cloned());
4567                self.state.quota.extend(losses);
4568                let (updated, res, _) = results.pop().expect("one job in, one result out");
4569                seat = updated;
4570                let agent_id = seat.agent.clone();
4571                self.state.seats.insert(seat.key.clone(), seat);
4572                let body = match res {
4573                    Ok((body, _)) => body,
4574                    // Skip the seat; a CLI's raw error JSON is never read as
4575                    // this judge's position.
4576                    Err(e) => {
4577                        self.state
4578                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4579                        continue;
4580                    }
4581                };
4582                let tentative = verdict::extract_json::<Position>(&body)
4583                    .ok()
4584                    .and_then(|p| p.tentative)
4585                    .and_then(|s| s.trim().chars().next())
4586                    .map(|c| c.to_ascii_uppercase());
4587                self.state.event(
4588                    "deliberate",
4589                    format!(
4590                        "round {round}: judge {} now favours {}",
4591                        j + 1,
4592                        tentative.map_or("—".to_owned(), |c| c.to_string())
4593                    ),
4594                );
4595                turns.push(DeliberationTurn {
4596                    judge: j + 1,
4597                    agent: agent_id,
4598                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4599                    tentative,
4600                });
4601            }
4602            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4603                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4604                return self.stop_for_resource();
4605            }
4606            self.state
4607                .deliberation
4608                .push(DeliberationRound { round, turns });
4609            self.state.save()?;
4610        }
4611
4612        self.state.status = RunStatus::Voting;
4613        self.state.save()?;
4614        Ok(())
4615    }
4616
4617    // ---------------------------------------------------------------- vote
4618
4619    async fn vote(&mut self) -> Result<()> {
4620        if self.hold_base_sync().await? {
4621            return Ok(());
4622        }
4623        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4624        // agent files with `magi task add` name the run that paid for it. The
4625        // prompt overlay is cloned alongside it because the waves borrow it
4626        // while `self` is mutably borrowed by the node's own bookkeeping.
4627        let run_id = self.state.id.clone();
4628        let prompts = self.state.config.prompts.clone();
4629        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4630            return Ok(());
4631        }
4632        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4633        if viable.len() == 1 {
4634            return Ok(());
4635        }
4636        self.state.status = RunStatus::Voting;
4637
4638        let language = self.state.config.graph.language.clone();
4639        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4640        let sessions = self.state.config.graph.sessions;
4641        let artifacts = agent::artifacts_dir(&self.state.dir());
4642        let root = self.state.worktree_root();
4643        let base_short = short(&self.state.base_commit);
4644        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4645
4646        let mut jobs = Vec::new();
4647        let mut seats_at = Vec::new();
4648        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4649            if self
4650                .state
4651                .judgements
4652                .get(j)
4653                .is_some_and(|r| r.failed.is_some())
4654            {
4655                continue;
4656            }
4657            let seat_key = format!("judge-{}", j + 1);
4658            let spec = self.occupant(&seat_key, spec);
4659            let seat = self.seat(&seat_key, &spec.id);
4660            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4661            let text = if has_context(&spec, &seat, sessions) {
4662                prompt::final_vote(&viable, &language)
4663            } else {
4664                full.clone()
4665            };
4666            jobs.push(SeatJob {
4667                spec,
4668                seat,
4669                prompt: text,
4670                cwd: root.join(format!("judge-{}", j + 1)),
4671                timeout,
4672                allow_write: false,
4673                sessions,
4674                artifacts: artifacts.clone(),
4675                stem: format!("vote-judge-{}", j + 1),
4676                handover: Some(full),
4677            });
4678            seats_at.push(j);
4679        }
4680
4681        self.state.event(
4682            "vote",
4683            format!(
4684                "collecting {} final votes one by one, privately",
4685                jobs.len()
4686            ),
4687        );
4688        let allowed = viable.clone();
4689        let mut quota_losses = Vec::new();
4690        let cache = self.state.config.cache_dir();
4691        let ctx = WaveCtx {
4692            carry_seats: false,
4693            pauses: Some((&self.pause, &self.interrupt)),
4694            run: &run_id,
4695            node: "vote",
4696            prompts: &prompts,
4697            cache: cache.as_deref(),
4698            round: None,
4699        };
4700        let results = ask_json_wave::<FinalVote>(
4701            jobs,
4702            Arc::clone(&self.sem),
4703            self.state.config.graph.retries,
4704            &self.roles.judge_roster,
4705            &ctx,
4706            &mut quota_losses,
4707            &mut self.state,
4708            &move |v: &FinalVote| match v.label() {
4709                Some(c) if allowed.contains(&c) => Ok(()),
4710                other => bail!("vote {other:?} is not one of {allowed:?}"),
4711            },
4712        )
4713        .await;
4714        if self.state.resource_block.is_some() {
4715            return self.stop_for_resource();
4716        }
4717        self.state.quota.extend(quota_losses);
4718
4719        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4720            let agent_id = seat.agent.clone();
4721            self.state.seats.insert(seat.key.clone(), seat);
4722            let initial = self
4723                .state
4724                .judgements
4725                .get(j)
4726                .and_then(|r| r.ranking.first().copied());
4727            let mut record = VoteRecord {
4728                judge: j + 1,
4729                agent: agent_id,
4730                vote: None,
4731                reason: String::new(),
4732                changed: false,
4733            };
4734            match res {
4735                Ok((v, _)) => {
4736                    record.vote = v.label();
4737                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4738                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4739                    self.state.event(
4740                        "vote",
4741                        format!(
4742                            "judge {} voted {}{}",
4743                            j + 1,
4744                            record.vote.unwrap_or('?'),
4745                            if record.changed { " (changed)" } else { "" }
4746                        ),
4747                    );
4748                }
4749                Err(e) => {
4750                    self.state
4751                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4752                }
4753            }
4754            self.state.votes.push(record);
4755            self.state.save()?;
4756        }
4757        Ok(())
4758    }
4759
4760    // --------------------------------------------------------------- tally
4761
4762    fn tally(&mut self) -> Result<()> {
4763        if self.state.tally.is_some() {
4764            return Ok(());
4765        }
4766        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4767        let tops: Vec<char> = self
4768            .state
4769            .judgements
4770            .iter()
4771            .filter_map(|j| j.ranking.first().copied())
4772            .collect();
4773        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4774
4775        // A judge whose private vote failed still counted once, in the initial
4776        // ranking; using it beats discarding a whole seat.
4777        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4778        let mut cast: Vec<char> = Vec::new();
4779        for (i, j) in self.state.judgements.iter().enumerate() {
4780            let vote = self
4781                .state
4782                .votes
4783                .iter()
4784                .find(|v| v.judge == i + 1)
4785                .and_then(|v| v.vote)
4786                .or_else(|| j.ranking.first().copied());
4787            if let Some(v) = vote {
4788                *first_choice.entry(v).or_insert(0) += 1;
4789                cast.push(v);
4790            }
4791        }
4792
4793        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4794        for j in &self.state.judgements {
4795            let n = j.ranking.len();
4796            for (pos, label) in j.ranking.iter().enumerate() {
4797                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4798            }
4799        }
4800
4801        let best = first_choice.values().copied().max().unwrap_or(0);
4802        let mut leaders: Vec<char> = first_choice
4803            .iter()
4804            .filter(|(_, v)| **v == best)
4805            .map(|(k, _)| *k)
4806            .collect();
4807        let mut tie_break = None;
4808        if leaders.len() > 1 {
4809            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4810            let borda_leaders: Vec<char> = leaders
4811                .iter()
4812                .copied()
4813                .filter(|l| borda[l] == top_borda)
4814                .collect();
4815            tie_break = Some(if borda_leaders.len() == 1 {
4816                format!(
4817                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4818                    leaders.len()
4819                )
4820            } else {
4821                format!(
4822                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4823                    leaders.len()
4824                )
4825            });
4826            leaders = borda_leaders;
4827            leaders.sort_unstable();
4828        }
4829        let winner = *leaders
4830            .first()
4831            .or(viable.first())
4832            .context("no candidate to declare a winner from")?;
4833
4834        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4835        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4836        let deliberated = !self.state.deliberation.is_empty();
4837
4838        // Whose verdict is this? A rate-limited seat is absent even if it
4839        // ranked before the limit hit, so presence is measured against the
4840        // recorded losses, not just "did a ranking ever appear".
4841        let quota_seats: std::collections::BTreeSet<&str> =
4842            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4843        let mut present = 0usize;
4844        for (i, j) in self.state.judgements.iter().enumerate() {
4845            if quota_seats.contains(j.seat.as_str()) {
4846                continue;
4847            }
4848            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4849            let voted = self
4850                .state
4851                .votes
4852                .iter()
4853                .any(|v| v.judge == i + 1 && v.vote.is_some());
4854            if ranked || voted {
4855                present += 1;
4856            }
4857        }
4858        // Strict majority of the configured panel. A bare majority is real
4859        // signal we can act on, while a minority verdict must never stand in
4860        // for a healthy one. A one-candidate run needs no panel at all, and
4861        // `judges` stays `0` rather than the roster size a panel that never
4862        // sat would otherwise be credited with.
4863        let needs_quorum = viable.len() > 1;
4864        let judges_total = if needs_quorum {
4865            self.roles.judges.len()
4866        } else {
4867            0
4868        };
4869        let quorum = if needs_quorum {
4870            judges_total / 2 + 1
4871        } else {
4872            0
4873        };
4874        let met_quorum = !needs_quorum || present >= quorum;
4875        let uncontested = (!needs_quorum).then(|| {
4876            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4877        });
4878
4879        self.state.event(
4880            "tally",
4881            match &uncontested {
4882                Some(reason) => format!("winner {winner} — {reason}"),
4883                None => format!(
4884                    "winner {winner} — votes {} | initial {} | {} changed | \
4885                     {present}/{judges_total} judges{}",
4886                    first_choice
4887                        .iter()
4888                        .map(|(k, v)| format!("{k}:{v}"))
4889                        .collect::<Vec<_>>()
4890                        .join(" "),
4891                    if unanimous_initial {
4892                        "unanimous"
4893                    } else {
4894                        "split"
4895                    },
4896                    changed_votes,
4897                    if met_quorum {
4898                        String::new()
4899                    } else {
4900                        format!(" — below quorum ({quorum} required)")
4901                    },
4902                ),
4903            },
4904        );
4905        if !met_quorum {
4906            self.state.event(
4907                "stall",
4908                format!(
4909                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4910                     the run stops here, resumable"
4911                ),
4912            );
4913        }
4914        self.state.tally = Some(Tally {
4915            first_choice,
4916            borda,
4917            winner,
4918            rankings: tops.len(),
4919            unanimous_initial,
4920            deliberated,
4921            changed_votes,
4922            unanimous_final,
4923            tie_break,
4924            judges: judges_total,
4925            present,
4926            quorum,
4927            met_quorum,
4928            uncontested,
4929        });
4930        self.state.status = if met_quorum {
4931            RunStatus::Reviewing
4932        } else {
4933            RunStatus::Stalled
4934        };
4935        self.state.save()?;
4936        Ok(())
4937    }
4938
4939    // ------------------------------------------------------------- recover
4940
4941    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4942    /// resumed toward completion once the transient cause clears.
4943    ///
4944    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4945    /// it toward the quorum, which is exactly the set of seats whose absence
4946    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4947    /// not depend on which node happened to hit the limit), or an ordinary
4948    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4949    /// seat is never disturbed.
4950    ///
4951    /// A seat that now answers with a usable ranking is "recovered": its
4952    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4953    /// `tally` counts it present again), and its vote re-collected. A seat that
4954    /// still fails keeps its loss and stays absent.
4955    ///
4956    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4957    /// to review/gate/merge), `false` when it is still below quorum (the run
4958    /// stays `Stalled`, still resumable for a later retry).
4959    #[allow(clippy::too_many_lines)]
4960    async fn recover_stall(&mut self) -> Result<bool> {
4961        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4962        // agent files with `magi task add` name the run that paid for it. The
4963        // prompt overlay is cloned alongside it because the waves borrow it
4964        // while `self` is mutably borrowed by the node's own bookkeeping.
4965        let run_id = self.state.id.clone();
4966        let prompts = self.state.config.prompts.clone();
4967        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4968        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4969        // is what keeps a non-quota collapse — or a quota loss recorded at the
4970        // deliberate node — from being a permanent dead-end on `--resume`.
4971        let quota_seats: BTreeSet<&str> =
4972            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4973        let absent: Vec<String> = self
4974            .state
4975            .judgements
4976            .iter()
4977            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4978            .map(|j| j.seat.clone())
4979            .collect();
4980        if absent.is_empty() {
4981            return Ok(false);
4982        }
4983        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4984        if viable.len() <= 1 {
4985            return Ok(false);
4986        }
4987        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4988        let language = self.state.config.graph.language.clone();
4989        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4990        let sessions = self.state.config.graph.sessions;
4991        let artifacts = agent::artifacts_dir(&self.state.dir());
4992        let root = self.state.worktree_root();
4993        let base_short = short(&self.state.base_commit);
4994        let candidates: Vec<Candidate> = viable.clone();
4995
4996        // Map each absent seat key to its 0-based position in `roles.judges`.
4997        let mut positions: Vec<usize> = absent
4998            .iter()
4999            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5000            .collect();
5001        if positions.is_empty() {
5002            return Ok(false);
5003        }
5004        positions.sort_unstable();
5005        positions.dedup();
5006
5007        // Re-rank the lost seats, one blind prompt each.
5008        let mut judge_jobs = Vec::new();
5009        for &j in &positions {
5010            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5011            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5012            let seat_key = format!("judge-{}", j + 1);
5013            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5014            let seat = self.seat(&seat_key, &spec.id);
5015            judge_jobs.push(SeatJob {
5016                spec,
5017                seat,
5018                prompt: prompt::judge(
5019                    &self.state.instruction,
5020                    &views,
5021                    self.roles.judges.len(),
5022                    &base_short,
5023                    &language,
5024                ),
5025                cwd: root.join(seat_key),
5026                timeout,
5027                allow_write: false,
5028                sessions,
5029                artifacts: artifacts.clone(),
5030                stem: format!("judge-{}-recover", j + 1),
5031                handover: None,
5032            });
5033        }
5034
5035        let labels_for_check = labels.clone();
5036        let mut judge_losses = Vec::new();
5037        let retries = self.state.config.graph.retries;
5038        let cache = self.state.config.cache_dir();
5039        let ctx = WaveCtx {
5040            carry_seats: false,
5041            pauses: Some((&self.pause, &self.interrupt)),
5042            run: &run_id,
5043            node: "judge",
5044            prompts: &prompts,
5045            cache: cache.as_deref(),
5046            round: None,
5047        };
5048        let results = ask_json_wave::<Ranking>(
5049            judge_jobs,
5050            Arc::clone(&self.sem),
5051            retries,
5052            &self.roles.judge_roster,
5053            &ctx,
5054            &mut judge_losses,
5055            &mut self.state,
5056            &move |r: &Ranking| r.validate(&labels_for_check),
5057        )
5058        .await;
5059        if self.state.resource_block.is_some() {
5060            self.stop_for_resource()?;
5061            return Ok(false);
5062        }
5063
5064        // Refresh the judgement of every seat that ranked again.
5065        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5066        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5067            let agent_id = seat.agent.clone();
5068            self.state.seats.insert(seat.key.clone(), seat);
5069            let record = &mut self.state.judgements[j];
5070            match res {
5071                Ok((ranking, out)) => {
5072                    record.agent = agent_id;
5073                    record.ranking = ranking.normalized();
5074                    record.reasons = ranking.reasons;
5075                    record.strengths = ranking.strengths;
5076                    record.confidence = ranking.confidence;
5077                    record.failed = None;
5078                    record.duration_ms = out.duration_ms;
5079                    recovered.insert(j);
5080                    self.state.event(
5081                        "recover",
5082                        format!("judge {} ranked again after the limit", j + 1),
5083                    );
5084                }
5085                Err(e) => {
5086                    self.state
5087                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5088                }
5089            }
5090        }
5091
5092        // Re-ask the votes of the seats that recovered a ranking.
5093        let mut vote_jobs = Vec::new();
5094        let mut vote_pos: Vec<usize> = Vec::new();
5095        for &j in &recovered {
5096            let seat_key = format!("judge-{}", j + 1);
5097            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5098            let seat = self.seat(&seat_key, &spec.id);
5099            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5100            let text = if has_context(&spec, &seat, sessions) {
5101                prompt::final_vote(&labels, &language)
5102            } else {
5103                full.clone()
5104            };
5105            vote_jobs.push(SeatJob {
5106                spec,
5107                seat,
5108                prompt: text,
5109                cwd: root.join(seat_key),
5110                timeout,
5111                allow_write: false,
5112                sessions,
5113                artifacts: artifacts.clone(),
5114                stem: format!("vote-judge-{}-recover", j + 1),
5115                handover: Some(full),
5116            });
5117            vote_pos.push(j);
5118        }
5119        let allowed = labels.clone();
5120        let mut vote_losses = Vec::new();
5121        let vote_retries = self.state.config.graph.retries;
5122        let vote_cache = self.state.config.cache_dir();
5123        let ctx = WaveCtx {
5124            carry_seats: false,
5125            pauses: Some((&self.pause, &self.interrupt)),
5126            run: &run_id,
5127            node: "vote",
5128            prompts: &prompts,
5129            cache: vote_cache.as_deref(),
5130            round: None,
5131        };
5132        let votes = ask_json_wave::<FinalVote>(
5133            vote_jobs,
5134            Arc::clone(&self.sem),
5135            vote_retries,
5136            &self.roles.judge_roster,
5137            &ctx,
5138            &mut vote_losses,
5139            &mut self.state,
5140            &move |v: &FinalVote| match v.label() {
5141                Some(c) if allowed.contains(&c) => Ok(()),
5142                other => bail!("vote {other:?} is not one of {allowed:?}"),
5143            },
5144        )
5145        .await;
5146        if self.state.resource_block.is_some() {
5147            self.stop_for_resource()?;
5148            return Ok(false);
5149        }
5150        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5151            let agent_id = seat.agent.clone();
5152            self.state.seats.insert(seat.key.clone(), seat);
5153            match res {
5154                Ok((v, _)) => {
5155                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5156                        rec.vote = v.label();
5157                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5158                    } else {
5159                        self.state.votes.push(VoteRecord {
5160                            judge: j + 1,
5161                            agent: agent_id,
5162                            vote: v.label(),
5163                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5164                            changed: false,
5165                        });
5166                    }
5167                    self.state.event(
5168                        "recover",
5169                        format!("judge {} voted again after the limit", j + 1),
5170                    );
5171                }
5172                Err(e) => {
5173                    self.state
5174                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5175                }
5176            }
5177        }
5178
5179        // A seat that ranked again is present even if its re-vote failed —
5180        // `tally` falls back to the initial ranking's first choice — so clear
5181        // its quota loss. Seats that still fail keep theirs and stay absent.
5182        let recovered_keys: BTreeSet<String> = recovered
5183            .iter()
5184            .map(|&j| format!("judge-{}", j + 1))
5185            .collect();
5186        self.state
5187            .quota
5188            .retain(|q| !recovered_keys.contains(&q.seat));
5189        // A seat that hit the limit again is a fresh loss, not the old one:
5190        // replace the stale entry so the history stays one-per-seat and the
5191        // daemon can tell this attempt's loss from a previous session's.
5192        for loss in judge_losses.into_iter().chain(vote_losses) {
5193            if recovered_keys.contains(&loss.seat) {
5194                continue;
5195            }
5196            self.state.quota.retain(|q| q.seat != loss.seat);
5197            self.state.quota.push(loss);
5198        }
5199
5200        // Recompute the verdict from the refreshed panel.
5201        self.state.tally = None;
5202        self.tally()?;
5203        Ok(self
5204            .state
5205            .tally
5206            .as_ref()
5207            .map(|t| t.met_quorum)
5208            .unwrap_or(false))
5209    }
5210
5211    // ---------------------------------------------------------------- graft
5212
5213    /// Port the strengths the judges attributed to the losing candidates onto
5214    /// the winner, once, between the tally and the review loop.
5215    ///
5216    /// Best-effort by construction: it returns nothing and fails nothing. A
5217    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5218    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5219    /// the run carries on as if the phase were off. See [`graft`] for the
5220    /// decisions and `AGENTS.md` for the invariants.
5221    ///
5222    /// The one exception is a rollback that could not be confirmed: the
5223    /// rejected commit may still be the winner's tip, so the run is blocked
5224    /// (resumable; the record stays `Running`, which makes a resume retry the
5225    /// restore) instead of reviewing, gating and merging it.
5226    async fn graft(&mut self) -> Result<()> {
5227        let Err(e) = self.graft_inner().await else {
5228            return Ok(());
5229        };
5230        if e.is::<crate::repo_lock::ResourceBlocked>() {
5231            return Err(e);
5232        }
5233        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5234            self.state.status = RunStatus::Blocked;
5235            self.state.event("graft", format!("blocked: {e:#}"));
5236            self.state.save()?;
5237            return Err(e);
5238        }
5239        // An error after the `Running` record was saved may have left the
5240        // fixer's work in the tree: the record must not stay unsettled
5241        // (a later resume would reset past the review fixes), so confirm the
5242        // restore now, or block.
5243        if let Some(rec) = self.state.graft.clone()
5244            && !rec.outcome.settled()
5245        {
5246            if let Some(winner) = self.state.winner().cloned() {
5247                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5248                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5249                        return Err(re);
5250                    }
5251                    self.state.status = RunStatus::Blocked;
5252                    self.state.event("graft", format!("blocked: {re:#}"));
5253                    self.state.save()?;
5254                    return Err(re);
5255                }
5256            }
5257            if let Some(g) = self.state.graft.as_mut() {
5258                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5259            }
5260        }
5261        self.state.event("graft", format!("skipped: {e:#}"));
5262        if let Err(e) = self.state.save() {
5263            tracing::warn!("save after graft: {e:#}");
5264        }
5265        Ok(())
5266    }
5267
5268    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5269    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5270    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5271        let _coordination = self.coordinate(wt).await?;
5272        crate::recovery::restore_repair(wt, pre)
5273            .await
5274            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5275    }
5276
5277    /// A skip is a run event, recorded once however often the node is re-entered.
5278    fn graft_skipped(&mut self, why: &str) {
5279        let message = format!("skipped: {why}");
5280        if !self
5281            .state
5282            .events
5283            .iter()
5284            .any(|e| e.node == "graft" && e.message == message)
5285        {
5286            self.state.event("graft", message);
5287        }
5288    }
5289
5290    async fn graft_inner(&mut self) -> Result<()> {
5291        // A round that was started and never finished (crash, kill): the
5292        // fixer may have left anything in the tree, so put the winner back.
5293        if let Some(rec) = self.state.graft.clone()
5294            && !rec.outcome.settled()
5295        {
5296            // Reviews exist only if the graft ended without its record being
5297            // settled (a swallowed error): the tree has moved on since, and
5298            // a reset to `pre` would discard the review fixes.
5299            if self.state.reviews.is_empty()
5300                && let Some(winner) = self.state.winner().cloned()
5301            {
5302                self.graft_restore(&winner.worktree, &rec.pre).await?;
5303            }
5304            if rec.outcome == GraftOutcome::WaitingForRestore {
5305                self.state.graft = None;
5306                self.state.save()?;
5307            } else {
5308                if let Some(g) = self.state.graft.as_mut() {
5309                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5310                }
5311                self.state.event(
5312                    "graft",
5313                    "rolled back: the previous round was interrupted; the winner is untouched",
5314                );
5315                self.state.save()?;
5316                return Ok(());
5317            }
5318        }
5319        let plan = match graft::plan(&self.state) {
5320            Ok(plan) => plan,
5321            Err(skip) => {
5322                if skip != graft::Skip::AlreadyDone {
5323                    self.graft_skipped(skip.reason());
5324                    self.state.save()?;
5325                }
5326                return Ok(());
5327            }
5328        };
5329        let Some(winner) = self.state.winner().cloned() else {
5330            return Ok(());
5331        };
5332        let wt = winner.worktree.clone();
5333        if !git::is_clean(&wt).await? {
5334            self.graft_skipped("the winner's worktree has uncommitted changes");
5335            self.state.save()?;
5336            return Ok(());
5337        }
5338        let pre = git::rev_parse(&wt, "HEAD").await?;
5339        // Saved before the fixer is called: a stop from here on is repaired
5340        // by the branch above on the next entry.
5341        self.state.graft = Some(GraftRecord {
5342            pre: pre.clone(),
5343            post: None,
5344            lines: None,
5345            limit: None,
5346            agent: None,
5347            outcome: GraftOutcome::Running,
5348            requested: graft::requested(&plan),
5349            adoption: None,
5350            adoption_error: None,
5351        });
5352        self.state.event(
5353            "graft",
5354            format!(
5355                "porting strengths of candidate(s) {} onto {}",
5356                plan.strengths
5357                    .iter()
5358                    .map(|(l, _, _)| l.to_string())
5359                    .collect::<Vec<_>>()
5360                    .join(", "),
5361                plan.winner
5362            ),
5363        );
5364        self.state.save()?;
5365
5366        let fix_prompt = prompt::graft(
5367            &self.state.instruction,
5368            plan.winner,
5369            &plan.strengths,
5370            &self.state.config.graph.language,
5371        );
5372        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5373        let sessions = self.state.config.graph.sessions;
5374        let artifacts = agent::artifacts_dir(&self.state.dir());
5375        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5376        let (_, seat, out) = self
5377            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5378                SeatJob {
5379                    prompt: fix_prompt.clone(),
5380                    spec,
5381                    seat,
5382                    cwd: wt.clone(),
5383                    timeout,
5384                    allow_write: true,
5385                    sessions,
5386                    artifacts: artifacts.clone(),
5387                    stem: "graft".to_owned(),
5388                    handover: None,
5389                }
5390            })
5391            .await;
5392        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5393            // Preserve the need to restore earlier fallback edits without
5394            // confusing an unstarted seat with an interrupted invocation.
5395            self.state.graft.as_mut().expect("graft record").outcome =
5396                GraftOutcome::WaitingForRestore;
5397            return self.stop_for_resource();
5398        }
5399        let mut why: Option<String> = None;
5400        match &out {
5401            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5402                why = Some("the fixer produced nothing usable".to_owned());
5403            }
5404            AgentOutcome::Ok(_) => {}
5405            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5406            AgentOutcome::Quota(o) => {
5407                self.state.quota.push(QuotaLoss::from_report(
5408                    seat.key.clone(),
5409                    "graft",
5410                    o.quota.as_ref(),
5411                ));
5412                why = Some("rate limited (quota)".to_owned());
5413            }
5414            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5415                why = Some(format!(
5416                    "the fixer failed: {}",
5417                    e.lines()
5418                        .next()
5419                        .unwrap_or("")
5420                        .chars()
5421                        .take(160)
5422                        .collect::<String>()
5423                ));
5424            }
5425        }
5426        let agent_id = seat.agent.clone();
5427        self.state.seats.insert(seat.key.clone(), seat);
5428
5429        let mut post = None;
5430        let mut lines = None;
5431        let _coordination = self.coordinate(&wt).await?;
5432        if why.is_none() {
5433            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5434            if let Ok(r) = &rescued {
5435                self.state.note_withheld("graft", &r.withheld);
5436            }
5437            let head = git::rev_parse(&wt, "HEAD").await?;
5438            // What is measured must be what gets reviewed and gated: a failed
5439            // rescue, or anything still uncommitted (withheld lockfiles
5440            // aside, which are never part of the tree), rejects the graft.
5441            let dirty = match &rescued {
5442                Ok(r) => git::status_porcelain(&wt)
5443                    .await
5444                    .map(|st| {
5445                        st.lines().any(|l| {
5446                            !r.withheld
5447                                .iter()
5448                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5449                        })
5450                    })
5451                    .unwrap_or(true),
5452                Err(_) => true,
5453            };
5454            if dirty {
5455                why = Some("the fixer left changes that could not be committed".to_owned());
5456            } else if head == pre {
5457                why = Some("the fixer changed nothing".to_owned());
5458            } else {
5459                lines = git::changed_lines(&wt, &pre, &head).await;
5460                post = Some(head);
5461            }
5462        }
5463        let (adoption, adoption_error) = match &out {
5464            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5465            _ => (None, None),
5466        };
5467        let requested = graft::requested(&plan);
5468        let outcome = match why {
5469            None => {
5470                self.state.event(
5471                    "graft",
5472                    format!(
5473                        "applied: {}",
5474                        lines.map_or_else(
5475                            || "changed lines unavailable".to_owned(),
5476                            |n| format!("{n} changed lines")
5477                        )
5478                    ),
5479                );
5480                GraftOutcome::Applied
5481            }
5482            Some(why) => {
5483                // Not settled until the restore is confirmed: the record
5484                // stays `Running`, so a resume retries it.
5485                crate::recovery::restore_repair(&wt, &pre)
5486                    .await
5487                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5488                self.state.event(
5489                    "graft",
5490                    format!("rolled back: {why}; the winner is untouched"),
5491                );
5492                GraftOutcome::RolledBack(why)
5493            }
5494        };
5495        self.state.graft = Some(GraftRecord {
5496            pre,
5497            post,
5498            lines,
5499            limit: None,
5500            agent: Some(agent_id),
5501            outcome,
5502            requested,
5503            adoption,
5504            adoption_error,
5505        });
5506        self.state.save()?;
5507        Ok(())
5508    }
5509
5510    // ----------------------------------------------------------------- fold
5511
5512    async fn fold_losers(&mut self) -> Result<()> {
5513        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5514            return Ok(());
5515        };
5516        if !self.state.candidate_preservation.is_empty() {
5517            bail!("candidate preservation incomplete; refusing cleanup");
5518        }
5519        let repo = self.state.repo.clone();
5520        let _coordination = self.coordinate(&repo).await?;
5521        let home = crate::run::home();
5522        let root = self.state.worktree_root();
5523        let isolated = crate::build_target::isolated(&self.state.config);
5524        let mut folded = Vec::new();
5525        for i in 0..self.state.candidates.len() {
5526            let c = &self.state.candidates[i];
5527            if c.label == winner || c.folded {
5528                continue;
5529            }
5530            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5531            let target = fold_target(&home, &root, &wt, isolated);
5532            remove_preserved_worktree(&repo, &wt).await?;
5533            reclaim_fold_target(&home, target);
5534            if git::branch_exists(&repo, &branch).await?
5535                && !git::branch_delete(&repo, &branch).await?
5536            {
5537                bail!("candidate branch removal refused");
5538            }
5539            self.state.candidates[i].folded = true;
5540            self.state.save()?;
5541            folded.push(label.to_string());
5542        }
5543        // The judges are finished; their checkouts are pure cost from here.
5544        for j in 1..=self.roles.judges.len() {
5545            let wt = root.join(format!("judge-{j}"));
5546            if wt.exists() {
5547                let target = fold_target(&home, &root, &wt, isolated);
5548                remove_read_seat_worktree(&mut self.state, &wt).await?;
5549                reclaim_fold_target(&home, target);
5550                self.state.save()?;
5551            }
5552        }
5553        // The design-deliberation stage is finished by the time a tally
5554        // exists — same reasoning as the judges above.
5555        if self.state.config.graph.advise {
5556            for k in 1..=self.state.config.graph.advisors {
5557                let wt = root.join(format!("advisor-{k}"));
5558                if wt.exists() {
5559                    let target = fold_target(&home, &root, &wt, isolated);
5560                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5561                    reclaim_fold_target(&home, target);
5562                    self.state.save()?;
5563                }
5564            }
5565        }
5566        if !folded.is_empty() {
5567            self.state
5568                .event("fold", format!("folded candidates {}", folded.join(", ")));
5569            self.state.save()?;
5570        }
5571        Ok(())
5572    }
5573
5574    // ------------------------------------------------------------ base sync
5575
5576    async fn hold_base_sync(&mut self) -> Result<bool> {
5577        self.hold_base_sync_as(None).await
5578    }
5579
5580    async fn hold_base_sync_kind(
5581        &mut self,
5582        kind: crate::base_sync_recovery::StopKind,
5583    ) -> Result<()> {
5584        self.hold_base_sync_as(Some(kind)).await?;
5585        Ok(())
5586    }
5587
5588    async fn hold_base_sync_as(
5589        &mut self,
5590        kind: Option<crate::base_sync_recovery::StopKind>,
5591    ) -> Result<bool> {
5592        if !self.state.base_sync_blocked() {
5593            self.state.base_sync_recovery.stop = None;
5594            return Ok(false);
5595        }
5596        let head = match self.state.winner() {
5597            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5598                .await
5599                .unwrap_or_default(),
5600            None => String::new(),
5601        };
5602        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5603            && !authorization.consumed
5604            && authorization.stop.head != head
5605        {
5606            authorization.refuse(format!(
5607                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5608                authorization.stop.head
5609            ));
5610        }
5611        self.state.record_base_sync_stop(&head);
5612        if let Some(kind) = kind {
5613            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5614            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5615                stop.kind = kind;
5616            }
5617        }
5618        self.state.save()?;
5619        Ok(true)
5620    }
5621
5622    async fn resume_legacy_sequencer_stop(
5623        &mut self,
5624        winner: &Candidate,
5625        scratch: &Path,
5626        head: &str,
5627    ) -> Result<()> {
5628        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5629
5630        if !resumable_sequencer_stop(&self.state)
5631            || legacy_sequencer_head(&self.state) != Some(head)
5632            || self.state.base_recovery_pending()
5633            || self
5634                .state
5635                .repair_grants
5636                .iter()
5637                .any(|grant| !grant.succeeded)
5638        {
5639            return Ok(());
5640        }
5641        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5642            return Ok(());
5643        };
5644        let owner = crate::queue::Queue::open().get(task)?;
5645        if owner.execution_runs().last() != Some(&self.state.id)
5646            || owner.status == crate::queue::TaskStatus::Done
5647            || owner.fresh_start
5648            || owner.review_branch.is_some()
5649            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5650        {
5651            return Ok(());
5652        }
5653
5654        let repo = self.state.repo.clone();
5655        let wait = repository_wait(&self.state, None);
5656        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5657        let common = crate::repo_lock::common_dir(&repo).await?;
5658        let op = self.state.base_sync_recovery.operations.last().unwrap();
5659        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5660            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5661            || git::current_branch(&winner.worktree).await?.as_deref()
5662                != Some(winner.branch.as_str())
5663            || common.is_none()
5664            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5665            || crate::repo_lock::common_dir(&owner.repo).await? != common
5666            || !git::is_clean(&winner.worktree).await?
5667        {
5668            return Ok(());
5669        }
5670        if scratch.try_exists()? {
5671            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5672            if admin.join("locked").try_exists()?
5673                || !git::git(
5674                    scratch,
5675                    &[
5676                        "status",
5677                        "--porcelain",
5678                        "--untracked-files=all",
5679                        "--ignored",
5680                    ],
5681                )
5682                .await?
5683                .is_empty()
5684            {
5685                return Ok(());
5686            }
5687            if git::checked_rebase_in_progress(scratch).await? {
5688                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5689                    || crate::rebase::rebase_target(scratch).await? != op.tip
5690                    || !git::unmerged_paths(scratch).await?.is_empty()
5691                {
5692                    return Ok(());
5693                }
5694            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5695                || git::rev_parse(scratch, "HEAD").await? != head
5696            {
5697                return Ok(());
5698            }
5699        }
5700
5701        self.state
5702            .base_sync_recovery
5703            .operations
5704            .last_mut()
5705            .unwrap()
5706            .finished = false;
5707        let diagnostic = self
5708            .state
5709            .base_sync
5710            .as_mut()
5711            .unwrap()
5712            .conflict
5713            .take()
5714            .unwrap();
5715        self.state.base_sync_recovery.stop = None;
5716        self.state.event(
5717            "rebase",
5718            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5719        );
5720        self.state.save()
5721    }
5722
5723    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5724    /// anything verifies it.
5725    ///
5726    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5727    /// read whatever is checked out in the winner's worktree. Left alone that
5728    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5729    /// it when the run *branched* - and a run takes long enough that the base
5730    /// has usually moved by the time it gets here. A gate that ran there
5731    /// answers "green on the commit this run started from", not "green on
5732    /// what is about to land", and the difference showed up three times in
5733    /// one day as a green run whose merge would have reverted a file another
5734    /// pull request had already landed.
5735    ///
5736    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5737    /// `land::Step::Rebase` calls, rather than a second implementation of the
5738    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5739    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5740    /// doc warns about ("two answers to a question nobody notices until a
5741    /// diff is wrong").
5742    ///
5743    /// Foreign-checkout reviews instead merge the base into the owned shadow
5744    /// worktree, preserving the ancestry required for fast-forward delivery.
5745    /// A conflicting merge is aborted and held for operator resolution.
5746    ///
5747    /// A conflict is not the end of the road: the standing rebase is handed
5748    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5749    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5750    /// land). Once it finishes, review and the gate run as usual on the
5751    /// rebased tree, which is where a breakage the new base caused is caught
5752    /// by the ordinary gate-fix round. magi resolves nothing itself.
5753    ///
5754    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5755    /// the current durable recovery interval, bounds how often the base is
5756    /// synchronized during active recovery (lifetime attempts remain evidence).
5757    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5758    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5759    /// what was tried (rounds spent, paths still conflicted) and the branch
5760    /// and worktree stay exactly as they were - untouched, for a person to
5761    /// look at - which is also what makes re-entering this function
5762    /// afterwards a no-op instead of a second attempt at the same wall. A
5763    /// push failure ends the same way.
5764    async fn sync_to_base(&mut self) -> Result<()> {
5765        if self.state.status == RunStatus::AlreadyInBase {
5766            return Ok(());
5767        }
5768        self.hold_base_sync().await?;
5769        let Some(winner) = self.state.winner().cloned() else {
5770            return Ok(());
5771        };
5772
5773        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5774
5775        let repo = self.state.repo.clone();
5776        let remote = self.state.config.merge.remote.clone();
5777        let base_branch = self.state.base_branch.clone();
5778        let tracking = format!("{remote}/{base_branch}");
5779
5780        let fetched_base =
5781            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5782        if !fetched_base
5783            && self
5784                .state
5785                .base_sync_recovery
5786                .stop
5787                .as_ref()
5788                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5789        {
5790            self.state.event(
5791                "land",
5792                "cannot recheck recorded public branch divergence without a fresh base",
5793            );
5794            self.state.save()?;
5795            return Ok(());
5796        }
5797        // No network, or the remote never had this branch: the run already
5798        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5799        // otherwise), and one that got this far is not blocked by a fetch
5800        // that fails now. It just has no newer tip to compare against.
5801        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5802            return Ok(());
5803        };
5804
5805        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5806        self.state.ensure_base_episode();
5807        let scratch = self.state.dir().join("base-sync");
5808        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
5809            .await?;
5810        let conflicted = self
5811            .state
5812            .base_sync
5813            .as_ref()
5814            .is_some_and(|s| s.conflict.is_some());
5815        let mut pending = self.state.pending_base_operation().cloned();
5816        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
5817        {
5818            Ok(active) => active,
5819            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
5820            Err(error) => return Err(error),
5821        };
5822        if in_progress {
5823            // Older resource stops predate operation reservations. Import the
5824            // standing Git operation, never retarget it to today's main.
5825            if pending.is_none()
5826                && self.state.base_sync_recovery.operations.is_empty()
5827                && !conflicted
5828                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5829                    .await
5830                    .ok()
5831                    .as_deref()
5832                    == Some(head.as_str())
5833                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5834                && git::is_clean(&winner.worktree).await?
5835            {
5836                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5837                if self.state.base_sync.is_none() {
5838                    self.state.base_sync = Some(BaseSync {
5839                        tip: saved_tip.clone(),
5840                        behind: 0,
5841                        attempts: 0,
5842                        conflict: None,
5843                        already_in: None,
5844                    });
5845                }
5846                self.state.reserve_base_operation(&head, &saved_tip);
5847                self.state.event(
5848                    "base-recovery",
5849                    "imported standing legacy rebase as a spent synchronization reservation",
5850                );
5851                self.state.save()?;
5852                pending = self.state.base_sync_recovery.operations.last().cloned();
5853            }
5854            let expected = pending.as_ref().map(|op| op.tip.as_str());
5855            if expected.is_none()
5856                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5857            {
5858                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5859                if self.state.base_sync.is_none() {
5860                    self.state.base_sync = Some(BaseSync {
5861                        tip: tip.clone(),
5862                        behind: 0,
5863                        attempts: 0,
5864                        conflict: None,
5865                        already_in: None,
5866                    });
5867                }
5868                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
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        }
5875        if let Some(op) = &pending {
5876            // A replay may add the pinned base's commits, never foreign work.
5877            let mut replay_proven =
5878                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5879            if !replay_proven && !in_progress && scratch.try_exists()? {
5880                let wait = repository_wait(&self.state, None);
5881                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5882                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5883                    Ok(true) => {
5884                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5885                        self.state.save()?;
5886                        git::worktree_remove(&repo, &scratch).await.ok();
5887                        replay_proven = true;
5888                    }
5889                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5890                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5891                }
5892            }
5893            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5894                if self.state.foreign_checkout.is_some() {
5895                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5896                        .await
5897                        .ok()
5898                        .as_deref()
5899                        == Some(op.head.as_str())
5900                        && git::rev_parse(&repo, &format!("{head}^2"))
5901                            .await
5902                            .ok()
5903                            .as_deref()
5904                            == Some(op.tip.as_str());
5905                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5906                    .await
5907                    .is_ok_and(|m| m.is_empty())
5908                    && let Ok(added) =
5909                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5910                {
5911                    replay_proven = true;
5912                    for commit in added {
5913                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5914                            replay_proven = false;
5915                            break;
5916                        }
5917                    }
5918                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5919                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5920                }
5921            }
5922            // Never retarget an operation across a crash, even if main moved.
5923            // sync_to_head resets and cleans with -x, so even ignored untracked
5924            // files must stop recovery independently of the old tracked tree.
5925            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5926                || (head != op.head
5927                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5928                        .await?
5929                        .is_empty())
5930                || (!git::is_clean(&winner.worktree).await?
5931                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5932                        .await
5933                        .is_ok_and(|o| o.ok()))
5934                || !replay_proven
5935            {
5936                let why = format!(
5937                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5938                    op.id
5939                );
5940                let sync = self
5941                    .state
5942                    .base_sync
5943                    .as_mut()
5944                    .context("reserved synchronization has no lifetime accounting")?;
5945                sync.conflict = Some(why.clone());
5946                self.state.event("land", why);
5947                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5948                    .await?;
5949                return Ok(());
5950            }
5951            if head != op.head {
5952                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5953            }
5954            tip = op.tip.clone();
5955        }
5956        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5957        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5958        if pending.is_none()
5959            && !conflicted
5960            && fetched_base
5961            && self
5962                .state
5963                .base_sync_recovery
5964                .episodes
5965                .last()
5966                .is_some_and(|e| e.boundary.is_some())
5967            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5968            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5969            && owner.execution_runs().last() == Some(&self.state.id)
5970            && owner.status != crate::queue::TaskStatus::Done
5971            && !owner.fresh_start
5972            && owner.review_branch.is_none()
5973            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5974            && let Some(approval) = owner.resumption.as_ref()
5975            && approval.instruction == owner.instruction
5976            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5977            && git::is_clean(&winner.worktree).await?
5978            && self.state.renew_base_episode(&task, approval, &head, &tip)
5979        {
5980            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5981            self.state.save()?;
5982        }
5983
5984        // Before any rebase, and before a recorded conflict is honoured: a
5985        // branch whose change reached the base under other commit ids has
5986        // nothing to rebase and nothing to conflict with, and a run that
5987        // already stopped on that phantom conflict recovers here on resume.
5988        // `behind == 0` with head == tip is a branch the base has since taken
5989        // in whole, whether or not a conflict was ever recorded: the ancestry
5990        // proof must still run (`classify` ignores a head still on the start
5991        // commit).
5992        if (behind > 0 || conflicted || head == tip)
5993            && self
5994                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5995                .await?
5996        {
5997            return Ok(());
5998        }
5999        if conflicted && self.state.base_recovery_pending() {
6000            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6001            let owner =
6002                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6003            let owner_valid = owner.as_ref().is_ok_and(|t| {
6004                t.execution_runs().last() == Some(&self.state.id)
6005                    && t.status != crate::queue::TaskStatus::Done
6006                    && !t.fresh_start
6007                    && t.review_branch.is_none()
6008            });
6009            let invalidation = if !owner_valid {
6010                Some("latest task ownership changed")
6011            } else if !owner.as_ref().is_ok_and(|t| {
6012                authorization
6013                    .generation
6014                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6015            }) {
6016                Some("owner approval generation changed")
6017            } else if authorization.question.as_ref().is_some_and(|question| {
6018                !crate::base_recovery_control::decision_current(
6019                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6020                    &self.state,
6021                    &authorization.task,
6022                    question,
6023                )
6024            }) {
6025                Some("recovery decision ownership, routing or stop evidence changed")
6026            } else if authorization.request.is_some()
6027                && !owner
6028                    .as_ref()
6029                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6030            {
6031                Some("owner decision changed")
6032            } else if let Some(scope) = &authorization.scope {
6033                if scope.tip != tip {
6034                    Some("fetched base changed")
6035                } else if !self
6036                    .state
6037                    .base_sync_recovery
6038                    .episodes
6039                    .last()
6040                    .is_some_and(|e| e.id == scope.episode)
6041                {
6042                    Some("active synchronization interval changed")
6043                } else if !owner
6044                    .as_ref()
6045                    .is_ok_and(|t| t.instruction == scope.instruction)
6046                {
6047                    Some("task instruction changed")
6048                } else {
6049                    None
6050                }
6051            } else {
6052                None
6053            };
6054            if let Some(reason) = invalidation {
6055                let authorization = self
6056                    .state
6057                    .base_sync_recovery
6058                    .authorizations
6059                    .last_mut()
6060                    .unwrap();
6061                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6062                self.state.save()?;
6063                return Ok(());
6064            }
6065            if !fetched_base
6066                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6067                || !git::is_clean(&winner.worktree).await?
6068                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6069            {
6070                return Ok(());
6071            }
6072        }
6073        let recovery = conflicted && self.state.consume_base_recovery(&head);
6074        if conflicted {
6075            // Consumption (including a refused changed HEAD) is durable before Git.
6076            self.state.save()?;
6077            if !recovery {
6078                return Ok(());
6079            }
6080        }
6081
6082        if behind == 0 {
6083            // A fixer-finished rebase moves the branch ref before the
6084            // winner's worktree is told (`sync_to_head` below). A run that
6085            // died in between resumes here with `behind == 0` and a tree still
6086            // holding the pre-rebase files, which review and the gate would
6087            // then read. That state is exactly: HEAD moved off the tip the
6088            // rebase started from, yet the tree is still identical to that
6089            // tip. A tree with edits of its own differs from it, so nothing
6090            // is thrown away.
6091            if let Some(from) = self
6092                .state
6093                .rebase_fixes
6094                .iter()
6095                .rev()
6096                .find_map(|r| r.from.clone())
6097                && from != head
6098                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6099                    .await
6100                    .is_ok_and(|o| o.ok())
6101            {
6102                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6103            }
6104            // An earlier attempt may have rebased the branch locally and died
6105            // before pushing it (only the fresh-rebase arm below pushes).
6106            // Publish it now, so the plain push at PR time is not refused as
6107            // a non-fast-forward. A run already holding a recorded conflict
6108            // never reaches here; that case is out of scope.
6109            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6110            if let Some(why) = &conflict {
6111                self.state.status = RunStatus::Blocked;
6112                self.state.event("land", why.clone());
6113            }
6114            self.state.base_sync = Some(BaseSync {
6115                tip,
6116                behind: 0,
6117                attempts,
6118                conflict,
6119                already_in: None,
6120            });
6121            if pending.is_some() {
6122                self.state.finish_base_operation(Some(&head));
6123            }
6124            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6125                .await?;
6126            self.state.save()?;
6127            return Ok(());
6128        }
6129
6130        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6131            let why = format!(
6132                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6133                 synchronization(s); synchronizing again would only race it",
6134                winner.branch
6135            );
6136            self.state.status = RunStatus::Blocked;
6137            self.state.base_sync = Some(BaseSync {
6138                tip,
6139                behind,
6140                attempts,
6141                conflict: Some(why.clone()),
6142                already_in: None,
6143            });
6144            self.state.event("land", why);
6145            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6146                .await?;
6147            self.state.save()?;
6148            return Ok(());
6149        }
6150
6151        if self.state.foreign_checkout.is_some() {
6152            // Delivery to the operator's checkout is fast-forward only. A
6153            // rebase here would discard its saved head from our ancestry.
6154            let wait = repository_wait(&self.state, None);
6155            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6156            if self.state.base_sync.is_none() {
6157                self.state.base_sync = Some(BaseSync {
6158                    tip: tip.clone(),
6159                    behind,
6160                    attempts: 0,
6161                    conflict: None,
6162                    already_in: None,
6163                });
6164            }
6165            self.state.reserve_base_operation(&head, &tip);
6166            self.state.save()?;
6167            let merged = git::git_raw(
6168                &winner.worktree,
6169                &[
6170                    "-c",
6171                    "core.hooksPath=/dev/null",
6172                    "merge",
6173                    "--no-ff",
6174                    "--no-autostash",
6175                    "--no-edit",
6176                    "-m",
6177                    &format!("Merge {tracking} before verifying"),
6178                    &tip,
6179                ],
6180            )
6181            .await?;
6182            let conflict = if merged.ok() {
6183                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6184                self.state.event(
6185                    "land",
6186                    format!("merged {tracking} into {} before verifying", winner.branch),
6187                );
6188                None
6189            } else {
6190                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6191                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6192                }
6193                let why = format!(
6194                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6195                    winner.branch,
6196                    merged.stderr.chars().take(600).collect::<String>()
6197                );
6198                self.state.status = RunStatus::Blocked;
6199                self.state.event("land", &why);
6200                Some(why)
6201            };
6202            let synced = conflict.is_none();
6203            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6204            self.state
6205                .finish_base_operation(synced.then_some(fresh.as_str()));
6206            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6207            self.state.base_sync = Some(BaseSync {
6208                tip,
6209                behind: if synced { 0 } else { behind },
6210                attempts,
6211                conflict,
6212                already_in: None,
6213            });
6214            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6215                .await?;
6216            self.state.save()?;
6217            return Ok(());
6218        }
6219
6220        self.state.event(
6221            "land",
6222            format!(
6223                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6224                winner.branch
6225            ),
6226        );
6227        self.state.save()?;
6228
6229        // The remote's copy of the branch, read now and only if the fetch
6230        // really succeeded (a stale tracking ref must never pin a lease). It is
6231        // pushed over after a rebase only when it is a commit this branch
6232        // already contains, by ancestry or by patch (an earlier rebase of ours
6233        // that never reached the remote): anything else is somebody else's work.
6234        let branch_tracking = format!("{remote}/{}", winner.branch);
6235        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6236        let remote_tip = if self.state.task_pr_branch().is_none()
6237            && matches!(&fetched_branch, Ok(o) if o.ok())
6238        {
6239            git::rev_parse(&repo, &branch_tracking).await.ok()
6240        } else {
6241            None
6242        };
6243        // A remote tip this branch does not contain is somebody else's work:
6244        // rebasing would leave a local tip that can never be pushed. Stop
6245        // before touching anything and say so.
6246        if let Some(theirs) = &remote_tip
6247            && !git::is_ancestor(&repo, theirs, &head).await
6248            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6249                .await
6250                .is_ok_and(|missing| missing.is_empty())
6251        {
6252            let why = format!(
6253                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6254                 them",
6255                short(theirs),
6256                winner.branch
6257            );
6258            self.state.status = RunStatus::Blocked;
6259            self.state.base_sync = Some(BaseSync {
6260                tip,
6261                behind,
6262                attempts,
6263                conflict: Some(why.clone()),
6264                already_in: None,
6265            });
6266            self.state.event("land", why);
6267            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6268                .await?;
6269            self.state.save()?;
6270            return Ok(());
6271        }
6272
6273        if self.state.base_sync.is_none() {
6274            self.state.base_sync = Some(BaseSync {
6275                tip: tip.clone(),
6276                behind,
6277                attempts: 0,
6278                conflict: None,
6279                already_in: None,
6280            });
6281        }
6282        let scratch = self.state.dir().join("base-sync");
6283        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6284        {
6285            if error.is::<crate::repo_lock::ResourceBlocked>() {
6286                return Ok(());
6287            }
6288            return Err(error);
6289        }
6290        self.state.reserve_base_operation(&head, &tip);
6291        self.state.save()?;
6292        let rebased =
6293            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6294                .await
6295            {
6296                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6297                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6298                Err(e) => Err(e),
6299            };
6300        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6301        let stop_kind = match &rebased {
6302            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6303            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6304            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6305        };
6306        match rebased {
6307            Ok(None) => {
6308                // The branch ref moved, but a worktree that already had it
6309                // checked out (the winner's) was not told; sync its index and
6310                // files before anything reads them.
6311                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6312                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6313                self.state.finish_base_operation(Some(&fresh));
6314                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6315                let mut conflict = None;
6316                if let Some(pinned) = &remote_tip {
6317                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6318                    match pushed {
6319                        Ok(o) if o.ok() => self.state.event(
6320                            "land",
6321                            format!("pushed rebased {} to {remote}", winner.branch),
6322                        ),
6323                        Ok(o) => {
6324                            conflict = Some(format!(
6325                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6326                                winner.branch,
6327                                short(pinned),
6328                                o.stderr.chars().take(600).collect::<String>()
6329                            ));
6330                        }
6331                        Err(e) => {
6332                            conflict = Some(format!(
6333                                "rebased {} locally but could not push it: {e:#}",
6334                                winner.branch
6335                            ));
6336                        }
6337                    }
6338                }
6339                if let Some(why) = &conflict {
6340                    self.state.status = RunStatus::Blocked;
6341                    self.state.event("land", why.clone());
6342                }
6343                self.state.base_sync = Some(BaseSync {
6344                    tip: tip.clone(),
6345                    behind: 0,
6346                    attempts,
6347                    conflict,
6348                    already_in: None,
6349                });
6350                self.state
6351                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6352            }
6353            Ok(Some(conflict)) => {
6354                self.state.finish_base_operation(None);
6355                let why = format!(
6356                    "{} conflicts with {tracking} and did not rebase: {}",
6357                    winner.branch,
6358                    conflict.chars().take(600).collect::<String>()
6359                );
6360                self.state.status = RunStatus::Blocked;
6361                self.state.base_sync = Some(BaseSync {
6362                    tip,
6363                    behind,
6364                    attempts,
6365                    conflict: Some(why.clone()),
6366                    already_in: None,
6367                });
6368                self.state.event("land", why);
6369            }
6370            // A refused Git write or a busy repository: nothing is wrong with
6371            // the branch. The scratch rebase stays standing and the run
6372            // resumes into it (`base_sync` must not claim a conflict).
6373            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6374                self.state.save()?;
6375                return Ok(());
6376            }
6377            Err(e) => {
6378                self.state.finish_base_operation(None);
6379                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6380                self.state.status = RunStatus::Blocked;
6381                self.state.base_sync = Some(BaseSync {
6382                    tip,
6383                    behind,
6384                    attempts,
6385                    conflict: Some(why.clone()),
6386                    already_in: None,
6387                });
6388                self.state.event("land", why);
6389            }
6390        }
6391        if !self.state.base_sync_blocked() {
6392            self.state.base_sync_recovery.stop = None;
6393        }
6394        self.hold_base_sync_kind(stop_kind).await?;
6395        self.state.save()?;
6396        Ok(())
6397    }
6398
6399    /// Push a branch an earlier attempt rebased locally but never published,
6400    /// pinned to the remote tip read right after a successful fetch. Returns
6401    /// the reason when the run must stop; `None` when there was nothing to do
6402    /// (no remote copy, the same tip, or a remote copy this branch already
6403    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6404    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6405        // Task competitions publish only after the PR text gate, to their
6406        // public head; never resurrect a candidate branch on the remote.
6407        if self.state.task_pr_branch().is_some() {
6408            return None;
6409        }
6410        let repo = self.state.repo.clone();
6411        let remote = self.state.config.merge.remote.clone();
6412        let fetched = git::fetch(&repo, &remote, branch).await;
6413        if !matches!(&fetched, Ok(o) if o.ok()) {
6414            return None;
6415        }
6416        let branch_tracking = format!("{remote}/{branch}");
6417        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6418        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6419            return None;
6420        }
6421        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6422            .await
6423            .is_ok_and(|missing| missing.is_empty())
6424        {
6425            return Some(format!(
6426                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6427                 them",
6428                short(&theirs)
6429            ));
6430        }
6431        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6432            Ok(o) if o.ok() => {
6433                self.state
6434                    .event("land", format!("pushed rebased {branch} to {remote}"));
6435                None
6436            }
6437            Ok(o) => Some(format!(
6438                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6439                 someone may have pushed): {}",
6440                short(&theirs),
6441                o.stderr.chars().take(600).collect::<String>()
6442            )),
6443            Err(e) => Some(format!(
6444                "{branch} is rebased locally but could not be pushed: {e:#}"
6445            )),
6446        }
6447    }
6448
6449    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6450    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6451    /// whether it did.
6452    ///
6453    /// Checked only when the base is ahead of the branch. A failing check is
6454    /// "not proven" - the ordinary rebase path then decides - never a reason to
6455    /// stop the run.
6456    ///
6457    /// The remote copy of the branch is held to the same standard as the local
6458    /// one: if it carries a tip this worktree does not, that tip must itself be
6459    /// proven in the base, or nothing is settled (a pull request would
6460    /// otherwise be closed over commits nobody checked). The pull request is
6461    /// closed *before* the terminal status is saved; if that fails for a
6462    /// reason other than a refusal (no network, a `gh` error) the run is left
6463    /// `Blocked` with the reason as its conflict, which a resume retries -
6464    /// the same recovery a phantom conflict gets.
6465    async fn settle_already_in(
6466        &mut self,
6467        branch: &str,
6468        tip: &str,
6469        head: &str,
6470        attempts: usize,
6471        behind: usize,
6472    ) -> Result<bool> {
6473        let repo = self.state.repo.clone();
6474        let remote = self.state.config.merge.remote.clone();
6475        let start = self.state.base_commit.clone();
6476        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6477            Ok(Some(e)) => e,
6478            Ok(None) => return Ok(false),
6479            Err(e) => {
6480                tracing::warn!("already-in-base check for {branch}: {e:#}");
6481                return Ok(false);
6482            }
6483        };
6484        let mut verified = vec![head.to_owned()];
6485        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6486        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6487        let divergence = self
6488            .state
6489            .base_sync_recovery
6490            .stop
6491            .as_ref()
6492            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6493        if matches!(&fetched, Ok(o) if o.ok()) {
6494            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6495                Ok(theirs) if theirs != head => {
6496                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6497                        Ok(Some(_)) => verified.push(theirs),
6498                        _ => return Ok(false),
6499                    }
6500                }
6501                Err(_) if divergence => return Ok(false),
6502                _ => {}
6503            }
6504        } else if divergence
6505            && !matches!(
6506                git::remote_has_branch(&repo, &remote, &public_branch).await,
6507                Ok(false)
6508            )
6509        {
6510            // A failed fetch cannot discharge a recorded divergence.
6511            return Ok(false);
6512        }
6513        let base_branch = self.state.base_branch.clone();
6514        let message = format!(
6515            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6516             land",
6517            evidence.names(),
6518            evidence.proof.as_str()
6519        );
6520        let closed =
6521            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6522                .await;
6523        match closed {
6524            Ok(Ok(url)) => self
6525                .state
6526                .event("land", format!("closed {url}: superseded on {base_branch}")),
6527            Ok(Err(why)) => self
6528                .state
6529                .event("land", format!("did not close a pull request: {why}")),
6530            Err(e) => {
6531                let why = format!(
6532                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6533                     not be closed ({e:#}); resume to retry"
6534                );
6535                self.state.status = RunStatus::Blocked;
6536                self.state.base_sync = Some(BaseSync {
6537                    tip: tip.to_owned(),
6538                    behind,
6539                    attempts,
6540                    conflict: Some(why.clone()),
6541                    already_in: None,
6542                });
6543                self.state.event("land", why);
6544                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6545                    .await?;
6546                self.state.save()?;
6547                return Ok(true);
6548            }
6549        }
6550        self.state.status = RunStatus::AlreadyInBase;
6551        self.state.base_sync_recovery.stop = None;
6552        self.state.base_sync = Some(BaseSync {
6553            tip: tip.to_owned(),
6554            behind,
6555            attempts,
6556            conflict: None,
6557            already_in: Some(evidence),
6558        });
6559        self.state.event("land", message);
6560        self.state.save()?;
6561        self.settle_questions();
6562        Ok(true)
6563    }
6564
6565    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6566    /// last landed the winner on, once it has run, else the commit the run
6567    /// branched from.
6568    ///
6569    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6570    /// and `vote` all happen before there is a winner to rebase, so they
6571    /// compare every candidate against the branch point on purpose, and a
6572    /// base that moves after they are already done cannot change an answer
6573    /// they already gave.
6574    fn landing_base(&self) -> String {
6575        self.state
6576            .base_sync
6577            .as_ref()
6578            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6579    }
6580
6581    // ------------------------------------------------------- operator fix
6582
6583    /// Route specific, already-recorded review findings to a fixer for a
6584    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6585    /// entry point.
6586    ///
6587    /// Distinct from `review_loop`'s own fix step in three ways: it never
6588    /// runs a reviewer wave, it never spends review-round budget, and what
6589    /// happened is recorded as an [`OperatorFixRequest`] appended to
6590    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6591    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6592    /// and vote must never be rewritten to look like a manufactured blocking
6593    /// verdict.
6594    ///
6595    /// Only meaningful once review has actually concluded: `Ready` (handed
6596    /// off with findings still open, or simply concluded clean while minor
6597    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6598    /// gate failed). Everything else is refused: a run still in progress
6599    /// should simply be resumed, and a `Merged` run's branch has already
6600    /// landed — reopening *this* run's own record cannot change that, so the
6601    /// answer there is a fresh `magi review <branch>`.
6602    ///
6603    /// A real commit here re-verifies through a fresh, ordinary review-only
6604    /// run on the same branch ([`Self::review`]) rather than reopening this
6605    /// run's own `review_loop`: once any round in this run's history went
6606    /// clean, `review_conclusion` treats that as permanent by design (the
6607    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6608    /// way to force one more genuine reviewer wave out of *this* run without
6609    /// either rewriting history or weakening that guarantee for every other
6610    /// caller. A review-only run costs nothing extra — no implementation, no
6611    /// judging, no vote — and exercises the exact same review → verify →
6612    /// gate → (human) merge path, unmodified.
6613    pub async fn fix_selected(
6614        &mut self,
6615        ids: &[String],
6616        reason: &str,
6617        allow_stale: bool,
6618    ) -> Result<()> {
6619        let reason = reason.trim();
6620        if reason.is_empty() {
6621            bail!("a fix request needs a reason — that is the operator's own record of why");
6622        }
6623        if ids.is_empty() {
6624            bail!("no finding id given");
6625        }
6626        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6627            bail!(
6628                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6629                 has already concluded — can be given a targeted fix. A run still \
6630                 in progress should simply be resumed; a `merged` run's branch has \
6631                 already landed, so its answer is a fresh `magi review <branch>`, \
6632                 not reopening this run's own record",
6633                self.state.id,
6634                self.state.status.as_str()
6635            );
6636        }
6637        // Reassignment shares this claim through its atomic task save. Check
6638        // the canonical run identity inside it, before preflight or any await.
6639        let _claim = FixClaim::acquire(&self.state.dir())?;
6640        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6641        let home = crate::run::home();
6642        // The ordinary driver takes these same locks at admission. Keep the
6643        // execution lease through the fix, but never the owner lock across Git
6644        // or agent awaits.
6645        let execution = {
6646            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6647            let disk = RunState::load(&self.state.id)?;
6648            crate::pr_head::ensure_owner(&disk)?;
6649            anyhow::ensure!(
6650                disk.status == self.state.status && disk.released_to.is_none(),
6651                "run changed since it was loaded; reload before fixing"
6652            );
6653            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6654            anyhow::ensure!(
6655                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6656                "run {} is currently being worked on or its ownership is unknown",
6657                disk.id
6658            );
6659            let lease = crate::driver::maintenance(&home, &disk.id).context(
6660                "run is currently being worked on or its execution lease is unavailable",
6661            )?;
6662            self.state = disk;
6663            lease
6664        };
6665        let Some(winner) = self.state.winner().cloned() else {
6666            bail!("run {} has no winning candidate to fix", self.state.id);
6667        };
6668        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6669            bail!(
6670                "branch `{}` no longer exists; this run cannot be extended",
6671                winner.branch
6672            );
6673        }
6674        // Resolve every id before spending anything — an unknown id refuses
6675        // the whole request rather than silently dropping it — and dedup
6676        // while keeping the operator's own order.
6677        let mut seen = BTreeSet::new();
6678        let mut findings = Vec::new();
6679        let mut missing = Vec::new();
6680        for id in ids {
6681            if !seen.insert(id.clone()) {
6682                continue;
6683            }
6684            match self.state.finding(id) {
6685                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6686                    id: f.id.clone(),
6687                    severity: f.severity,
6688                    reviewer_vote: rec.vote,
6689                    round: round.round,
6690                    round_head: round.head.clone(),
6691                    reviewer: rec.reviewer,
6692                    agent: rec.agent.clone(),
6693                    file: f.file.clone(),
6694                    line: f.line,
6695                    title: f.title.clone(),
6696                    detail: f.detail.clone(),
6697                    outcome: OperatorFixOutcome::Pending,
6698                }),
6699                None => missing.push(id.clone()),
6700            }
6701        }
6702        if !missing.is_empty() {
6703            bail!(
6704                "unknown finding id(s): {}; nothing was changed",
6705                missing.join(", ")
6706            );
6707        }
6708
6709        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6710        let stale_details: Vec<(String, String)> = findings
6711            .iter()
6712            .filter(|f| f.round_head != head_at_request)
6713            .map(|f| (f.id.clone(), f.round_head.clone()))
6714            .collect();
6715        let stale = !stale_details.is_empty();
6716        if stale && !allow_stale {
6717            bail!(
6718                "the branch has moved since some finding(s) were raised — {} — now \
6719                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6720                stale_details
6721                    .iter()
6722                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6723                    .collect::<Vec<_>>()
6724                    .join(", "),
6725                short(&head_at_request)
6726            );
6727        }
6728
6729        let request = OperatorFixRequest {
6730            requested_at: Timestamp::now(),
6731            reason: reason.to_owned(),
6732            findings,
6733            head_at_request: head_at_request.clone(),
6734            allow_stale,
6735            stale,
6736            fix: None,
6737            result_head: None,
6738            follow_up_review_run: None,
6739        };
6740        self.state.event(
6741            "fix",
6742            format!(
6743                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6744                request.findings.len(),
6745                request
6746                    .findings
6747                    .iter()
6748                    .map(|f| f.id.as_str())
6749                    .collect::<Vec<_>>()
6750                    .join(", "),
6751            ),
6752        );
6753        // Recorded now, before any worktree work or the fixer call itself —
6754        // and re-saved at each checkpoint below: a crash at any point after
6755        // this (mid fixer call, mid follow-up review) must not lose the fact
6756        // that this was requested, for which findings, and why. Everything
6757        // past this point reads and writes through `request_index` rather
6758        // than a local variable, since `request` itself is moved here.
6759        self.state.operator_fixes.push(request);
6760        self.state.save()?;
6761        let request_index = self.state.operator_fixes.len() - 1;
6762
6763        // A fresh, dedicated worktree for this one call, never the winner's
6764        // own worktree in place: that one may already be gone (folded away),
6765        // and reusing it in place would leave the branch checked out there
6766        // when the follow-up review below tries to check it out again. Freed
6767        // immediately after, either way — but only once confirmed clean:
6768        // `worktree_remove` is a `git worktree remove --force`, which would
6769        // otherwise discard uncommitted work left there by the operator or
6770        // another process before this had a chance to even look at it.
6771        let repo = self.state.repo.clone();
6772        let coordination = self.coordinate(&repo).await?;
6773        if winner.worktree.exists() {
6774            // Lockfiles a rescue commit withheld stay untracked on purpose and
6775            // are already recorded; they are not the operator's work to protect.
6776            let dirty = git::git(
6777                &winner.worktree,
6778                &["status", "--porcelain", "--untracked-files=all"],
6779            )
6780            .await?;
6781            let only_withheld = dirty.lines().all(|l| {
6782                l.strip_prefix("?? ")
6783                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6784            });
6785            if !only_withheld {
6786                bail!(
6787                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6788                     discard them first",
6789                    winner.worktree.display()
6790                );
6791            }
6792            git::worktree_remove(&self.state.repo, &winner.worktree)
6793                .await
6794                .ok();
6795        }
6796        let fix_worktree = self.state.worktree_root().join("operator-fix");
6797        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6798        git::git(
6799            &self.state.repo,
6800            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6801        )
6802        .await
6803        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6804        if !git::is_clean(&fix_worktree).await? {
6805            git::worktree_remove(&self.state.repo, &fix_worktree)
6806                .await
6807                .ok();
6808            bail!(
6809                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6810                winner.branch
6811            );
6812        }
6813        let repo_for_setup = self.state.repo.clone();
6814        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6815            Ok(()) => {
6816                worktree_setup::prepare_with(
6817                    &self.state.config,
6818                    &repo_for_setup,
6819                    &fix_worktree,
6820                    crate::build_target::Coordination::Held(coordination.as_ref()),
6821                )
6822                .await
6823            }
6824            Err(e) => Err(e),
6825        };
6826        if let Err(e) = setup {
6827            git::worktree_remove(&self.state.repo, &fix_worktree)
6828                .await
6829                .ok();
6830            return Err(e);
6831        }
6832
6833        // This explicit operator request retries availability independently
6834        // of execute(); the previous call has already saved and cleaned up.
6835        self.state.resource_block = None;
6836
6837        let run_id = self.state.id.clone();
6838        let prompts = self.state.config.prompts.clone();
6839        let language = self.state.config.graph.language.clone();
6840        let sessions = self.state.config.graph.sessions;
6841        let artifacts = agent::artifacts_dir(&self.state.dir());
6842        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6843            .findings
6844            .iter()
6845            .map(|f| Finding {
6846                id: f.id.clone(),
6847                severity: f.severity,
6848                file: f.file.clone(),
6849                line: f.line,
6850                title: f.title.clone(),
6851                detail: f.detail.clone(),
6852            })
6853            .collect();
6854        let fix_prompt = prompt::operator_fix_in(
6855            &self.state.instruction,
6856            &finding_list,
6857            reason,
6858            &stale_details,
6859            &head_at_request,
6860            &language,
6861            &self.state.config.graph.github_language,
6862        );
6863        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6864        drop(coordination);
6865        let (job, seat, out) = self
6866            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6867                prompt: fix_prompt.clone(),
6868                spec,
6869                seat,
6870                cwd: fix_worktree.clone(),
6871                timeout,
6872                allow_write: true,
6873                sessions,
6874                artifacts: artifacts.clone(),
6875                stem: "operator-fix".to_owned(),
6876                handover: None,
6877            })
6878            .await;
6879        let agent_id = seat.agent.clone();
6880
6881        let mut fix = FixRecord {
6882            agent: agent_id,
6883            addressed: Vec::new(),
6884            rejected: Vec::new(),
6885            notes: String::new(),
6886            committed: false,
6887            failed: None,
6888            duration_ms: 0,
6889            continuation: None,
6890        };
6891        let mut final_seat = seat.clone();
6892        match out {
6893            AgentOutcome::Ok(o) => {
6894                fix.duration_ms = o.duration_ms;
6895                let parsed = verdict::extract_json::<FixReport>(&o.text);
6896                let incomplete_reason = match &parsed {
6897                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6898                        "the reply parsed, but it reported a command whose own CLI \
6899                         never confirmed an exit status"
6900                            .to_owned(),
6901                    ),
6902                    Ok(_) => None,
6903                    Err(e) => Some(e.to_string()),
6904                };
6905                match incomplete_reason {
6906                    None => {
6907                        let report = parsed.expect("checked Ok above");
6908                        fix.addressed = report.addressed;
6909                        fix.rejected = report.rejected;
6910                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6911                    }
6912                    Some(reason) => {
6913                        let (resumed_seat, resolved, failure, cont) = self
6914                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6915                            .await;
6916                        fix.duration_ms += cont.cumulative_wait_ms;
6917                        fix.continuation = Some(cont);
6918                        final_seat = resumed_seat;
6919                        match resolved {
6920                            Some(report) => {
6921                                fix.addressed = report.addressed;
6922                                fix.rejected = report.rejected;
6923                                fix.notes =
6924                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6925                            }
6926                            None => fix.failed = failure,
6927                        }
6928                    }
6929                }
6930            }
6931            AgentOutcome::Dropped(o) => {
6932                fix.duration_ms = o.duration_ms;
6933                let why = o
6934                    .dropped
6935                    .as_ref()
6936                    .map(|d| d.why.as_str())
6937                    .unwrap_or("the CLI ended the stream without delivering its answer");
6938                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6939            }
6940            AgentOutcome::Quota(o) => {
6941                self.state.quota.push(QuotaLoss::from_report(
6942                    final_seat.key.clone(),
6943                    "fix",
6944                    o.quota.as_ref(),
6945                ));
6946                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6947            }
6948            AgentOutcome::Failed(e) => fix.failed = Some(e),
6949            AgentOutcome::ResourceBlocked(e) => {
6950                fix.failed = Some(format!("the fixer was not started: {e}"));
6951            }
6952        }
6953        // Even a deferred call must rescue edits, release the worktree and
6954        // finalize its record below so an explicit `magi fix` can retry.
6955        if fix.continuation.is_none() {
6956            fix.continuation = Some(ContinuationRecord::not_needed());
6957        }
6958        self.state.seats.insert(final_seat.key.clone(), final_seat);
6959
6960        let rescue_message = format!(
6961            "magi: operator-selected fix ({}) (uncommitted work)",
6962            self.state.operator_fixes[request_index]
6963                .findings
6964                .iter()
6965                .map(|f| f.id.as_str())
6966                .collect::<Vec<_>>()
6967                .join(", ")
6968        );
6969        let repo = self.state.repo.clone();
6970        let coordination = self.coordinate(&repo).await?;
6971        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6972            self.state.note_withheld("fix", &r.withheld);
6973        }
6974        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6975        fix.committed = after != head_at_request;
6976        git::worktree_remove(&self.state.repo, &fix_worktree)
6977            .await
6978            .ok();
6979        drop(coordination);
6980
6981        self.state.event(
6982            "fix",
6983            match &fix.failed {
6984                Some(reason) => format!(
6985                    "operator fix: adoption report was lost ({reason}); {}",
6986                    if fix.committed {
6987                        "committed"
6988                    } else {
6989                        "NO new commit"
6990                    }
6991                ),
6992                None => format!(
6993                    "operator fix: {} addressed, {} rejected, {}",
6994                    fix.addressed.len(),
6995                    fix.rejected.len(),
6996                    if fix.committed {
6997                        "committed"
6998                    } else {
6999                        "NO new commit"
7000                    }
7001                ),
7002            },
7003        );
7004
7005        // Every selected finding gets an outcome — never left `Pending` once
7006        // the fixer's own turn is over. A report that never came back at all
7007        // marks every one of them `Unreported`, not silently "not addressed":
7008        // quota, a dropped stream, or an exhausted continuation are gaps in
7009        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7010        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7011        for f in &mut self.state.operator_fixes[request_index].findings {
7012            f.outcome = if fix.failed.is_some() {
7013                OperatorFixOutcome::Unreported
7014            } else if fix.addressed.contains(&f.id) {
7015                OperatorFixOutcome::Addressed
7016            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7017                OperatorFixOutcome::Rejected { why: r.why.clone() }
7018            } else {
7019                OperatorFixOutcome::Unreported
7020            };
7021        }
7022
7023        let committed = fix.committed;
7024        if committed {
7025            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7026        }
7027        self.state.operator_fixes[request_index].fix = Some(fix);
7028        // Saved again now that the fixer's own outcome is final, on top of
7029        // the save right after the request was first pushed above.
7030        self.state.save()?;
7031        if self.state.resource_block.is_some() {
7032            return self.stop_for_resource();
7033        }
7034
7035        if committed {
7036            self.state.event(
7037                "fix",
7038                format!(
7039                    "operator fix committed {}; opening a follow-up review-only run",
7040                    short(&after)
7041                ),
7042            );
7043            self.state.save()?;
7044            drop(execution);
7045            // The new review owns its own execution. Update only its audit link
7046            // afterwards, since publication may have changed the old record.
7047            let event_count = self.state.events.len();
7048            let save_follow_up = |state: &mut RunState| -> Result<()> {
7049                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7050                let _execution = crate::driver::maintenance(&home, &state.id)?;
7051                let mut disk = RunState::load(&state.id)?;
7052                disk.events.extend(state.events.drain(event_count..));
7053                let follow_up = state.operator_fixes[request_index]
7054                    .follow_up_review_run
7055                    .clone();
7056                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7057                disk.save()?;
7058                *state = disk;
7059                Ok(())
7060            };
7061            // The operator asked for the fix, and the follow-up serves whatever
7062            // task the run it follows served.
7063            let origin =
7064                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7065            match Self::review(
7066                &self.state.repo,
7067                &winner.branch,
7068                self.state.config.clone(),
7069                origin,
7070            )
7071            .await
7072            {
7073                Ok(mut follow_up) => {
7074                    follow_up.state.event(
7075                        "start",
7076                        format!(
7077                            "requested by an operator fix on run {} for finding(s) {}",
7078                            self.state.id,
7079                            self.state.operator_fixes[request_index]
7080                                .findings
7081                                .iter()
7082                                .map(|f| f.id.as_str())
7083                                .collect::<Vec<_>>()
7084                                .join(", "),
7085                        ),
7086                    );
7087                    follow_up.state.save()?;
7088                    let follow_up_id = follow_up.state.id.clone();
7089                    // The follow-up is a run like any other: it belongs to the
7090                    // task of the run it follows, or to one filed for it.
7091                    let adopted = match crate::direct::adopt(
7092                        &follow_up.state,
7093                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7094                    ) {
7095                        Ok(a) => a,
7096                        Err(e) => {
7097                            // An ownerless run must not spend agent calls; it
7098                            // stays saved, and `magi run --resume` adopts it.
7099                            self.state.event(
7100                                "fix",
7101                                format!(
7102                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7103                                ),
7104                            );
7105                            save_follow_up(&mut self.state)?;
7106                            return Ok(());
7107                        }
7108                    };
7109                    let executed = follow_up.execute().await;
7110                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7111                    if let Some(a) = adopted {
7112                        a.finish(&follow_up.state, executed);
7113                    }
7114                    if let Some(e) = failure {
7115                        self.state.event(
7116                            "fix",
7117                            format!(
7118                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7119                            ),
7120                        );
7121                    }
7122                    self.state.operator_fixes[request_index].follow_up_review_run =
7123                        Some(follow_up_id);
7124                }
7125                Err(e) => {
7126                    self.state.event(
7127                        "fix",
7128                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7129                    );
7130                }
7131            }
7132            save_follow_up(&mut self.state)?;
7133        }
7134
7135        Ok(())
7136    }
7137
7138    // --------------------------------------------------------------- review
7139
7140    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7141    /// names, in order, each at most once, moving on only when the call
7142    /// advances (an error, a quota hit or nothing usable - the same decision
7143    /// point `agent::chain_advances` is for the other chained roles).
7144    ///
7145    /// Each agent gets its own seat from `Runner::seat`: the same agent
7146    /// continues its conversation (the winner's own implementer seat when it
7147    /// is the winner's author, now that the competition is over), another
7148    /// takes a fresh one so the full prompt is sent again. A handover is
7149    /// recorded under `node`, which is what makes the fallback stick for the
7150    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7151    /// is returned, so an exhausted chain reads exactly like a single failed
7152    /// fixer: one quota loss, the same wording, the same refund. An earlier
7153    /// attempt's edits are left in the tree and judged, with the final
7154    /// attempt's, by what git says afterwards.
7155    ///
7156    /// Returns the job that produced the outcome, for `continue_fix_report`.
7157    async fn ask_fixer(
7158        &mut self,
7159        winner: &Candidate,
7160        node: &'static str,
7161        round: Option<usize>,
7162        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7163    ) -> (SeatJob, SeatState, AgentOutcome) {
7164        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7165        self.ask_fixer_among(attempts, node, round, None, build)
7166            .await
7167    }
7168
7169    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7170    /// worktree and a commit: before the next agent is asked after one that
7171    /// did not satisfy the call, the worktree is put back on that commit, so
7172    /// a failed agent's partial edits are not carried into the next one.
7173    async fn ask_fixer_among(
7174        &mut self,
7175        attempts: Vec<(AgentSpec, String)>,
7176        node: &'static str,
7177        round: Option<usize>,
7178        restore: Option<(&Path, &str)>,
7179        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7180    ) -> (SeatJob, SeatState, AgentOutcome) {
7181        let run_id = self.state.id.clone();
7182        let prompts = self.state.config.prompts.clone();
7183        let cache = self.state.config.cache_dir();
7184        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7185        let mut last = None;
7186        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7187            let seat = self.seat(&key, &spec.id);
7188            let mut job = build(spec.clone(), seat);
7189            if i > 0 {
7190                job.stem = format!("{}-{}", job.stem, spec.id);
7191            }
7192            let ctx = WaveCtx {
7193                carry_seats: false,
7194                pauses: Some((&self.pause, &self.interrupt)),
7195                run: &run_id,
7196                node,
7197                prompts: &prompts,
7198                cache: cache.as_deref(),
7199                round,
7200            };
7201            let (seat, out) =
7202                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7203            // A resource block never advances the chain: the chosen agent
7204            // was not asked, so it must be the one asked again on resume.
7205            let advances = match &out {
7206                AgentOutcome::Ok(o) => agent::output_advances(o),
7207                AgentOutcome::ResourceBlocked(_) => false,
7208                _ => true,
7209            };
7210            if let Some(next) = ids.get(i + 1)
7211                && advances
7212            {
7213                self.state.seats.insert(seat.key.clone(), seat.clone());
7214                let class =
7215                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7216                let reason = match &out {
7217                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7218                    other => fail_reason(other),
7219                };
7220                // A failed agent's edits must not reach the next one, and a
7221                // restore that did not work ends the chain: the call fails
7222                // and the caller's own (confirmed) restore decides.
7223                if let Some((wt, rev)) = restore
7224                    && let Err(e) = self.graft_restore(wt, rev).await
7225                {
7226                    let why =
7227                        format!("could not restore the worktree before the next fixer: {e:#}");
7228                    tracing::warn!("{why}");
7229                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7230                        AgentOutcome::ResourceBlocked(why)
7231                    } else {
7232                        AgentOutcome::Failed(why)
7233                    };
7234                    last = Some((job, seat, out));
7235                    break;
7236                }
7237                record_handover(
7238                    &mut self.state,
7239                    node,
7240                    &seat.key,
7241                    &spec.id,
7242                    next,
7243                    &class,
7244                    &reason,
7245                );
7246                continue;
7247            }
7248            last = Some((job, seat, out));
7249            break;
7250        }
7251        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7252        if let AgentOutcome::Quota(output) = &out
7253            && node != "graft"
7254        {
7255            // Graft is best effort: its caller records the loss and restores
7256            // the pre-graft tree, then proceeds to review and gate.
7257            // Every fallback was tried. Machine outages cannot be repaired by
7258            // spending a fix round; use each caller's resumable resource path.
7259            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7260            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7261            self.state.quota.push(loss);
7262            self.state.seats.insert(seat.key.clone(), seat.clone());
7263            self.state.status = RunStatus::Blocked;
7264            return (
7265                job,
7266                seat,
7267                AgentOutcome::ResourceBlocked(
7268                    "fixer unavailable; restore agent availability and resume".into(),
7269                ),
7270            );
7271        }
7272        (job, seat, out)
7273    }
7274
7275    /// The one repair a verification-only failure earns (see
7276    /// [`crate::recovery`]), before the first review round of a run that took
7277    /// a branch over.
7278    ///
7279    /// Saved as started *before* the fixer is called, so a resume never
7280    /// repairs twice; a start found on re-entry is rolled back to the commit
7281    /// it began from. A failed or unusable fixer leaves the tree as it was and
7282    /// the review goes on over it, so the first round's own verification
7283    /// reports the failure again. The failure is never carried into a round as
7284    /// a result: verification is re-run on whatever commit this leaves.
7285    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7286        use crate::recovery::{Mode, Repair};
7287        if !self.state.reviews.is_empty() {
7288            return Ok(());
7289        }
7290        let Some(mut rec) = self.state.recovery.clone() else {
7291            return Ok(());
7292        };
7293        if rec.mode != Mode::VerifyRepair {
7294            return Ok(());
7295        }
7296        let wt = winner.worktree.clone();
7297        let mut head = git::rev_parse(&wt, "HEAD").await?;
7298        match rec.repair.clone() {
7299            Repair::Done { .. } => return Ok(()),
7300            Repair::WaitingForRestore { before } => {
7301                self.graft_restore(&wt, &before).await?;
7302                head = before;
7303                rec.repair = Repair::NotStarted;
7304                self.state.recovery = Some(rec.clone());
7305                self.state.save()?;
7306            }
7307            Repair::Started { before } => {
7308                // Interrupted: the unfinished edits are not trusted.
7309                // An unconfirmed rollback blocks the run with `Started` kept,
7310                // so a resume retries it; the tree is never reviewed as is.
7311                if let Err(e) = self.graft_restore(&wt, &before).await {
7312                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7313                        return Err(e);
7314                    }
7315                    return self
7316                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7317                        .await;
7318                }
7319                rec.repair = Repair::Done {
7320                    before: before.clone(),
7321                    after: before,
7322                    committed: false,
7323                    failed: Some("interrupted; rolled back".to_owned()),
7324                };
7325                self.state
7326                    .event("recovery", "the repair was interrupted and rolled back");
7327                self.state.recovery = Some(rec);
7328                self.state.save()?;
7329                return Ok(());
7330            }
7331            Repair::NotStarted => {}
7332        }
7333        if crate::recovery::recheck(&mut rec, &head) {
7334            self.state.event("recovery", rec.summary());
7335            self.state.recovery = Some(rec);
7336            self.state.save()?;
7337            return Ok(());
7338        }
7339        rec.repair = Repair::Started {
7340            before: head.clone(),
7341        };
7342        self.state.recovery = Some(rec.clone());
7343        self.state.save()?;
7344
7345        let language = self.state.config.graph.language.clone();
7346        let sessions = self.state.config.graph.sessions;
7347        let artifacts = agent::artifacts_dir(&self.state.dir());
7348        let fix_prompt = prompt::recovery_fix(
7349            &self.state.instruction,
7350            &rec,
7351            self.state.config.graph.review_rounds,
7352            &language,
7353        );
7354        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7355        self.state.event(
7356            "recovery",
7357            format!(
7358                "repair: the fixer starts from the failed verification on {}",
7359                short(&head)
7360            ),
7361        );
7362        let (_job, seat, out) = self
7363            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7364                prompt: fix_prompt.clone(),
7365                spec,
7366                seat,
7367                cwd: wt.clone(),
7368                timeout,
7369                allow_write: true,
7370                sessions,
7371                artifacts: artifacts.clone(),
7372                stem: "fix-recovery".to_owned(),
7373                handover: None,
7374            })
7375            .await;
7376        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7377            rec.repair = Repair::WaitingForRestore { before: head };
7378            self.state.recovery = Some(rec);
7379            return self.stop_for_resource();
7380        }
7381        let failed = match &out {
7382            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7383            AgentOutcome::Quota(o) => {
7384                self.state.quota.push(QuotaLoss::from_report(
7385                    seat.key.clone(),
7386                    "fix",
7387                    o.quota.as_ref(),
7388                ));
7389                Some("rate limited (quota); the fixer could not run".to_owned())
7390            }
7391            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7392            AgentOutcome::Failed(e) => Some(e.clone()),
7393        };
7394        self.state.seats.insert(seat.key.clone(), seat);
7395        let coordination = self.coordinate(&wt).await?;
7396        let failed = match failed {
7397            // The agent's partial edits are not kept.
7398            Some(why) => {
7399                if let Err(e) = git::restore_to(&wt, &head).await {
7400                    return self
7401                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7402                        .await;
7403                }
7404                Some(why)
7405            }
7406            None => {
7407                if let Ok(r) = git::rescue_commit(
7408                    &wt,
7409                    "magi: recovery repair of the failed verification (uncommitted work)",
7410                )
7411                .await
7412                {
7413                    self.state.note_withheld("fix", &r.withheld);
7414                }
7415                None
7416            }
7417        };
7418        let after = git::rev_parse(&wt, "HEAD").await?;
7419        drop(coordination);
7420        self.state.event(
7421            "recovery",
7422            match &failed {
7423                Some(why) => format!("repair: nothing kept ({why})"),
7424                None if after != head => {
7425                    format!("repair: committed {}", short(&after))
7426                }
7427                None => "repair: the fixer made no commit".to_owned(),
7428            },
7429        );
7430        rec.repair = Repair::Done {
7431            before: head.clone(),
7432            committed: after != head,
7433            after,
7434            failed,
7435        };
7436        self.state.recovery = Some(rec);
7437        self.state.save()?;
7438        Ok(())
7439    }
7440
7441    /// A repair whose rollback could not be confirmed: the run is blocked and
7442    /// resumable, and the unconfirmed state is never reviewed.
7443    async fn stop_recovery(
7444        &mut self,
7445        mut rec: crate::recovery::RecoveryRecord,
7446        head: &str,
7447        why: String,
7448    ) -> Result<()> {
7449        // `Started` stays recorded: a resume retries the restore.
7450        rec.repair = crate::recovery::Repair::Started {
7451            before: head.to_owned(),
7452        };
7453        self.state.recovery = Some(rec);
7454        self.state
7455            .event("recovery", format!("repair could not be undone: {why}"));
7456        self.state.status = RunStatus::Blocked;
7457        self.state.save()?;
7458        bail!("recovery repair could not be rolled back: {why}")
7459    }
7460
7461    async fn review_loop(&mut self) -> Result<()> {
7462        if self.hold_base_sync().await? {
7463            return Ok(());
7464        }
7465        loop {
7466            if self
7467                .state
7468                .base_sync
7469                .as_ref()
7470                .is_some_and(|s| s.conflict.is_some())
7471            {
7472                return Ok(());
7473            }
7474            if self.catchup_repairable() {
7475                let record = self.state.reviews.last().expect("repairable round").clone();
7476                let winner = self
7477                    .state
7478                    .winner()
7479                    .cloned()
7480                    .context("catch-up repair has no winner")?;
7481                if !self.fix_review_round(&winner, record).await? {
7482                    return Ok(());
7483                }
7484            }
7485            self.review_loop_pass().await?;
7486            if !self.catchup_repairable() {
7487                return Ok(());
7488            }
7489        }
7490    }
7491
7492    /// Derive an owed catch-up repair from durable round evidence, including
7493    /// reentry after a crash before the fixer was dispatched.
7494    fn catchup_repairable(&self) -> bool {
7495        self.state.reviews.len() < self.state.config.graph.review_rounds
7496            && self.state.reviews.last().is_some_and(|r| {
7497                !r.clean
7498                    && r.blocking == 0
7499                    && r.fix.is_none()
7500                    && r.e2e_status() == E2eStatus::Failed
7501            })
7502    }
7503
7504    async fn review_loop_pass(&mut self) -> Result<()> {
7505        // A base that would not rebase is a person's decision, not a review
7506        // round: nothing here would change the answer, and reviewers and a
7507        // fixer would be spending real budget on a tree that cannot land
7508        // regardless of what they find.
7509        if self
7510            .state
7511            .base_sync
7512            .as_ref()
7513            .is_some_and(|s| s.conflict.is_some())
7514        {
7515            return Ok(());
7516        }
7517        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7518        // agent files with `magi task add` name the run that paid for it. The
7519        // prompt overlay is cloned alongside it because the waves borrow it
7520        // while `self` is mutably borrowed by the node's own bookkeeping.
7521        let run_id = self.state.id.clone();
7522        let prompts = self.state.config.prompts.clone();
7523        let Some(winner) = self.state.winner().cloned() else {
7524            return Ok(());
7525        };
7526        let granted_review = self
7527            .state
7528            .repair_grants
7529            .last()
7530            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7531            .cloned();
7532        let fresh_review = granted_review
7533            .as_ref()
7534            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7535        let max_rounds = granted_review
7536            .as_ref()
7537            .map_or(self.state.config.graph.review_rounds, |g| {
7538                g.review_start.saturating_add(1)
7539            });
7540        // A clean round, an exhausted round budget, or a stalled tree (see
7541        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7542        // they are recorded — recomputed here, not read off `status`, so a
7543        // reentry into a run that already stopped restates the identical
7544        // verdict instead of silently handing back whatever an earlier node
7545        // in this same walk clobbered `status` to (a solo-candidate
7546        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7547        // below runs an empty range once the budget is spent, and would
7548        // otherwise fall through without touching `status` at all.
7549        if let Some(status) =
7550            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7551        {
7552            // A reentry after a crash between the last round's save and
7553            // `stop_reviewing` reaches the hand-off here, not there.
7554            if status == RunStatus::Gating {
7555                self.record_contested_handoff();
7556            }
7557            self.state.status = status;
7558            self.state.save()?;
7559            return Ok(());
7560        }
7561        self.state.status = RunStatus::Reviewing;
7562        // A last recorded round whose own verification never resolved
7563        // (`ResourceBlocked` — the shared build cache, not the patch) is
7564        // never a concluded round, whatever the round budget says: starting
7565        // a fresh round on top of it would spend a whole new reviewer wave
7566        // re-reading an unchanged patch instead of just retrying the one
7567        // check that actually needs it, and once the budget is spent the
7568        // loop below has nothing left to do at all (its range is empty).
7569        // Retry that check directly instead, exactly the same retry
7570        // `stop_reviewing` already does for its own catch-up case.
7571        if !fresh_review
7572            && self.state.reviews.last().is_some_and(|r| {
7573                r.e2e_status() == E2eStatus::ResourceBlocked
7574                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7575            })
7576        {
7577            let shell = self.state.config.shell();
7578            return self
7579                .stop_unresolved_review(
7580                    "the last round's own verification never resolved",
7581                    &shell,
7582                    &winner.worktree,
7583                )
7584                .await;
7585        }
7586
7587        if granted_review.is_none() {
7588            self.recovery_repair(&winner).await?;
7589        }
7590        if self.resource_halt()? {
7591            return Ok(());
7592        }
7593
7594        let repo = self.state.repo.clone();
7595        let root = self.state.worktree_root();
7596        let language = self.state.config.graph.language.clone();
7597        let sessions = self.state.config.graph.sessions;
7598        let artifacts = self.merge_repair_artifacts();
7599        let base = self.landing_base();
7600        let base_short = short(&base);
7601        let reviewers = self.roles.reviewers.clone();
7602        let shell = self.state.config.shell();
7603
7604        for round in (self.state.reviews.len() + 1)..=max_rounds {
7605            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7606            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7607            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7608            // The prior round's own record, already persisted — never a
7609            // hand-carried variable of just its failing output: that is
7610            // exactly what let a round's e2e result drift out of sync with
7611            // which commit it was actually about (see `SCHEMA`'s doc for
7612            // schema 8). Judged against `head`, the commit reviewers are
7613            // about to look at now, so the summary always reads as "an
7614            // earlier head" here — this round's own patch has not been
7615            // checked yet.
7616            let prev_verification = self
7617                .state
7618                .reviews
7619                .last()
7620                .and_then(|r| r.verification_summary(&head));
7621            // Only the first round of a run that took a branch over: later
7622            // rounds have this run's own history.
7623            let prior_section = match (&self.state.recovery, round) {
7624                (Some(rec), 1) if self.state.reviews.is_empty() => {
7625                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7626                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7627                            Some(crate::recovery::head_of(
7628                                &git::diff(&winner.worktree, reviewed, "HEAD")
7629                                    .await
7630                                    .unwrap_or_default(),
7631                                crate::recovery::SINCE_DIFF_MAX,
7632                            ))
7633                        }
7634                        _ => None,
7635                    };
7636                    Some(prompt::recovery_review(rec, since.as_deref()))
7637                }
7638                _ => None,
7639            };
7640
7641            // Each reviewer gets its own detached checkout of exactly this
7642            // commit: nobody can perturb the winner's tree, and the fixer can
7643            // keep working without racing a reviewer.
7644            let mut jobs = Vec::new();
7645            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7646                self.coordinate(&repo).await?
7647            } else {
7648                None
7649            };
7650            for (r, spec) in reviewers.iter().cloned().enumerate() {
7651                let wt = root.join(format!("review-{}", r + 1));
7652                // `clean -fdx` in a reset wipes setup's products, so every
7653                // round sets the seat up again.
7654                if wt.exists() {
7655                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7656                } else {
7657                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7658                        None
7659                    } else {
7660                        self.coordinate(&repo).await?
7661                    };
7662                    git::worktree_add_detached(&repo, &wt, &head).await?;
7663                }
7664                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7665                    None
7666                } else {
7667                    self.coordinate(&repo).await?
7668                };
7669                self.setup_seat_worktree(
7670                    &repo,
7671                    &wt,
7672                    false,
7673                    coordination.as_ref().or(_setup_lease.as_ref()),
7674                )
7675                .await?;
7676                let seat_key = format!("review-{}", r + 1);
7677                // The seat starts the round on whoever answered it last, not
7678                // on the agent the spec names, so a failure is not re-paid.
7679                let spec = pick_start_spec(
7680                    &self.roles.reviewer_roster,
7681                    spec,
7682                    self.state.seat_history.get(&seat_key),
7683                );
7684                let seat = self.seat(&seat_key, &spec.id);
7685                jobs.push(SeatJob {
7686                    prompt: prompt::review(&prompt::ReviewCtx {
7687                        instruction: &self.state.instruction,
7688                        branch: &winner.branch,
7689                        base_short: &base_short,
7690                        stat: &stat,
7691                        patch: &patch,
7692                        verification: prev_verification.as_ref(),
7693                        prior: prior_section.as_deref(),
7694                        reviewers: reviewers.len(),
7695                        round,
7696                        rounds: max_rounds,
7697                        // A review-only run has no rankings, so nothing
7698                        // competed for this patch and the reviewer is told so.
7699                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7700                        lens: Lens::for_seat(r),
7701                        language: &language,
7702                        github_language: &self.state.config.graph.github_language,
7703                    }),
7704                    spec,
7705                    seat,
7706                    cwd: wt,
7707                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7708                    allow_write: false,
7709                    sessions,
7710                    artifacts: artifacts.clone(),
7711                    stem: format!("review-{round}-{}", r + 1),
7712                    handover: None,
7713                });
7714            }
7715
7716            drop(coordination);
7717            self.state.event(
7718                "review",
7719                format!(
7720                    "round {round}: {} reviewers on {}",
7721                    jobs.len(),
7722                    short(&head)
7723                ),
7724            );
7725            let mut quota_losses = Vec::new();
7726            let review_retries = self.state.config.graph.retries;
7727            let review_cache = self.state.config.cache_dir();
7728            let ctx = WaveCtx {
7729                carry_seats: true,
7730                pauses: Some((&self.pause, &self.interrupt)),
7731                run: &run_id,
7732                node: "review",
7733                prompts: &prompts,
7734                cache: review_cache.as_deref(),
7735                round: Some(round),
7736            };
7737            let results = ask_json_wave::<Review>(
7738                jobs,
7739                Arc::clone(&self.sem),
7740                review_retries,
7741                &self.roles.reviewer_roster,
7742                &ctx,
7743                &mut quota_losses,
7744                &mut self.state,
7745                &|_: &Review| Ok(()),
7746            )
7747            .await;
7748            if self.state.resource_block.is_some() {
7749                return self.stop_for_resource();
7750            }
7751            // Counted before the move below: how many of *this* round's
7752            // reviewer seats were lost to their own rate limit, as opposed to
7753            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7754            let round_quota_missing = quota_losses.len();
7755            self.state.quota.extend(quota_losses);
7756
7757            let mut records = Vec::new();
7758            let mut all_findings = Vec::new();
7759            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7760                let agent_id = seat.agent.clone();
7761                self.state.seats.insert(seat.key.clone(), seat);
7762                let mut record = ReviewRecord {
7763                    reviewer: r + 1,
7764                    agent: agent_id,
7765                    summary: String::new(),
7766                    findings: Vec::new(),
7767                    vote: None,
7768                    failed: None,
7769                    duration_ms: 0,
7770                    // Set for both outcomes: `failed: Some(_)` with
7771                    // `attempts > 0` is a seat every retry still lost, not a
7772                    // recovered one — only `failed: None` with `attempts > 0`
7773                    // reads as "answered after a nudge" (see this field's own
7774                    // doc).
7775                    attempts,
7776                };
7777                match res {
7778                    Ok((review, out)) => {
7779                        // Sanitized here, at the point every other piece of
7780                        // agent prose in this file is (candidate summaries,
7781                        // deliberation turns, vote reasons): a reviewer's own
7782                        // words are the one thing about it that could name
7783                        // it, and reconsideration below broadcasts this same
7784                        // summary and these same findings to every other
7785                        // seat on the panel.
7786                        record.summary =
7787                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7788                        record.vote = Some(review.vote);
7789                        record.duration_ms = out.duration_ms;
7790                        for (n, mut f) in review.findings.into_iter().enumerate() {
7791                            // ids are magi's, never the agent's: the fixer's
7792                            // adoption report is keyed by them.
7793                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7794                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7795                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7796                            // `file` is agent-supplied prose too, never
7797                            // checked against the real tree — the same
7798                            // exposure `title`/`detail` above have, just in
7799                            // a field easy to forget because it looks like a
7800                            // path rather than free text.
7801                            f.file = f
7802                                .file
7803                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7804                            all_findings.push(f.clone());
7805                            record.findings.push(f);
7806                        }
7807                        self.state.event(
7808                            "review",
7809                            format!(
7810                                "round {round}: reviewer {} voted {} with {} finding(s)",
7811                                r + 1,
7812                                review.vote.label(),
7813                                record.findings.len()
7814                            ),
7815                        );
7816                    }
7817                    Err(e) => {
7818                        record.failed = Some(e.to_string());
7819                        self.state.event(
7820                            "review",
7821                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7822                        );
7823                    }
7824                }
7825                records.push(record);
7826            }
7827
7828            // Tally the round's votes and, if they split, spend the one
7829            // round of reconsideration the split -> deliberate -> revote
7830            // shape `judge`/`vote` use for the panel, sized down to what a
7831            // read-only review round can afford: one round, and a revote
7832            // rather than an argument, because the panel already wrote its
7833            // reasoning down as findings the first time around.
7834            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7835            let vote_split =
7836                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7837            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7838            if vote_split {
7839                self.state.event(
7840                    "review",
7841                    format!(
7842                        "round {round}: votes split ({}) — one round of reconsideration",
7843                        initial_votes
7844                            .iter()
7845                            .map(|v| v.label())
7846                            .collect::<Vec<_>>()
7847                            .join(", ")
7848                    ),
7849                );
7850                // Seats read every seat's findings and votes, still numbered
7851                // and never named — the same anonymity `review` itself keeps.
7852                let panel: Vec<ReviewSeatReport<'_>> = records
7853                    .iter()
7854                    .filter_map(|r| {
7855                        r.vote.map(|vote| ReviewSeatReport {
7856                            reviewer: r.reviewer,
7857                            vote,
7858                            summary: &r.summary,
7859                            findings: &r.findings,
7860                        })
7861                    })
7862                    .collect();
7863
7864                let mut jobs = Vec::new();
7865                let mut seats_at = Vec::new();
7866                for (r, spec) in reviewers.iter().cloned().enumerate() {
7867                    // A seat with no initial vote has nothing to reconsider
7868                    // from and stays absent, the same as it stayed absent
7869                    // from `panel` above.
7870                    if records[r].vote.is_none() {
7871                        continue;
7872                    }
7873                    let wt = root.join(format!("review-{}", r + 1));
7874                    let seat_key = format!("review-{}", r + 1);
7875                    let spec = self.occupant(&seat_key, spec);
7876                    let seat = self.seat(&seat_key, &spec.id);
7877                    // A seat with no live session has already forgotten the
7878                    // initial review's prompt — restate the patch it is
7879                    // voting on, the same as `deliberate`/`vote` do for a
7880                    // judge in the same position.
7881                    // The panel already carries this seat's own review and
7882                    // vote, so restating the patch makes the prompt whole for
7883                    // a seat handed to another agent.
7884                    let build = |with_patch: bool| {
7885                        prompt::review_reconsider(&ReviewReconsiderCtx {
7886                            instruction: &self.state.instruction,
7887                            reviewer: r + 1,
7888                            lens: Lens::for_seat(r),
7889                            panel: &panel,
7890                            patch: with_patch.then_some(ReviewPatch {
7891                                branch: &winner.branch,
7892                                base_short: &base_short,
7893                                stat: &stat,
7894                                patch: &patch,
7895                            }),
7896                            round,
7897                            rounds: max_rounds,
7898                            language: &language,
7899                        })
7900                    };
7901                    let full = build(true);
7902                    let prompt = if has_context(&spec, &seat, sessions) {
7903                        build(false)
7904                    } else {
7905                        full.clone()
7906                    };
7907                    jobs.push(SeatJob {
7908                        prompt,
7909                        spec,
7910                        seat,
7911                        cwd: wt,
7912                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7913                        allow_write: false,
7914                        sessions,
7915                        artifacts: artifacts.clone(),
7916                        stem: format!("review-{round}-reconsider-{}", r + 1),
7917                        handover: Some(full),
7918                    });
7919                    seats_at.push(r);
7920                }
7921
7922                let mut recon_quota_losses = Vec::new();
7923                let recon_cache = self.state.config.cache_dir();
7924                let recon_ctx = WaveCtx {
7925                    carry_seats: true,
7926                    pauses: Some((&self.pause, &self.interrupt)),
7927                    run: &run_id,
7928                    node: "review",
7929                    prompts: &prompts,
7930                    cache: recon_cache.as_deref(),
7931                    round: Some(round),
7932                };
7933                let recon_results = ask_json_wave::<ReviewRevote>(
7934                    jobs,
7935                    Arc::clone(&self.sem),
7936                    review_retries,
7937                    &self.roles.reviewer_roster,
7938                    &recon_ctx,
7939                    &mut recon_quota_losses,
7940                    &mut self.state,
7941                    &|_: &ReviewRevote| Ok(()),
7942                )
7943                .await;
7944                if self.state.resource_block.is_some() {
7945                    return self.stop_for_resource();
7946                }
7947                self.state.quota.extend(recon_quota_losses);
7948
7949                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7950                    let agent_id = seat.agent.clone();
7951                    self.state.seats.insert(seat.key.clone(), seat);
7952                    let mut rec = ReviewRevoteRecord {
7953                        reviewer: r + 1,
7954                        agent: agent_id,
7955                        vote: None,
7956                        reason: String::new(),
7957                        failed: None,
7958                    };
7959                    match res {
7960                        Ok((rv, _)) => {
7961                            rec.vote = Some(rv.vote);
7962                            rec.reason =
7963                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7964                            self.state.event(
7965                                "review",
7966                                format!(
7967                                    "round {round}: reviewer {} revoted {}",
7968                                    r + 1,
7969                                    rv.vote.label()
7970                                ),
7971                            );
7972                        }
7973                        Err(e) => {
7974                            rec.failed = Some(e.to_string());
7975                            self.state.event(
7976                                "review",
7977                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7978                            );
7979                        }
7980                    }
7981                    reconsideration.push(rec);
7982                }
7983            } else if initial_votes.len() > 1 {
7984                self.state.event(
7985                    "review",
7986                    format!(
7987                        "round {round}: votes agreed ({}) — no reconsideration",
7988                        initial_votes[0].label()
7989                    ),
7990                );
7991            }
7992
7993            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7994            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7995            // A round that already has a blocking finding and a round left to
7996            // try is going back to the fixer no matter what `verify.e2e`
7997            // says, so running it first only spends the loop's slowest step
7998            // (minutes, for a Rust repo's full test suite) on a head about
7999            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8000            // runs once a round has no blocking findings left (see
8001            // `round_is_clean`, which a deferred — empty — `e2e` can never
8002            // satisfy since `blocking` is nonzero whenever this branch is
8003            // taken), and `stop_reviewing` forces a real run before it will
8004            // ever read a deferred round as green.
8005            let defer_e2e =
8006                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8007            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8008                let reason =
8009                    format!("{blocking} blocking finding(s) already required a fix this round");
8010                self.state.event(
8011                    "verify",
8012                    format!(
8013                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8014                         {}); it will run once a round has none left",
8015                        short(&head)
8016                    ),
8017                );
8018                (Vec::new(), false, true, Some(reason))
8019            } else {
8020                let e2e_commands = self.state.config.verify.e2e.clone();
8021                let cache_dir = self.state.config.cache_dir();
8022                let context = format!("round {round}");
8023                let wait = self.repository_wait();
8024                let (e2e, verify_retried) = with_cache_lease(
8025                    &mut self.state,
8026                    cache_dir.as_deref(),
8027                    "e2e",
8028                    "e2e",
8029                    &winner.worktree,
8030                    &head,
8031                    verify_timeout,
8032                    &context,
8033                    &wait,
8034                    |state, budget| {
8035                        let shell = shell.clone();
8036                        let e2e_commands = e2e_commands.clone();
8037                        let worktree = winner.worktree.clone();
8038                        let context = context.clone();
8039                        let winner = winner.clone();
8040                        async move {
8041                            if !e2e_commands.is_empty() {
8042                                // The suite certifies one SHA. Format before it
8043                                // runs, or the commit `pre_gate` makes at the
8044                                // gate owes the whole suite again.
8045                                Self::run_pre_gate(state, &winner).await;
8046                            }
8047                            run_e2e_with_retry(
8048                                state,
8049                                &shell,
8050                                &e2e_commands,
8051                                &worktree,
8052                                budget,
8053                                &context,
8054                                Some(round),
8055                            )
8056                            .await
8057                        }
8058                    },
8059                )
8060                .await?;
8061                (e2e, verify_retried, false, None)
8062            };
8063
8064            let expected = records.len();
8065            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8066            let incomplete = answered < expected;
8067            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8068            let policy = self.state.config.graph.incomplete_review;
8069            let clean = round_is_clean(
8070                blocking,
8071                e2e_ok,
8072                answered,
8073                expected,
8074                round_quota_missing,
8075                policy,
8076            );
8077
8078            let mut round_record = ReviewRound {
8079                round,
8080                head: head.clone(),
8081                verified_head: None,
8082                verified_at: None,
8083                reviews: records,
8084                e2e,
8085                verify_retried,
8086                e2e_deferred,
8087                e2e_defer_reason,
8088                fix: None,
8089                blocking,
8090                answered,
8091                expected,
8092                clean,
8093                progressed: false,
8094                vote_split,
8095                reconsideration,
8096                verdict: None,
8097            };
8098            // The final vote per seat is its revote where reconsideration
8099            // ran and answered, its initial vote otherwise — the same
8100            // fallback `tally` uses for a judge whose private vote failed.
8101            round_record.verdict = ReviewVote::worst(
8102                round_record
8103                    .final_votes()
8104                    .into_iter()
8105                    .map(|(_, _, vote)| vote),
8106            );
8107            // Which commit and when magi actually attempted to check —
8108            // known the moment a command was dispatched against `head`,
8109            // whether or not it finished: a resource-blocked attempt still
8110            // targeted a specific commit at a specific time, and leaving
8111            // that unrecorded is exactly what made `verification_summary`
8112            // report a fresh attempt as "commit unknown ... recorded before
8113            // this was tracked", indistinguishable from a genuinely old,
8114            // untracked record. Only a deferred or unconfigured round never
8115            // ran at all and has nothing to record — see
8116            // `ReviewRound::verified_head`'s own doc.
8117            if !matches!(
8118                round_record.e2e_status(),
8119                E2eStatus::Deferred | E2eStatus::NotConfigured
8120            ) {
8121                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8122                // mechanical fixes before the commands ran.
8123                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8124                round_record.verified_at = Some(Timestamp::now());
8125            }
8126
8127            if incomplete {
8128                let missing: Vec<String> = round_record
8129                    .reviews
8130                    .iter()
8131                    .filter(|r| r.failed.is_some())
8132                    .map(|r| format!("review-{}", r.reviewer))
8133                    .collect();
8134                self.state.event(
8135                    "review",
8136                    format!(
8137                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8138                        missing.join(", ")
8139                    ),
8140                );
8141            }
8142
8143            if clean {
8144                self.state.event(
8145                    "review",
8146                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8147                        format!(
8148                            "round {round}: clean (warn policy, incomplete panel) — no \
8149                             blocking findings from the seats that answered, verification green"
8150                        )
8151                    } else if incomplete {
8152                        format!(
8153                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8154                             quorum) — no blocking findings from the seats that answered, \
8155                             verification green",
8156                            expected - answered
8157                        )
8158                    } else {
8159                        format!("round {round}: clean — no blocking findings, verification green")
8160                    },
8161                );
8162                self.state.reviews.push(round_record);
8163                self.state.status = RunStatus::Gating;
8164                self.state.save()?;
8165                return Ok(());
8166            }
8167
8168            // Nothing was raised and verification passed, but not every seat
8169            // answered and `round_is_clean` still refused to call it clean —
8170            // either a seat is missing for a reason other than its own quota
8171            // (a crash, a timeout, unparsable output — worth another try), or
8172            // every seat that could have answered lost its quota and nobody
8173            // is left to decide on: re-review rather than send the fixer
8174            // after a round with nothing to fix.
8175            if incomplete && blocking == 0 && e2e_ok {
8176                self.state.reviews.push(round_record);
8177                self.state.save()?;
8178                if round == max_rounds {
8179                    self.state.status = RunStatus::Blocked;
8180                    self.state.event(
8181                        "review",
8182                        format!(
8183                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8184                             refusing to call it clean",
8185                            expected - answered
8186                        ),
8187                    );
8188                    return Ok(());
8189                }
8190                continue;
8191            }
8192
8193            // Nothing for the fixer to act on (`blocking == 0`) and the only
8194            // reason this round is not clean is that magi itself never got
8195            // a command to run — the shared build cache, not the patch (see
8196            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8197            // the fixer would invite a change to appease contention that has
8198            // nothing to do with the diff, and would leave this attempt
8199            // sitting in the next round's prompt as if it were about an
8200            // earlier, superseded commit rather than what it actually is:
8201            // the same head, still waiting to be checked. Wait for it the
8202            // same way the final round's own contention is already handled,
8203            // whatever round this happens to be.
8204            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8205                self.state.reviews.push(round_record);
8206                return self
8207                    .stop_unresolved_review(
8208                        "the round's own verification could not run",
8209                        &shell,
8210                        &winner.worktree,
8211                    )
8212                    .await;
8213            }
8214
8215            if round == max_rounds {
8216                self.state.reviews.push(round_record);
8217                return self
8218                    .stop_reviewing(
8219                        &format!(
8220                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8221                        ),
8222                        &shell,
8223                        &winner.worktree,
8224                    )
8225                    .await;
8226            }
8227
8228            if !self.fix_review_round(&winner, round_record).await? {
8229                return Ok(());
8230            }
8231        }
8232        Ok(())
8233    }
8234
8235    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8236    /// False means admission or continuation policy stopped the review loop.
8237    async fn fix_review_round(
8238        &mut self,
8239        winner: &Candidate,
8240        mut round_record: ReviewRound,
8241    ) -> Result<bool> {
8242        let round = round_record.round;
8243        let shell = self.state.config.shell();
8244        let step = self.run_fix_round(winner, &mut round_record).await?;
8245        if matches!(step, FixStep::Resource) {
8246            self.stop_for_resource()?;
8247            return Ok(false);
8248        }
8249        if self.state.reviews.len() < round {
8250            self.state.reviews.push(round_record);
8251        } else {
8252            self.state.reviews[round - 1] = round_record;
8253        }
8254        self.state.save()?;
8255
8256        // The fixer's own report never came back this round, even after
8257        // `continue_fix_report`'s own budget was spent on it — not an
8258        // ordinary "no report" (dropped stream, quota, plain failure),
8259        // which already reads that way and is left to the existing round
8260        // budget. Stopping here, rather than opening another round, is
8261        // what keeps a next reviewer/fixer wave from ever being
8262        // dispatched onto `winner.worktree` while whatever the seat's
8263        // last call may still have running there is unaccounted for: no
8264        // process liveness check exists (and none is being added — see
8265        // AGENTS.md/this task's own scope), so the only way to honour
8266        // "nothing starts before a valid report returns" is to not start
8267        // anything further on this worktree from this run at all.
8268        if matches!(step, FixStep::Recorded { report_lost: true }) {
8269            self.stop_reviewing(
8270                "the fixer's adoption report never came back, even after resuming its \
8271                         own seat; refusing to start another round against the same worktree \
8272                         while that is unresolved",
8273                &shell,
8274                &winner.worktree,
8275            )
8276            .await?;
8277            return Ok(false);
8278        }
8279
8280        let streak = self
8281            .state
8282            .reviews
8283            .iter()
8284            .rev()
8285            .take_while(|r| !r.progressed)
8286            .count();
8287        if streak >= STAGNANT_LIMIT {
8288            self.stop_reviewing(
8289                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8290                &shell,
8291                &winner.worktree,
8292            )
8293            .await?;
8294            return Ok(false);
8295        }
8296        Ok(true)
8297    }
8298
8299    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8300    async fn run_fix_round(
8301        &mut self,
8302        winner: &Candidate,
8303        round_record: &mut ReviewRound,
8304    ) -> Result<FixStep> {
8305        let round = round_record.round;
8306        let max_rounds = self.state.config.graph.review_rounds;
8307        let run_id = self.state.id.clone();
8308        let prompts = self.state.config.prompts.clone();
8309        let language = self.state.config.graph.language.clone();
8310        let sessions = self.state.config.graph.sessions;
8311        let artifacts = self.merge_repair_artifacts();
8312        let base = self.landing_base();
8313        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8314        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8315        let this_round_verification = round_record.verification_summary(&head);
8316        let all_findings: Vec<_> = round_record
8317            .reviews
8318            .iter()
8319            .flat_map(|r| r.findings.iter().cloned())
8320            .collect();
8321        // Fix. The winner's own implementer seat continues its conversation:
8322        // the competition is over, so context is pure benefit now.
8323        let blocking_findings: Vec<_> = all_findings
8324            .iter()
8325            .filter(|f| f.severity.blocks())
8326            .cloned()
8327            .collect();
8328        let fix_prompt = prompt::fix_in(
8329            &self.state.instruction,
8330            &blocking_findings,
8331            this_round_verification.as_ref(),
8332            round,
8333            max_rounds,
8334            &language,
8335            &self.state.config.graph.github_language,
8336        );
8337        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8338        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8339        let (job, seat, out) = self
8340            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8341                prompt: fix_prompt.clone(),
8342                spec,
8343                seat,
8344                cwd: winner.worktree.clone(),
8345                timeout,
8346                allow_write: true,
8347                sessions,
8348                artifacts: artifacts.clone(),
8349                stem: format!("fix-{round}"),
8350                handover: None,
8351            })
8352            .await;
8353        // Not asked: the round is not recorded (so a resume repeats it),
8354        // no fixer was handed over to, and the seat is left as it was.
8355        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8356            return Ok(FixStep::Resource);
8357        }
8358        let agent_id = seat.agent.clone();
8359
8360        let mut fix = FixRecord {
8361            agent: agent_id,
8362            addressed: Vec::new(),
8363            rejected: Vec::new(),
8364            notes: String::new(),
8365            committed: false,
8366            failed: None,
8367            duration_ms: 0,
8368            continuation: None,
8369        };
8370        let mut continuation = ContinuationRecord::not_needed();
8371        let mut final_seat = seat.clone();
8372        match out {
8373            AgentOutcome::Ok(o) => {
8374                fix.duration_ms = o.duration_ms;
8375                let parsed = verdict::extract_json::<FixReport>(&o.text);
8376                // A parsed report standing next to a command this same
8377                // reply's own CLI never confirmed the exit status of is
8378                // not a resolved answer — the identical `CommandEvidence`
8379                // `state.jobs` renders, read here instead of only on
8380                // display, per the completion judgment and the shown
8381                // record needing to agree.
8382                let incomplete_reason = match &parsed {
8383                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8384                        "the reply parsed, but it reported a command whose own CLI never \
8385                             confirmed an exit status"
8386                            .to_owned(),
8387                    ),
8388                    Ok(_) => None,
8389                    Err(e) => Some(e.to_string()),
8390                };
8391                match incomplete_reason {
8392                    None => {
8393                        let report = parsed.expect("checked Ok above");
8394                        fix.addressed = report.addressed;
8395                        fix.rejected = report.rejected;
8396                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8397                    }
8398                    Some(reason) => {
8399                        let (resumed_seat, resolved, failure, cont) = self
8400                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8401                            .await;
8402                        fix.duration_ms += cont.cumulative_wait_ms;
8403                        continuation = cont;
8404                        final_seat = resumed_seat;
8405                        match resolved {
8406                            Some(report) => {
8407                                fix.addressed = report.addressed;
8408                                fix.rejected = report.rejected;
8409                                fix.notes =
8410                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8411                            }
8412                            None => fix.failed = failure,
8413                        }
8414                    }
8415                }
8416            }
8417            // The CLI's raw error JSON is not a fix report to parse.
8418            AgentOutcome::Dropped(o) => {
8419                fix.duration_ms = o.duration_ms;
8420                let why = o
8421                    .dropped
8422                    .as_ref()
8423                    .map(|d| d.why.as_str())
8424                    .unwrap_or("the CLI ended the stream without delivering its answer");
8425                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8426            }
8427            AgentOutcome::Quota(o) => {
8428                self.state.quota.push(QuotaLoss::from_report(
8429                    final_seat.key.clone(),
8430                    "fix",
8431                    o.quota.as_ref(),
8432                ));
8433                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8434            }
8435            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8436        }
8437        if self.state.resource_block.is_some() {
8438            self.state.seats.insert(final_seat.key.clone(), final_seat);
8439            return Ok(FixStep::Resource);
8440        }
8441        fix.continuation = Some(continuation);
8442        self.state.seats.insert(final_seat.key.clone(), final_seat);
8443        let coordination = self.coordinate(&winner.worktree).await?;
8444        if let Ok(r) = git::rescue_commit(
8445            &winner.worktree,
8446            &format!("magi: review round {round} fixes (uncommitted work)"),
8447        )
8448        .await
8449        {
8450            self.state.note_withheld("fix", &r.withheld);
8451        }
8452        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8453        fix.committed = after != before;
8454        // Judged by what `git` says moved against base, never by the
8455        // fixer's own `addressed`/`rejected` count — see
8456        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8457        // `patch` snapshot above: swallowing this error would default
8458        // `diff_after` to empty, which almost always differs from a
8459        // non-empty `patch` and reads as "progressed" — exactly backwards
8460        // for a `git` failure the stagnation check cannot see through.
8461        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8462        drop(coordination);
8463        let progressed = diff_after != patch;
8464        let commit_note = if fix.committed {
8465            "committed"
8466        } else {
8467            "NO new commit"
8468        };
8469        let tree_note = if progressed {
8470            "changed vs base"
8471        } else {
8472            "unchanged vs base"
8473        };
8474        self.state.event(
8475            "fix",
8476            match &fix.failed {
8477                // Distinct on purpose from "0 addressed, 0 rejected": the
8478                // fixer's own diff still landed (blocking counts do keep
8479                // falling round over round), only its adoption report did
8480                // not come back, so this must never read like every
8481                // finding was reviewed and declined.
8482                Some(reason) => {
8483                    format!(
8484                        "round {round}: fixer's adoption report was lost ({reason}); \
8485                             {commit_note}, tree {tree_note}"
8486                    )
8487                }
8488                None => format!(
8489                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8490                         {tree_note}{}",
8491                    fix.addressed.len(),
8492                    fix.rejected.len(),
8493                    if continuation.outcome == ContinuationOutcome::Resumed {
8494                        format!(
8495                            " (adoption report recovered after {} continuation(s))",
8496                            continuation.attempts
8497                        )
8498                    } else {
8499                        String::new()
8500                    },
8501                ),
8502            },
8503        );
8504        round_record.fix = Some(fix);
8505        round_record.progressed = progressed;
8506        Ok(FixStep::Recorded {
8507            report_lost: matches!(
8508                continuation.outcome,
8509                ContinuationOutcome::Exhausted
8510                    | ContinuationOutcome::QuotaLost
8511                    | ContinuationOutcome::NoSession
8512            ),
8513        })
8514    }
8515
8516    /// Decide, from the last recorded round's own verification, whether
8517    /// stopping the review loop is a hand-off or a genuine block.
8518    ///
8519    /// Called once the loop has given up trying — the round budget is spent,
8520    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8521    /// findings still open, never while a round is still clean or the
8522    /// incomplete-panel case handled inline above. Gate and e2e are facts
8523    /// about the tree; a lingering review finding is an opinion, and this
8524    /// workload's own `magi stats` puts reviewer precision low enough
8525    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8526    /// must not by itself stand between a green, verified change and the
8527    /// human who decides what to do with it. A red e2e is not an opinion, so
8528    /// that case still blocks, with the failing command and a tail of its
8529    /// output recorded here rather than left in `run.json` for someone to go
8530    /// find.
8531    ///
8532    /// A round that deferred its own e2e (see [`Config::graph`]'s
8533    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8534    /// only because nothing ran, and treating an empty list as a passing one
8535    /// here is exactly the "deferred painted green" bug this function exists
8536    /// to not have. When the last round's own verification never resolved —
8537    /// deferred on purpose, or a real attempt the shared build cache blocked
8538    /// — this makes (or retries) the real run, on the actual worktree this
8539    /// loop is about to stop touching, before deciding anything. A
8540    /// resource-blocked attempt is likewise never read as either green or
8541    /// red: it is evidence about the machine, not the patch (see
8542    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8543    /// blocked cache leaves this call without deciding rather than guessing
8544    /// — the caller retries on a later reentry.
8545    /// Record, once, that the review loop handed off over a blocking finding
8546    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8547    /// `land` asks the owner even with `land_approval` off. Called from every
8548    /// path that concludes `Gating`; a reentry keeps the first record.
8549    fn record_contested_handoff(&mut self) {
8550        if self.state.contested_handoff.is_some() {
8551            return;
8552        }
8553        let Some(contested) = self
8554            .state
8555            .reviews
8556            .last()
8557            .and_then(ReviewRound::contested_handoff)
8558        else {
8559            return;
8560        };
8561        self.state.event(
8562            "review",
8563            format!(
8564                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8565                 wait for the owner's approval",
8566                contested.findings.len(),
8567                contested.rejecters.len()
8568            ),
8569        );
8570        self.state.contested_handoff = Some(contested);
8571    }
8572
8573    async fn stop_unresolved_review(
8574        &mut self,
8575        why: &str,
8576        shell: &[String],
8577        worktree: &Path,
8578    ) -> Result<()> {
8579        self.stop_reviewing_inner(why, shell, worktree, true).await
8580    }
8581
8582    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8583        self.stop_reviewing_inner(why, shell, worktree, false).await
8584    }
8585
8586    async fn stop_reviewing_inner(
8587        &mut self,
8588        why: &str,
8589        shell: &[String],
8590        worktree: &Path,
8591        repairable: bool,
8592    ) -> Result<()> {
8593        let round_idx = self.state.reviews.len() - 1;
8594        // A deferred round and a resource-blocked one are the same shape
8595        // here: neither has a real result yet, and both get one more
8596        // attempt. Read off `e2e_status` — the single source for this —
8597        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8598        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8599        // still retries instead of being read as a settled result the
8600        // instant it stops being empty.
8601        let needs_catchup_run = matches!(
8602            self.state.reviews[round_idx].e2e_status(),
8603            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8604        );
8605        if needs_catchup_run {
8606            let round = self.state.reviews[round_idx].round;
8607            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8608            let commands = self.state.config.verify.e2e.clone();
8609            let before_head = git::rev_parse(worktree, "HEAD").await?;
8610            let winner = self.state.winner().cloned();
8611            let cache_dir = self.state.config.cache_dir();
8612            let context = format!(
8613                "round {round}: verification unresolved, catching up before the final decision"
8614            );
8615            let wait = self.repository_wait();
8616            let (outcomes, verify_retried) = with_cache_lease(
8617                &mut self.state,
8618                cache_dir.as_deref(),
8619                "e2e",
8620                "e2e",
8621                worktree,
8622                &before_head,
8623                timeout,
8624                &context,
8625                &wait,
8626                |state, budget| {
8627                    let shell = shell.to_vec();
8628                    let commands = commands.clone();
8629                    let context = context.clone();
8630                    async move {
8631                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8632                            // Same reason as in the round itself: format before
8633                            // the suite, not after it.
8634                            Self::run_pre_gate(state, &winner).await;
8635                        }
8636                        run_e2e_with_retry(
8637                            state,
8638                            &shell,
8639                            &commands,
8640                            worktree,
8641                            budget,
8642                            &context,
8643                            Some(round),
8644                        )
8645                        .await
8646                    }
8647                },
8648            )
8649            .await?;
8650            // After `pre_gate`: the commit the commands actually ran against.
8651            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8652            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8653                self.state.record_base_progress(&attempted_head);
8654            }
8655            let last = &mut self.state.reviews[round_idx];
8656            last.e2e = outcomes;
8657            last.verify_retried = verify_retried;
8658            // Always the commit and time this attempt actually targeted,
8659            // whether or not it happens to equal the reviewed `head` and
8660            // whether or not a command finished — see
8661            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8662            // attempt is recorded too, so a later reader sees "attempted
8663            // again at T2" rather than silence.
8664            last.verified_head = Some(attempted_head);
8665            last.verified_at = Some(Timestamp::now());
8666            if verify_inconclusive(&last.e2e) {
8667                // Still not a real result: `e2e_deferred` is left exactly
8668                // as it was, so `needs_catchup_run` above reads
8669                // `ResourceBlocked` (via `e2e_status`, which checks
8670                // `resource_blocked` before `e2e_deferred`) and retries
8671                // again on the next reentry, rather than recording
8672                // contention as a red e2e and blocking the run on it.
8673                self.state.save()?;
8674                return Ok(());
8675            }
8676            last.e2e_deferred = false;
8677            // A complete panel may have been saved as unclean solely because
8678            // verification could not run. Refresh that verdict with the new
8679            // outcomes before a granted repair consumes the round's result.
8680            // Incomplete panels retain their original policy/quota decision.
8681            if last.answered == last.expected {
8682                last.clean = round_is_clean(
8683                    last.blocking,
8684                    last.e2e.iter().all(CommandOutcome::ok),
8685                    last.answered,
8686                    last.expected,
8687                    0,
8688                    self.state.config.graph.incomplete_review,
8689                );
8690            }
8691        }
8692        let last = &self.state.reviews[round_idx];
8693        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8694
8695        match last.e2e_status() {
8696            E2eStatus::Failed => {
8697                let red: Vec<String> = last
8698                    .e2e
8699                    .iter()
8700                    .filter(|o| !o.ok())
8701                    .map(|o| {
8702                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8703                            .map(|c| format!(" ({c})"))
8704                            .unwrap_or_default();
8705                        format!(
8706                            "`{}` -> {:?}{comparison}\n{}",
8707                            o.command,
8708                            o.code,
8709                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8710                        )
8711                    })
8712                    .collect();
8713                let can_repair = last.blocking == 0 && last.fix.is_none();
8714                self.state.reviews[round_idx].clean = false;
8715                self.state
8716                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8717                self.state.status = RunStatus::Blocked;
8718                if repairable
8719                    && can_repair
8720                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8721                {
8722                    self.state.status = RunStatus::Reviewing;
8723                }
8724            }
8725            // `needs_catchup_run` above already retried once this call; if
8726            // it is still blocked, this is magi's own admission it could
8727            // not get a command to run, never a verdict on the patch — the
8728            // run is left exactly where a later reentry can retry again.
8729            E2eStatus::ResourceBlocked => {
8730                self.state.event(
8731                    "review",
8732                    format!(
8733                        "{why}; e2e could not run (resource unavailable); not \
8734                         deciding yet"
8735                    ),
8736                );
8737            }
8738            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8739                self.state.event(
8740                    "review",
8741                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8742                );
8743                self.record_contested_handoff();
8744                self.state.status = RunStatus::Gating;
8745            }
8746        }
8747        self.state.save()?;
8748        Ok(())
8749    }
8750
8751    // ----------------------------------------------------------------- gate
8752
8753    async fn gate(&mut self) -> Result<()> {
8754        if self.hold_base_sync().await? {
8755            return Ok(());
8756        }
8757        // Judged by the review record itself, not by `status`: a solo
8758        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8759        // reentry (see `judge`), and trusting it here is exactly how a run
8760        // that exhausted its review budget got gated and merged a second
8761        // time around. `review_conclusion` recomputes the review loop's own
8762        // verdict from the round records themselves — `Gating` for a clean
8763        // round or a hand-off (see `stop_reviewing`), anything else means the
8764        // loop is still going or genuinely blocked.
8765        // A base the winner could not be replayed onto is a decision, not a
8766        // round: there is no landing tree to gate. Read as its own record for
8767        // the same reason the review verdict is.
8768        if self.state.status == RunStatus::Failed
8769            || self
8770                .state
8771                .base_sync
8772                .as_ref()
8773                .is_some_and(|s| s.conflict.is_some())
8774            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8775                != Some(RunStatus::Gating)
8776        {
8777            return Ok(());
8778        }
8779        let Some(winner) = self.state.winner().cloned() else {
8780            return Ok(());
8781        };
8782        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8783        self.state.reconcile_verification_head(&head);
8784        self.state.save()?;
8785        let wait = self.repository_wait();
8786        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8787            return Ok(());
8788        }
8789        if self.state.gate_ran {
8790            // `review_loop` derives its conclusion from the clean review
8791            // record on every reentry and therefore puts a completed run back
8792            // in `Gating`. A recorded gate is a stronger, terminal fact:
8793            // retain its original command output (or lack of any, for a repo
8794            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8795            // doc) and restore `Blocked` on a real failure rather than
8796            // pretending the command is still running or running it a second
8797            // time. `gate_ran == false` remains the only shape — unattempted,
8798            // or a resource-blocked retry — that may still need to execute a
8799            // command.
8800            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8801                self.state.status = RunStatus::Blocked;
8802                self.state.save()?;
8803            }
8804            return Ok(());
8805        }
8806        self.state.status = RunStatus::Gating;
8807        let mut outcomes = self.run_gate(&winner).await?;
8808        let mut attempted_head = self.state.gate_head.clone();
8809        loop {
8810            // A resource-blocked outcome means the gate command never actually
8811            // ran - the shared build cache could not be acquired or confirmed
8812            // fresh in time - which is evidence about the machine, not about
8813            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8814            // Recording it as a red gate would mark a run `Blocked` on nothing
8815            // but contention magi has already logged; leaving `self.state.gate`
8816            // empty and `self.state.gate_ran` false instead keeps the shape
8817            // this function already treats as "still needs to run" (see the
8818            // early-return above), so the next call retries the command
8819            // rather than concluding anything.
8820            if verify_inconclusive(&outcomes) {
8821                self.state.save()?;
8822                return Ok(());
8823            }
8824            if outcomes.iter().all(CommandOutcome::ok) {
8825                break;
8826            }
8827            let fixes_before = self.state.gate_fixes.len();
8828            match self.gate_fix_round(&winner, &outcomes).await? {
8829                GateFix::Retry => {
8830                    outcomes = self.run_gate(&winner).await?;
8831                    attempted_head = self.state.gate_head.clone();
8832                }
8833                GateFix::Stop => {
8834                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8835                    if self.state.gate_fixes.len() > fixes_before
8836                        && attempted_head.as_deref() != Some(current.as_str())
8837                        && verify_current_head(&mut self.state, &winner, &wait).await?
8838                    {
8839                        // A new SHA owes a gate even when a spent fixer changed only
8840                        // commit metadata. This does not grant another repair round.
8841                        outcomes = self.run_gate(&winner).await?;
8842                        attempted_head = self.state.gate_head.clone();
8843                    } else {
8844                        break;
8845                    }
8846                }
8847                GateFix::Defer => {
8848                    self.state.save()?;
8849                    return Ok(());
8850                }
8851            }
8852        }
8853        let passed = outcomes.iter().all(CommandOutcome::ok);
8854        self.state.gate = outcomes;
8855        self.state.gate_ran = true;
8856        self.state.gate_head = attempted_head;
8857        if !self.state.gate.is_empty()
8858            && !verify_inconclusive(&self.state.gate)
8859            && let Some(head) = self.state.gate_head.clone()
8860        {
8861            self.state.record_base_progress(&head);
8862        }
8863        self.state.save()?;
8864        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8865            return Ok(());
8866        }
8867        if !passed {
8868            self.state.status = RunStatus::Blocked;
8869            let spent = self.state.gate_fixes.len();
8870            self.state.event(
8871                "gate",
8872                if spent == 0 {
8873                    "gate failed; not merging".to_owned()
8874                } else {
8875                    format!("gate failed after {spent} gate-fix round(s); not merging")
8876                },
8877            );
8878        }
8879        self.state.save()?;
8880        Ok(())
8881    }
8882
8883    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8884    /// changed into one commit. Runs before `verify.e2e` in the review loop
8885    /// and again before the gate commands, always on the winner and never on
8886    /// a candidate awaiting judging.
8887    ///
8888    /// Before e2e as well as before the gate because command evidence belongs
8889    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8890    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8891    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8892    /// own call then finds nothing left to change. The commands must be
8893    /// idempotent; one that is not makes a commit per call.
8894    ///
8895    /// Never fails the run: a non-zero exit or timeout is a warning and a
8896    /// recorded outcome, and the gate remains the single arbiter. Nothing
8897    /// configured means nothing happens - no event, no commit. `commit_all`
8898    /// commits any leftover change under the neutral identity and returns
8899    /// `false` when the tree is clean, so no empty commit is ever made.
8900    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8901        let commands = state.config.verify.pre_gate.clone();
8902        if commands.is_empty() {
8903            return;
8904        }
8905        let shell = state.config.shell();
8906        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8907        let (outcomes, _) = run_commands(
8908            state,
8909            "pre_gate",
8910            "pre_gate",
8911            0,
8912            &shell,
8913            &commands,
8914            &winner.worktree,
8915            timeout,
8916        )
8917        .await;
8918        for o in &outcomes {
8919            if !o.ok() {
8920                tracing::warn!(
8921                    "pre_gate `{}` failed ({:?}); the gate decides",
8922                    o.command,
8923                    o.code
8924                );
8925            }
8926            state.event(
8927                "pre_gate",
8928                format!(
8929                    "`{}` -> {}",
8930                    o.command,
8931                    if o.ok() {
8932                        "pass".to_owned()
8933                    } else {
8934                        format!(
8935                            "FAIL ({:?})\n{}",
8936                            o.code,
8937                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8938                        )
8939                    }
8940                ),
8941            );
8942        }
8943        state.pre_gate = outcomes;
8944        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8945            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8946                Ok(head) => {
8947                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8948                    state.pre_gate_commit = Some(head);
8949                }
8950                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8951            },
8952            Ok(false) => {}
8953            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8954        }
8955        if let Err(e) = state.save() {
8956            tracing::warn!("could not persist the pre_gate record: {e:#}");
8957        }
8958    }
8959
8960    /// Run `verify.gate` once against the winner's current tree, logging one
8961    /// event per command. Empty when nothing is configured.
8962    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8963        let wait = self.repository_wait();
8964        run_landing_gate(&mut self.state, winner, &wait).await
8965    }
8966
8967    /// One bounded fix round for a failing gate.
8968    ///
8969    /// The fixer is told the failure came from the gate itself, not from a
8970    /// reviewer, and is shown the failed commands, their exit codes and a tail
8971    /// of their output - whatever `[verify].gate` holds, nothing here knows
8972    /// what those commands run. Only a normal non-zero exit that printed
8973    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8974    /// command or a full disk says nothing about the code, and a fixer sent
8975    /// after it can only appease the machine. The round is judged by what git
8976    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8977    /// again before the gate does, so a fix cannot trade a green gate for a
8978    /// red e2e unnoticed.
8979    async fn gate_fix_round(
8980        &mut self,
8981        winner: &Candidate,
8982        outcomes: &[CommandOutcome],
8983    ) -> Result<GateFix> {
8984        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8985            g.phase == crate::repair_budget::Phase::Fixing
8986                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8987        }) {
8988            self.state.gate_fixes.len().saturating_add(1)
8989        } else {
8990            self.state.config.graph.gate_fix_rounds
8991        };
8992        let spent = self.state.gate_fixes.len();
8993        if spent >= cap {
8994            if cap > 0 {
8995                self.state.event(
8996                    "gate",
8997                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8998                );
8999            }
9000            return Ok(GateFix::Stop);
9001        }
9002        if !gate_fixable(outcomes) {
9003            self.state.event(
9004                "gate",
9005                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9006                 command or similar); not spending a fix round on it",
9007            );
9008            return Ok(GateFix::Stop);
9009        }
9010        let min_free = self.state.config.disk.min_free_bytes;
9011        if min_free > 0 {
9012            match crate::disk::free_bytes(&winner.worktree) {
9013                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9014                Ok(free) => {
9015                    self.state.event(
9016                        "gate",
9017                        format!(
9018                            "only {free} bytes free ({min_free} required by `[disk] \
9019                             min_free_bytes`); not spending a fix round on a failure the disk \
9020                             may explain"
9021                        ),
9022                    );
9023                    return Ok(GateFix::Stop);
9024                }
9025                Err(e) => {
9026                    self.state.event(
9027                        "gate",
9028                        format!("free disk space could not be measured ({e:#}); no fix round"),
9029                    );
9030                    return Ok(GateFix::Stop);
9031                }
9032            }
9033        }
9034
9035        let attempt = spent + 1;
9036        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9037        let base = self.landing_base();
9038        let fix_prompt = prompt::gate_fix_in(
9039            &self.state.instruction,
9040            &failed,
9041            attempt,
9042            cap,
9043            &self.state.config.graph.language,
9044            &self.state.config.graph.github_language,
9045        );
9046        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9047        let sessions = self.state.config.graph.sessions;
9048        let artifacts = self.merge_repair_artifacts();
9049        self.state.event(
9050            "gate",
9051            format!("gate failed; gate-fix round {attempt} of {cap}"),
9052        );
9053        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9054        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9055        // Persist before invoking the fixer: it may commit and then be
9056        // interrupted before its result (or the following e2e) is saved.
9057        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9058            before.clone(),
9059            false,
9060            Vec::new(),
9061        ));
9062        self.state.save()?;
9063        let (_, seat, out) = self
9064            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9065                prompt: fix_prompt.clone(),
9066                spec,
9067                seat,
9068                cwd: winner.worktree.clone(),
9069                timeout,
9070                allow_write: true,
9071                sessions,
9072                artifacts: artifacts.clone(),
9073                stem: format!("gate-fix-{attempt}"),
9074                handover: None,
9075            })
9076            .await;
9077        // The fixer was never asked: no round is spent (nothing is recorded)
9078        // and a later reentry asks the same agent again.
9079        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9080            return Ok(GateFix::Defer);
9081        }
9082        let mut record = GateFixRecord {
9083            agent: seat.agent.clone(),
9084            failed,
9085            notes: String::new(),
9086            committed: false,
9087            error: None,
9088        };
9089        match out {
9090            AgentOutcome::Ok(o) => {
9091                // A missing report is not a failed fix: the round is judged
9092                // by the tree below, and the report only carries prose.
9093                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9094                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9095                }
9096            }
9097            AgentOutcome::Dropped(_) => {
9098                record.error = Some("the CLI dropped the stream".to_owned());
9099            }
9100            AgentOutcome::Quota(o) => {
9101                self.state.quota.push(QuotaLoss::from_report(
9102                    seat.key.clone(),
9103                    "gate-fix",
9104                    o.quota.as_ref(),
9105                ));
9106                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9107            }
9108            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9109        }
9110        self.state.seats.insert(seat.key.clone(), seat);
9111        let coordination = self.coordinate(&winner.worktree).await?;
9112        if let Ok(r) = git::rescue_commit(
9113            &winner.worktree,
9114            &format!("magi: gate fix {attempt} (uncommitted work)"),
9115        )
9116        .await
9117        {
9118            self.state.note_withheld("gate-fix", &r.withheld);
9119        }
9120        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9121        record.committed = after != before;
9122        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9123        let note = record.error.clone();
9124        self.state.gate_fixes.push(record);
9125        self.state.save()?;
9126        if !changed {
9127            self.state.event(
9128                "gate",
9129                match note {
9130                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9131                    None => format!("gate-fix round {attempt}: the tree did not change"),
9132                },
9133            );
9134            return Ok(GateFix::Stop);
9135        }
9136        self.state.event(
9137            "gate",
9138            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9139        );
9140
9141        drop(coordination);
9142        let wait = self.repository_wait();
9143        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9144    }
9145
9146    // ---------------------------------------------------------------- merge
9147
9148    /// One read-only rewrite by the summary's author; a text the gate still
9149    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9150    /// applies on their word or on silence. `None` means the run is parked on
9151    /// that question and nothing may be pushed or opened yet.
9152    async fn guarded_pr_message(
9153        &mut self,
9154        winner: &Candidate,
9155        facts: Option<&BranchFacts>,
9156        posting: bool,
9157    ) -> Result<Option<PrMessage>> {
9158        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9159        let head = match final_head.as_deref() {
9160            Some(h) => crate::pr_outcome::FinalHead::At(h),
9161            None => crate::pr_outcome::FinalHead::Unknown,
9162        };
9163        // Only a pull request that is about to be posted pays for a summary.
9164        let summarized = if posting {
9165            Some(self.summarize_change(winner, final_head.as_deref()).await)
9166        } else {
9167            None
9168        };
9169        // A busy shared resource is not a permanent cause: publishing an
9170        // "unavailable" description would stick (a later head move never
9171        // edits the body). Stop before anything is pushed or opened; the
9172        // run is `Blocked` and a resume asks the summary again.
9173        if self.state.resource_block.is_some() {
9174            self.state.event(
9175                "pr-summary",
9176                "a shared resource was busy; nothing was published, resume to summarize again",
9177            );
9178            return Ok(None);
9179        }
9180        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9181            anyhow::bail!(
9182                "the final commit moved during public description generation; retry before publishing"
9183            );
9184        }
9185        let note = match (&summarized, &self.state.change_summary) {
9186            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9187            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9188            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9189            (None, _) => ChangeNote::NotAsked,
9190        };
9191        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9192        if !posting {
9193            let identity = crate::scrub::Identity::current();
9194            return Ok(Some(PrMessage {
9195                title: crate::scrub::scrub(&pr.title, &identity),
9196                body: crate::scrub::scrub(&pr.body, &identity),
9197            }));
9198        }
9199        // This very text was already rejected and asked about: no second
9200        // judge call, rewrite or question, just carry the record on.
9201        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9202        if let Some(known) = self
9203            .state
9204            .github_text
9205            .clone()
9206            .filter(|g| g.fingerprint == raw_fp)
9207        {
9208            return self.settle_withheld(winner, &pr, known).await;
9209        }
9210        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9211        let mut violations =
9212            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9213        let identity = crate::scrub::Identity::current();
9214        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9215            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9216            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9217        {
9218            violations.push(crate::github_text::Violation::SensitiveData);
9219        }
9220        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9221        // only a language violation starts one; sensitive data alone goes
9222        // straight to the owner, with the redacted text as the fallback.
9223        let has_language = violations
9224            .iter()
9225            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9226        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9227            self.state.event(
9228                "github-text",
9229                if has_language {
9230                    format!("description rejected: {violations:?}; requesting one rewrite")
9231                } else {
9232                    format!("description rejected: {violations:?}; asking the owner")
9233                },
9234            );
9235            let mut rewritten = false;
9236            let mut rejected_rewrite = None;
9237            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9238            {
9239                let output = text;
9240                if let Some(title) = summary_title(&output) {
9241                    // Judge the redacted candidate that will actually be posted.
9242                    // Sensitive data alone must not discard a useful rewrite.
9243                    let raw_body = summary_without_title(&output);
9244                    let clean_title = crate::scrub::scrub(&title, &identity);
9245                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9246                    let redacted = clean_title != title || body != raw_body;
9247                    let title = clean_title;
9248                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9249                    if !complete {
9250                        self.state.event(
9251                            "github-text",
9252                            "description rewrite omitted required findings",
9253                        );
9254                    }
9255                    if !body.trim().is_empty() {
9256                        body.push_str("\n\n");
9257                        body.push_str(&public_pr_evidence(&self.state, head));
9258                    }
9259                    let marker = format!("magi:run/{}", self.state.id);
9260                    if !body.trim().is_empty() && !body.contains(&marker) {
9261                        body.push_str(&format!("\n\n{marker}"));
9262                    }
9263                    let rewrite = PrMessage {
9264                        title: title.clone(),
9265                        body: body.clone(),
9266                    };
9267                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9268                    let mut failed = crate::github_text::check_for(
9269                        &self.state.config.graph,
9270                        &title,
9271                        &body,
9272                        redecision,
9273                    );
9274                    if (!crate::github_text::shareable(&title)
9275                        || !crate::github_text::shareable(&body))
9276                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9277                    {
9278                        failed.push(crate::github_text::Violation::SensitiveData);
9279                    }
9280                    if complete
9281                        && !title.trim().is_empty()
9282                        && !body.trim().is_empty()
9283                        && !failed.is_empty()
9284                    {
9285                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9286                            title: title.clone(),
9287                            body: body.clone(),
9288                            failed: failed
9289                                .iter()
9290                                .map(|v| crate::github_text::category(*v).to_owned())
9291                                .collect(),
9292                        });
9293                    }
9294                    if complete
9295                        && !title.trim().is_empty()
9296                        && !raw_body.trim().is_empty()
9297                        && failed.is_empty()
9298                    {
9299                        decision = redecision;
9300                        pr = PrMessage { title, body };
9301                        rewritten = true;
9302                        self.state
9303                            .event("github-text", "description rewrite passed");
9304                        if redacted {
9305                            self.state.event(
9306                                "github-text",
9307                                "sensitive data removed from description rewrite",
9308                            );
9309                        }
9310                    }
9311                }
9312            }
9313            if !rewritten {
9314                self.state.event(
9315                    "github-text",
9316                    "description rewrite unavailable or rejected; asking the owner",
9317                );
9318                if let Some(w) =
9319                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9320                {
9321                    // A different text than the one asked about before: that
9322                    // question no longer describes anything.
9323                    self.retire_github_text_question("the withheld text changed");
9324                    let record = crate::run::GithubTextAsk {
9325                        rewrite: rejected_rewrite,
9326                        fingerprint: raw_fp,
9327                        title: w.title,
9328                        body: w.body,
9329                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9330                        question: None,
9331                        asks: 0,
9332                        resolved: false,
9333                        chosen_title: None,
9334                        choice: None,
9335                        publication: None,
9336                    };
9337                    return self.settle_withheld(winner, &pr, record).await;
9338                }
9339            }
9340        }
9341        let (title, body) =
9342            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9343        Ok(Some(PrMessage { title, body }))
9344    }
9345
9346    /// Describe the whole change from its final diff in either run mode.
9347    ///
9348    /// The summary is tied to the final commit and to the merge base of the
9349    /// resolved remote base; a record for any other pair is dropped and the
9350    /// agent asked again, so a description never outlives the diff it was
9351    /// written from. The seat is read-only and the prompt tells it to read the
9352    /// diff and the code around it. `[roles] synthesizer` selects the agents
9353    /// (unset: the default pick), each asked at most once, advancing on an
9354    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9355    /// carries the reason it is unavailable; nothing is invented then.
9356    async fn summarize_change(
9357        &mut self,
9358        winner: &Candidate,
9359        head: Option<&str>,
9360    ) -> std::result::Result<(), String> {
9361        let Some(head) = head else {
9362            return Err("the final commit could not be read".to_owned());
9363        };
9364        let remote = self.state.config.merge.remote.clone();
9365        let tracking = format!("{remote}/{}", self.state.base_branch);
9366        if !git::rev_exists(&winner.worktree, &tracking).await {
9367            return Err(format!("the remote base `{tracking}` could not be read"));
9368        }
9369        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9370            Ok(b) if !b.is_empty() => b,
9371            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9372        };
9373        let evidence = crate::pr_outcome::summary_evidence(
9374            &self.state,
9375            crate::pr_outcome::FinalHead::At(head),
9376        );
9377        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9378        if self
9379            .state
9380            .change_summary
9381            .as_ref()
9382            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9383        {
9384            return Ok(());
9385        }
9386        if self.state.change_summary.take().is_some() {
9387            self.state.event(
9388                "pr-summary",
9389                "the final diff or evidence changed; the earlier change summary was discarded",
9390            );
9391        }
9392        // Save the source snapshot even if no generation agent is available.
9393        if let Err(e) = write_artifact(
9394            &self.state,
9395            &format!("public-description-{fingerprint}.md"),
9396            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9397        ) {
9398            tracing::warn!("could not save public description evidence: {e:#}");
9399        }
9400        let chain = match agent::pick_chain(
9401            &self.state.config.agents,
9402            self.state.config.roles.synthesizer.as_ref(),
9403            &agent::installed,
9404            "synthesizer",
9405        ) {
9406            Ok(chain) => chain,
9407            Err(e) => {
9408                tracing::warn!("no agent for the change summary: {e:#}");
9409                self.state.event("pr-summary", "no summary agent available");
9410                return Err("no agent was available to summarize it".to_owned());
9411            }
9412        };
9413        let subjects = git::subjects(&winner.worktree, &base, head)
9414            .await
9415            .unwrap_or_default();
9416        let stat = git::diff_stat(&winner.worktree, &base, head)
9417            .await
9418            .unwrap_or_default();
9419        let stat: String = stat.chars().take(6_000).collect();
9420        let mut prompt = crate::prompt::change_summary_in(
9421            &base,
9422            head,
9423            &subjects,
9424            stat.trim(),
9425            &self.state.config.graph.github_language,
9426        );
9427        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."));
9428        let sessions = self.state.config.graph.sessions;
9429        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9430        let prompts = self.state.config.prompts.clone();
9431        let cache = self.state.config.cache_dir();
9432        let run = self.state.id.clone();
9433        for (i, spec) in chain.into_iter().enumerate() {
9434            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9435            let github_spec = match agent::for_github_text(
9436                &spec,
9437                &self.state.config.graph.github_language,
9438                &winner.worktree,
9439            ) {
9440                Ok(spec) => spec,
9441                Err(e) => {
9442                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9443                    continue;
9444                }
9445            };
9446            let job = SeatJob {
9447                spec: github_spec,
9448                seat,
9449                cwd: winner.worktree.clone(),
9450                prompt: prompt.clone(),
9451                timeout,
9452                allow_write: false,
9453                sessions,
9454                artifacts: agent::artifacts_dir(&self.state.dir()),
9455                stem: if i == 0 {
9456                    "change-summary".to_owned()
9457                } else {
9458                    format!("change-summary-{}", spec.id)
9459                },
9460                handover: None,
9461            };
9462            let ctx = WaveCtx {
9463                run: &run,
9464                node: "pr-summary",
9465                prompts: &prompts,
9466                cache: cache.as_deref(),
9467                round: None,
9468                carry_seats: false,
9469                pauses: Some((&self.pause, &self.interrupt)),
9470            };
9471            let (seat, outcome) =
9472                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9473            self.state.seats.insert(seat.key.clone(), seat);
9474            let text = match outcome {
9475                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9476                AgentOutcome::ResourceBlocked(why) => {
9477                    // No agent was asked: the run stops resumably before
9478                    // anything is published (see `guarded_pr_message`).
9479                    if self.state.resource_block.is_none() {
9480                        self.state.resource_block = Some(crate::run::ResourceBlock {
9481                            cause: crate::run::ResourceBlockCause::Other,
9482                            node: "pr-summary".to_owned(),
9483                            kind: "shared resource".to_owned(),
9484                            detail: why,
9485                            at: Timestamp::now(),
9486                        });
9487                    }
9488                    return Err("a shared resource was busy".to_owned());
9489                }
9490                _ => continue,
9491            };
9492            let blind = &self.state.config.blind;
9493            let Some(title) = summary_title(&text) else {
9494                continue;
9495            };
9496            let body: String = summary_without_title(&text)
9497                .lines()
9498                .filter(|l| !l.contains("magi:run/"))
9499                .collect::<Vec<_>>()
9500                .join("\n");
9501            let body = blind::sanitize_prose(body.trim(), blind);
9502            let title = blind::sanitize_prose(&title, blind);
9503            if body.trim().is_empty() || title.trim().is_empty() {
9504                continue;
9505            }
9506            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9507                continue;
9508            }
9509            // The branch must still be the one the agent was shown.
9510            if git::rev_parse(&winner.worktree, "HEAD")
9511                .await
9512                .ok()
9513                .as_deref()
9514                != Some(head)
9515            {
9516                return Err("the branch moved while the summary was written".to_owned());
9517            }
9518            if git::merge_base(&winner.worktree, &tracking, head)
9519                .await
9520                .ok()
9521                .as_deref()
9522                != Some(base.as_str())
9523                || crate::pr_outcome::summary_evidence(
9524                    &self.state,
9525                    crate::pr_outcome::FinalHead::At(head),
9526                ) != evidence
9527            {
9528                return Err("the summary evidence changed while it was written".to_owned());
9529            }
9530            self.state.change_summary = Some(crate::run::ChangeSummary {
9531                head: head.to_owned(),
9532                base,
9533                evidence: fingerprint,
9534                title,
9535                body,
9536            });
9537            self.state.event(
9538                "pr-summary",
9539                format!("change summary written by {} for the final diff", spec.id),
9540            );
9541            if let Err(e) = self.state.save() {
9542                tracing::warn!("could not save the change summary: {e:#}");
9543            }
9544            return Ok(());
9545        }
9546        self.state
9547            .event("pr-summary", "no agent produced a change summary");
9548        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9549    }
9550
9551    /// One read-only rewrite request for a withheld description. The
9552    /// implementer's own conversation is tried first when it exists and can be
9553    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9554    /// writes it in a separate conversation, skipping the implementer's agent.
9555    /// The prompt carries the whole text, so no agent needs any memory. Each
9556    /// agent is asked at most once and the chain advances on an error, quota,
9557    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9558    /// that has run out of quota must not end the rewrite. Nothing is recorded
9559    /// as a handover.
9560    async fn rewrite_pr_text(
9561        &mut self,
9562        winner: &Candidate,
9563        pr: &PrMessage,
9564        violations: &[crate::github_text::Violation],
9565    ) -> Option<String> {
9566        let prompt = format!(
9567            "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{}",
9568            pr.title, pr.body
9569        );
9570        let sessions = self.state.config.graph.sessions;
9571        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9572        // (spec, the resumed implementer's seat). A fallback seat is created
9573        // only when its turn comes, so an unused fallback leaves no record.
9574        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9575        let key = format!("impl-{}", winner.label);
9576        if let Some(spec) = self
9577            .state
9578            .config
9579            .agents
9580            .iter()
9581            .find(|a| a.id == winner.agent)
9582            .cloned()
9583            && let Some(existing) = self.state.seats.get(&key)
9584            && existing.agent == spec.id
9585            && agent::has_session(spec.kind, existing, sessions)
9586        {
9587            attempts.push((spec, Some(existing.clone())));
9588        }
9589        match agent::pick_chain(
9590            &self.state.config.agents,
9591            self.state.config.roles.language_judge.as_ref(),
9592            &agent::installed,
9593            "language_judge",
9594        ) {
9595            Ok(chain) => {
9596                for spec in chain {
9597                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9598                        continue;
9599                    }
9600                    attempts.push((spec, None));
9601                }
9602            }
9603            Err(e) if attempts.is_empty() => {
9604                tracing::warn!("no agent for the description rewrite: {e:#}");
9605                self.state
9606                    .event("github-text", "no rewrite agent available");
9607                return None;
9608            }
9609            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9610        }
9611        let prompts = self.state.config.prompts.clone();
9612        let cache = self.state.config.cache_dir();
9613        let run = self.state.id.clone();
9614        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9615            let resumed = resumed_seat.is_some();
9616            let seat = resumed_seat.unwrap_or_else(|| {
9617                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9618            });
9619            let github_spec = match agent::for_github_text(
9620                &spec,
9621                &self.state.config.graph.github_language,
9622                &winner.worktree,
9623            ) {
9624                Ok(spec) => spec,
9625                Err(e) => {
9626                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9627                    continue;
9628                }
9629            };
9630            let job = SeatJob {
9631                spec: github_spec,
9632                seat,
9633                cwd: winner.worktree.clone(),
9634                prompt: prompt.clone(),
9635                timeout: retry_budget(timeout_full, resumed),
9636                allow_write: false,
9637                sessions,
9638                artifacts: agent::artifacts_dir(&self.state.dir()),
9639                stem: if i == 0 {
9640                    "github-text-rewrite".to_owned()
9641                } else {
9642                    format!("github-text-rewrite-{}", spec.id)
9643                },
9644                handover: None,
9645            };
9646            let ctx = WaveCtx {
9647                run: &run,
9648                node: "github-text",
9649                prompts: &prompts,
9650                cache: cache.as_deref(),
9651                round: None,
9652                carry_seats: false,
9653                pauses: Some((&self.pause, &self.interrupt)),
9654            };
9655            let (seat, outcome) =
9656                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9657            self.state.seats.insert(seat.key.clone(), seat);
9658            match outcome {
9659                AgentOutcome::Ok(o)
9660                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9661                {
9662                    return Some(o.text);
9663                }
9664                AgentOutcome::ResourceBlocked(_) => return None,
9665                _ => {}
9666            }
9667        }
9668        None
9669    }
9670
9671    /// Abandon the standing posting-gate question, if any.
9672    fn retire_github_text_question(&mut self, why: &str) {
9673        let Some(id) = self
9674            .state
9675            .github_text
9676            .as_ref()
9677            .and_then(|g| g.question.clone())
9678        else {
9679            return;
9680        };
9681        let _ = ask::Questions::open().update(&id, |q| {
9682            q.abandon(why);
9683            Ok(())
9684        });
9685    }
9686
9687    /// Carry a withheld text to its end: file the question, park while it is
9688    /// open, and on an answer, silence or timeout pick the text to post. The
9689    /// decision is saved before it is used, so it applies once.
9690    async fn settle_withheld(
9691        &mut self,
9692        winner: &Candidate,
9693        pr: &PrMessage,
9694        mut g: crate::run::GithubTextAsk,
9695    ) -> Result<Option<PrMessage>> {
9696        use crate::github_text as gt;
9697        let store = ask::Questions::open();
9698        let timeout = self.state.config.graph.answer_timeout;
9699        if !g.resolved {
9700            let mut standing = g
9701                .question
9702                .as_ref()
9703                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9704            if let Some(q) = standing.as_ref()
9705                && q.status.open()
9706                && !store.held_reply(&q.id)
9707                && gt::expired(q, timeout)
9708            {
9709                let why = format!("no answer within {}s of asking", timeout.max(1));
9710                standing = store
9711                    .update(&q.id, |q| {
9712                        q.abandon(&why);
9713                        Ok(())
9714                    })
9715                    .ok()
9716                    .map(|(q, ())| q);
9717            }
9718            let mut ask_again: Option<Option<Vec<String>>> = None;
9719            match standing {
9720                // Recorded but never written (a stop between the two saves),
9721                // or removed: ask again without spending the retry.
9722                None if g.asks <= 1 => {
9723                    g.asks = 0;
9724                    ask_again = Some(None);
9725                }
9726                None => {
9727                    g.resolved = true;
9728                    g.chosen_title = None;
9729                    g.choice = Some(GithubTextChoice::Fallback);
9730                }
9731                Some(q) if q.status.open() => {
9732                    self.park_on_github_text(&g)?;
9733                    return Ok(None);
9734                }
9735                Some(q) => match gt::read_reply(&q) {
9736                    gt::Reply::Fallback => {
9737                        g.resolved = true;
9738                        g.chosen_title = None;
9739                        g.choice = Some(GithubTextChoice::Fallback);
9740                    }
9741                    gt::Reply::Original => {
9742                        g.resolved = true;
9743                        g.chosen_title = None;
9744                        g.choice = Some(GithubTextChoice::Original);
9745                    }
9746                    gt::Reply::Rewrite => {
9747                        g.resolved = true;
9748                        g.chosen_title = None;
9749                        g.choice = Some(if g.rewrite.is_some() {
9750                            GithubTextChoice::Rewrite
9751                        } else {
9752                            GithubTextChoice::Fallback
9753                        });
9754                    }
9755                    gt::Reply::Title(text) => {
9756                        let first = text
9757                            .lines()
9758                            .map(str::trim)
9759                            .find(|l| !l.is_empty())
9760                            .unwrap_or("");
9761                        let decision = if first.is_empty() {
9762                            None
9763                        } else {
9764                            let candidate = PrMessage {
9765                                title: first.to_owned(),
9766                                body: String::new(),
9767                            };
9768                            self.judge_pr_language(&winner.worktree, &candidate).await
9769                        };
9770                        match gt::vet_title(
9771                            &text,
9772                            decision,
9773                            self.state.config.graph.github_english(),
9774                        ) {
9775                            Ok(title) => {
9776                                g.resolved = true;
9777                                g.chosen_title = Some(title);
9778                                g.choice = Some(GithubTextChoice::MyTitle);
9779                            }
9780                            Err(cats) if g.asks < 2 => {
9781                                ask_again = Some(Some(
9782                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9783                                ))
9784                            }
9785                            Err(_) => {
9786                                g.resolved = true;
9787                                g.chosen_title = None;
9788                                g.choice = Some(GithubTextChoice::Fallback);
9789                            }
9790                        }
9791                    }
9792                },
9793            }
9794            if let Some(rejected) = ask_again {
9795                // A retry (after a rejected replacement title) is still about
9796                // the original text: the same ORIGINAL / FALLBACK comparison.
9797                let w = gt::Withheld {
9798                    title: g.title,
9799                    body: g.body,
9800                    categories: g.categories.clone(),
9801                };
9802                // Named by the original text's fingerprint alone, so a resume
9803                // rewrites the same file and the detail stays identical.
9804                let artifact = match crate::run::write_artifact(
9805                    &self.state,
9806                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9807                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9808                ) {
9809                    Ok(p) => Some(p),
9810                    Err(e) => {
9811                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9812                        None
9813                    }
9814                };
9815                let (detail, comparison) = gt::question_content(
9816                    &w,
9817                    &pr.title,
9818                    &pr.body,
9819                    &self.state.id,
9820                    rejected.as_deref(),
9821                    artifact.as_deref(),
9822                    g.rewrite.as_ref(),
9823                );
9824                let mut q = ask::Question::new(
9825                    self.state.id.clone(),
9826                    gt::ASK_NODE.to_owned(),
9827                    gt::ASK_SEAT.to_owned(),
9828                    gt::question_summary(&self.state.config.graph.language, &w),
9829                    detail,
9830                    gt::question_choices(&w, g.rewrite.as_ref()),
9831                );
9832                q.posting_comparison = Some(comparison);
9833                q.answer_timeout = timeout;
9834                // Recorded before it is written: a stop in between leaves a
9835                // record naming a question the resume then files again.
9836                g.question = Some(q.id.clone());
9837                g.asks += 1;
9838                self.state.github_text = Some(g.clone());
9839                self.state.event(
9840                    "github-text",
9841                    format!("asking the owner about the withheld text ({})", q.short()),
9842                );
9843                self.state.save()?;
9844                store
9845                    .put_executable(&mut q)
9846                    .context("file the posting-gate question")?;
9847                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9848                    tracing::warn!(
9849                        "could not notify about posting-gate question {}: {e:#}",
9850                        q.short()
9851                    );
9852                }
9853                self.park_on_github_text(&g)?;
9854                return Ok(None);
9855            }
9856        }
9857        let resolved = g.chosen_title.clone();
9858        let original = g.choice == Some(GithubTextChoice::Original);
9859        // Field names only: the event log never records the text.
9860        self.state.event(
9861            "github-text",
9862            if original {
9863                format!(
9864                    "posting the original text for: {}",
9865                    match (g.title, g.body) {
9866                        (true, true) => "title, description",
9867                        (true, false) => "title",
9868                        _ => "description",
9869                    }
9870                )
9871            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9872                "posting the saved rewrite title and description".to_owned()
9873            } else if resolved.is_some() {
9874                "posting the owner's replacement title".to_owned()
9875            } else {
9876                "posting the neutral text for the withheld fields".to_owned()
9877            },
9878        );
9879        self.state.github_text = Some(g.clone());
9880        self.state.save()?;
9881        if g.choice == Some(GithubTextChoice::Rewrite)
9882            && let Some(r) = g.rewrite.as_ref()
9883        {
9884            return Ok(Some(PrMessage {
9885                title: r.title.clone(),
9886                body: r.body.clone(),
9887            }));
9888        }
9889        let w = gt::Withheld {
9890            title: g.title,
9891            body: g.body,
9892            categories: g.categories.clone(),
9893        };
9894        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9895        if let Some(t) = resolved {
9896            title = t;
9897        }
9898        // Every withheld field is now neutral or vetted English.
9899        let english = gt::LanguageDecision {
9900            title_english: true,
9901            body_english: true,
9902            body_complete: true,
9903        };
9904        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9905        if original {
9906            // The owner's explicit choice overrides the gate for the fields it
9907            // was made for; the others keep what the gate produced.
9908            if g.title {
9909                title = pr.title.clone();
9910            }
9911            if g.body {
9912                body = pr.body.clone();
9913            }
9914        }
9915        Ok(Some(PrMessage { title, body }))
9916    }
9917
9918    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9919        self.state.github_text = Some(g.clone());
9920        self.state.end_pass_parked(ParkCause::Question);
9921        self.state.parked = true;
9922        self.state.event(
9923            "github-text",
9924            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9925        );
9926        self.state.save()
9927    }
9928
9929    /// Ask `[roles] language_judge` about this text and record which source
9930    /// decided; the text itself is never recorded.
9931    async fn judge_pr_language(
9932        &mut self,
9933        cwd: &Path,
9934        pr: &PrMessage,
9935    ) -> Option<crate::github_text::LanguageDecision> {
9936        self.state.config.roles.language_judge.as_ref()?;
9937        if !self.state.config.graph.language_gate() {
9938            return None;
9939        }
9940        let decision =
9941            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9942        self.state.event(
9943            "github-text",
9944            if decision.is_some() {
9945                "language decided by the language judge"
9946            } else {
9947                "language judge unavailable; using built-in heuristics"
9948            },
9949        );
9950        decision
9951    }
9952
9953    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9954        Box::pin(self.merge_inner())
9955    }
9956
9957    async fn merge_inner(&mut self) -> Result<()> {
9958        if self.resource_halt()? || self.hold_base_sync().await? {
9959            return Ok(());
9960        }
9961        // Same reasoning as `gate`: ask the review and gate records directly
9962        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9963        // skip can rewrite on reentry to something that no longer says
9964        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9965        // so a hand-off (open findings, green verification) reaches merge
9966        // exactly like a genuinely clean round does.
9967        //
9968        // A run resumed mid-`land` never reaches here at all: `execute`
9969        // recognises `RunStatus::Landing` before it even calls `prep`, and
9970        // routes straight to `run_land` instead. That has to happen a level
9971        // up from this function, not with a check in here, because
9972        // `review_loop`'s own status recomputation (see its doc) runs
9973        // *before* `merge` on every reentry and would otherwise overwrite
9974        // the `Landing` marker with `Gating` before this node ever saw it.
9975        if self
9976            .state
9977            .base_sync
9978            .as_ref()
9979            .is_some_and(|s| s.conflict.is_some())
9980            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9981                != Some(RunStatus::Gating)
9982            // `gate_ran == false` is not "passed" - `gate` leaves it false
9983            // both before it has ever run and when its last attempt was
9984            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9985            // permission to merge on nothing but the review record. Only a
9986            // gate that actually ran may proceed; an intentional local
9987            // review can also finish with verification explicitly not configured.
9988            // `RunState::gate_status` computes that distinction.
9989            || !self.state.gate_allows_progress()
9990        {
9991            return Ok(());
9992        }
9993        // This node's own record, not `status`: `status == Ready` is not
9994        // unique to the harmless `MergeMode::None` path this line was
9995        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9996        // run's PR was closed without merging — and on that run `mode` is
9997        // still `Pr`, so a reentry that fell through here would push and
9998        // open a second pull request. `self.state.merge` is set exactly once
9999        // this node (or `land`) has already produced a verdict, under every
10000        // mode, which is what "already done" actually means here.
10001        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10002            return Ok(());
10003        }
10004        let Some(winner) = self.state.winner().cloned() else {
10005            return Ok(());
10006        };
10007        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10008        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10009            self.state.status = RunStatus::Blocked;
10010            self.state.event(
10011                "gate",
10012                "winner changed after gate; fresh verification required",
10013            );
10014            self.state.save()?;
10015            return Ok(());
10016        }
10017        let wait = self.repository_wait();
10018        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10019            return Ok(());
10020        }
10021        let repo = self.state.repo.clone();
10022        let base = self.state.base_branch.clone();
10023        let mode = self.state.config.merge.mode;
10024        let style = self.state.config.merge.style;
10025        let facts = if is_review_run(&self.state) {
10026            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10027            let start = review_base(
10028                &repo,
10029                &self.state.config.merge.remote,
10030                &base,
10031                &self.state.base_commit,
10032                &winner.branch,
10033            )
10034            .await;
10035            branch_facts(&repo, &start, &winner.branch).await
10036        } else {
10037            None
10038        };
10039        // `None` when the base could not be freshly read: then an adopted
10040        // pull request's title is left alone.
10041        let leaked = if is_review_run(&self.state) {
10042            leaked_subjects(&self.state, &winner.branch).await
10043        } else {
10044            Some(Vec::new())
10045        };
10046        // `None`: parked on the owner's word about a withheld title or body.
10047        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10048        // the resume arrives here again.
10049        let Some(pr) = self
10050            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10051            .await?
10052        else {
10053            return Ok(());
10054        };
10055        let message = pr.commit_message();
10056
10057        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10058        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10059            return Ok(());
10060        }
10061        let outcome = match mode {
10062            MergeMode::None => MergeOutcome {
10063                mode,
10064                ok: true,
10065                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10066                empty: false,
10067            },
10068            MergeMode::Pr | MergeMode::Local
10069                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10070            {
10071                MergeOutcome {
10072                    mode,
10073                    ok: false,
10074                    detail: empty_candidate_detail(&self.state, &base),
10075                    empty: true,
10076                }
10077            }
10078            MergeMode::Local => {
10079                let on = git::current_branch(&repo).await?;
10080                if on.as_deref() != Some(base.as_str()) {
10081                    MergeOutcome {
10082                        mode,
10083                        ok: false,
10084                        detail: format!(
10085                            "{} has {} checked out, not the base branch {base}",
10086                            repo.display(),
10087                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10088                        ),
10089                        empty: false,
10090                    }
10091                } else if !git::is_clean(&repo).await? {
10092                    MergeOutcome {
10093                        mode,
10094                        ok: false,
10095                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10096                        empty: false,
10097                    }
10098                } else {
10099                    let out = match style {
10100                        MergeStyle::Merge => {
10101                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10102                        }
10103                        MergeStyle::Squash => {
10104                            git::merge_squash(&repo, &winner.branch, &message).await?
10105                        }
10106                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10107                    };
10108                    MergeOutcome {
10109                        mode,
10110                        ok: out.ok(),
10111                        detail: if out.ok() { out.stdout } else { out.stderr },
10112                        empty: false,
10113                    }
10114                }
10115            }
10116            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10117                self.state.pr_publication_pending = true;
10118                self.state.save()?;
10119                let out =
10120                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10121                self.state.pr_publication_pending = out.is_err();
10122                MergeOutcome {
10123                    mode,
10124                    ok: out.is_ok(),
10125                    detail: match out {
10126                        Ok(url) => url,
10127                        Err(e) => format!("{e:#}"),
10128                    },
10129                    empty: false,
10130                }
10131            }
10132            MergeMode::Pr => {
10133                let remote = self.state.config.merge.remote.clone();
10134                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10135                let pushed = if self.state.foreign_checkout.is_some() {
10136                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10137                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10138                } else {
10139                    git::push(&winner.worktree, &remote, &winner.branch).await?
10140                };
10141                if !pushed.ok() {
10142                    MergeOutcome {
10143                        mode,
10144                        ok: false,
10145                        detail: pushed.stderr,
10146                        empty: false,
10147                    }
10148                } else {
10149                    if self.state.foreign_checkout.is_some() {
10150                        self.state.pr_pushed_head = Some(delivery_head.clone());
10151                    }
10152                    // A retry or resume of a run whose branch already has an
10153                    // open pull request adopts it rather than failing on a
10154                    // duplicate. Only this winner branch into this base:
10155                    // `branch_for` derives the name from the run id, so a
10156                    // different run's pull request never matches.
10157                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10158                    let out = match pr_merge_plan(found) {
10159                        PrPlan::Create => {
10160                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10161                                .await
10162                        }
10163                        PrPlan::Adopt { url, title } => {
10164                            self.state
10165                                .event("merge", format!("Pr: adopted open pull request {url}"));
10166                            if self.state.explicit_github_text_selection() {
10167                                // An explicit publication selection applies the prepared
10168                                // payload; acceptance alone is not publication proof.
10169                                land::set_pr_text_verbatim(
10170                                    &winner.worktree,
10171                                    &url,
10172                                    &pr.title,
10173                                    &pr.body,
10174                                )
10175                                .await
10176                                .map(|()| url)
10177                            } else {
10178                                if title != pr.title
10179                                    && (!is_review_run(&self.state)
10180                                        || leaked
10181                                            .as_deref()
10182                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10183                                    && let Err(e) =
10184                                        if self.state.github_text.as_ref().is_some_and(|g| {
10185                                            g.resolved
10186                                                && g.title
10187                                                && g.choice == Some(GithubTextChoice::Original)
10188                                        }) {
10189                                            // The owner chose to post this title unmodified.
10190                                            land::set_pr_title_verbatim(
10191                                                &winner.worktree,
10192                                                &url,
10193                                                &pr.title,
10194                                            )
10195                                            .await
10196                                        } else {
10197                                            land::set_pr_title(
10198                                                &mut self.state,
10199                                                &winner.worktree,
10200                                                &url,
10201                                                &pr.title,
10202                                            )
10203                                            .await
10204                                        }
10205                                {
10206                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10207                                    self.state
10208                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10209                                }
10210                                Ok(url)
10211                            }
10212                        }
10213                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10214                    };
10215                    match out {
10216                        Ok(url) => MergeOutcome {
10217                            mode,
10218                            ok: true,
10219                            detail: url,
10220                            empty: false,
10221                        },
10222                        Err(e) => MergeOutcome {
10223                            mode,
10224                            ok: false,
10225                            detail: e.to_string(),
10226                            empty: false,
10227                        },
10228                    }
10229                }
10230            }
10231        };
10232
10233        self.state.status = match (mode, outcome.ok) {
10234            (MergeMode::None, _) => RunStatus::Ready,
10235            (_, true) if outcome.empty => RunStatus::Ready,
10236            (MergeMode::Pr, true) => RunStatus::Ready,
10237            (_, true) => RunStatus::Merged,
10238            (_, false) => RunStatus::Blocked,
10239        };
10240        self.state.event(
10241            "merge",
10242            format!(
10243                "{:?}: {}",
10244                mode,
10245                outcome.detail.lines().next().unwrap_or("")
10246            ),
10247        );
10248        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10249            self.state.record_github_text_publication(&outcome.detail);
10250        }
10251        self.state.merge = Some(outcome);
10252        self.state.save()?;
10253
10254        // The PR is open and the run would historically stop here, leaving the
10255        // operator to watch checks, feed review comments back to a fixer, and
10256        // merge. That was done by hand six times in one session before this
10257        // existed. Opt-in, because merging is the one irreversible thing magi
10258        // can do to a repository.
10259        if self.state.config.graph.land
10260            && mode == MergeMode::Pr
10261            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10262        {
10263            self.run_land().await?;
10264        }
10265        // `run_land` may have left `status` at `Landing` - still waiting on
10266        // CI or the owner's approval, not actually settled - so this has to
10267        // read whatever `status` ended up as here, not the `Merged` this
10268        // function set a few lines up.
10269        self.settle_questions();
10270        Ok(())
10271    }
10272
10273    /// Enter `land`.
10274    ///
10275    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10276    /// a resumed run's re-entry. `land::land` itself is what serialises the
10277    /// two git-mutating moments inside the loop — the rebase push and
10278    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10279    /// to hold a lock across the whole call, and doing so would serialise
10280    /// this run's CI wait against a *different* run's land-approval resume
10281    /// in the same repository, which is exactly the "must not wait on
10282    /// another task" property the daemon's slot-freeing exists to give.
10283    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10284        Box::pin(self.run_land_inner())
10285    }
10286
10287    async fn run_land_inner(&mut self) -> Result<()> {
10288        crate::pr_head::ensure_owner(&self.state)?;
10289        let url = self
10290            .state
10291            .pr
10292            .as_ref()
10293            .map(|pr| pr.url.clone())
10294            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10295            .unwrap_or_default();
10296        let url = url.lines().next().unwrap_or("").trim().to_owned();
10297        if !url.starts_with("http") {
10298            return Ok(());
10299        }
10300        // A land failure is not a lost run: the work is on a branch and the
10301        // pull request is open, which is exactly where a human takes over.
10302        loop {
10303            match land::land(&mut self.state, &url).await {
10304                Ok(_)
10305                    if self
10306                        .state
10307                        .merge_repairs
10308                        .last()
10309                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10310                {
10311                    if self.repair_merge_review().await? {
10312                        continue;
10313                    }
10314                }
10315                Ok(_) if self.state.resource_block.is_some() => {
10316                    return self.stop_for_resource();
10317                }
10318                Ok(pr) if self.state.parked => {
10319                    // `land` already saved the parked marker; nothing here
10320                    // overrides `status` back to a terminal value while an
10321                    // approval is still outstanding.
10322                    let _ = pr;
10323                }
10324                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10325                    self.state.status = RunStatus::Superseded;
10326                    self.state.save()?;
10327                }
10328                Ok(pr) => {
10329                    self.state.status = match pr.state {
10330                        land::PrLifecycle::Merged => RunStatus::Merged,
10331                        _ => RunStatus::Blocked,
10332                    };
10333                    // Downstream of a confirmed merge only - see
10334                    // `bump::should_release_bump`'s own doc for why this one
10335                    // check covers all three of `land`'s success paths.
10336                    // Best-effort: the run already landed, so a failure here
10337                    // (the decision call, `gh`, `cargo`) is recorded and never
10338                    // turns a landed run into a failed one.
10339                    if bump::should_release_bump(self.state.status)
10340                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10341                    {
10342                        // The event is the run's own record. Not-eligible cases
10343                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10344                        // `Err` is a bump that was tried and failed:
10345                        // `after_merge` itself raises the operator notice for
10346                        // that, whether or not a release PR exists yet.
10347                        self.state
10348                            .event("bump", format!("release bump skipped: {e:#}"));
10349                    }
10350                    // Independent of the bump, and best-effort in the same way:
10351                    // findings the merge left open become follow-up tasks.
10352                    if self.state.status == RunStatus::Merged {
10353                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10354                    }
10355                    self.state.save()?;
10356                }
10357                Err(e) => {
10358                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10359                        return Err(e);
10360                    }
10361                    self.state.status = RunStatus::Blocked;
10362                    self.state.event("land", format!("gave up: {e}"));
10363                    self.state.save()?;
10364                }
10365            }
10366            break;
10367        }
10368        Ok(())
10369    }
10370
10371    /// One repair cycle stays under the existing driver/task claim. An
10372    /// interrupted fixer is rolled back and held rather than run twice.
10373    async fn repair_merge_review(&mut self) -> Result<bool> {
10374        use crate::run::MergeRepairPhase as Phase;
10375        crate::pr_head::ensure_owner(&self.state)?;
10376        let i = self.state.merge_repairs.len() - 1;
10377        let request = self.state.merge_repairs[i].clone();
10378        if request.phase == Phase::Fixing {
10379            let restored = match self.state.winner().cloned() {
10380                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10381                None => Err(anyhow::anyhow!("repair has no winning branch")),
10382            };
10383            let why = match restored {
10384                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10385                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10386                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10387            };
10388            self.hold_merge_repair(i, why)?;
10389            return Ok(false);
10390        }
10391        // A completed repair gate is a publication checkpoint. On reentry,
10392        // reject external changes before the ordinary gate path can replace
10393        // that evidence by verifying a new head. Requested repairs still
10394        // start their own review generation below.
10395        if request.phase == Phase::Reviewing && self.state.gate_ran {
10396            let winner = self
10397                .state
10398                .winner()
10399                .context("repair has no winning branch")?;
10400            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10401            if self.state.gate_head.as_deref() != Some(head.as_str())
10402                || !git::is_clean(&winner.worktree).await?
10403            {
10404                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())?;
10405                return Ok(false);
10406            }
10407        }
10408        let failure = if i >= self.state.config.graph.land_rounds
10409            || self.state.config.graph.review_rounds == 0
10410        {
10411            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10412        } else {
10413            None
10414        };
10415        if let Some(why) = failure {
10416            self.hold_merge_repair(i, why)?;
10417            return Ok(false);
10418        }
10419        if request.phase == Phase::Requested {
10420            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10421                Ok(pr) => pr,
10422                Err(e) => {
10423                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10424                    return Ok(false);
10425                }
10426            };
10427            self.state.merge_repairs[i].phase = Phase::Fixing;
10428            self.state.land_approval = None;
10429            self.state.land_armed_head = None;
10430            self.state.save()?;
10431            // Serialize the exact records, including finding ids/details,
10432            // reconsideration reasons, final votes and verification output.
10433            let evidence = serde_json::to_string_pretty(&request)?;
10434            let reason = format!(
10435                "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}"
10436            );
10437            let budget = self.state.config.graph.land_rounds;
10438            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10439            match result {
10440                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10441                Ok(land::Fixed::Deferred) => {
10442                    // An unavailable fixer did not spend this repair request.
10443                    // Restore partial fallback work before retrying it, as for
10444                    // an interrupted repair, without closing the request.
10445                    let worktree = self
10446                        .state
10447                        .winner()
10448                        .context("repair has no winning branch")?
10449                        .worktree
10450                        .clone();
10451                    self.graft_restore(&worktree, &request.head).await?;
10452                    self.state.merge_repairs[i].phase = Phase::Requested;
10453                    self.stop_for_resource()?;
10454                    return Ok(false);
10455                }
10456                Ok(land::Fixed::Failed(why)) => {
10457                    self.hold_merge_repair(
10458                        i,
10459                        format!(
10460                            "repair failed: {why}; inspect the branch and run an explicit review"
10461                        ),
10462                    )?;
10463                    return Ok(false);
10464                }
10465                Err(e) => {
10466                    self.hold_merge_repair(
10467                        i,
10468                        format!(
10469                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10470                        ),
10471                    )?;
10472                    return Ok(false);
10473                }
10474            }
10475            // Even no change gets a real new reviewer wave. The previous
10476            // evidence remains in the request; a former clean/concluded round
10477            // cannot short-circuit the new review or gate.
10478            self.begin_merge_repair_review(i)?;
10479        }
10480        self.review_loop().await?;
10481        self.gate().await?;
10482        if self.resource_halt()? || self.state.parked {
10483            return Ok(false);
10484        }
10485        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10486            != Some(RunStatus::Gating)
10487            || !self.state.gate_allows_progress()
10488        {
10489            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10490            return Ok(false);
10491        }
10492        // Review and gate may have added commits after the initial repair.
10493        // Publish exactly their final head to the existing PR, with a lease.
10494        let winner = self
10495            .state
10496            .winner()
10497            .cloned()
10498            .context("repair has no winning branch")?;
10499        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10500        if self.state.gate_head.as_deref() != Some(after.as_str())
10501            || !git::is_clean(&winner.worktree).await?
10502        {
10503            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())?;
10504            return Ok(false);
10505        }
10506        let expected = self
10507            .state
10508            .pr_pushed_head
10509            .as_deref()
10510            .unwrap_or(&request.head)
10511            .to_owned();
10512        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10513        // Push the checked commit itself: a local ref moving after the check
10514        // must not change which commit the forge receives.
10515        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10516            return Ok(false);
10517        }
10518        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10519        let refspec = format!("{after}:refs/heads/{public}");
10520        let push = git::git_raw(
10521            &winner.worktree,
10522            &["push", &lease, &self.state.config.merge.remote, &refspec],
10523        )
10524        .await;
10525        match push {
10526            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10527            Ok(out) => {
10528                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10529                return Ok(false);
10530            }
10531            Err(e) => {
10532                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10533                return Ok(false);
10534            }
10535        }
10536        self.state.merge_repairs[i].phase = Phase::Complete;
10537        self.state.status = RunStatus::Landing;
10538        self.state.event(
10539            "repair",
10540            "new review and gate completed; fresh owner merge decision required",
10541        );
10542        self.state.save()?;
10543        Ok(true)
10544    }
10545
10546    fn merge_repair_artifacts(&self) -> PathBuf {
10547        let artifacts = agent::artifacts_dir(&self.state.dir());
10548        match self
10549            .state
10550            .merge_repairs
10551            .last()
10552            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10553        {
10554            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10555            None => artifacts,
10556        }
10557    }
10558
10559    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10560        if let Some(e2e) = self.state.head_e2e.take() {
10561            self.state
10562                .verification_history
10563                .push(crate::run::VerificationEvidence {
10564                    superseded_by: None,
10565                    archived_at: Some(Timestamp::now()),
10566                    fixes_spent: Some(self.state.gate_fixes.len()),
10567                    gate_head: None,
10568                    gate_ran: false,
10569                    gate: Vec::new(),
10570                    e2e: Some(e2e),
10571                });
10572        }
10573        self.state.reviews.clear();
10574        self.state.gate.clear();
10575        self.state.gate_ran = false;
10576        self.state.gate_head = None;
10577        self.state.gate_fixes.clear();
10578        self.state.gate_repair_e2e = None;
10579        self.state.pre_gate.clear();
10580        self.state.pre_gate_commit = None;
10581        self.state.contested_handoff = None;
10582        self.state.land_reruns = None;
10583        self.state.land_approval = None;
10584        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10585        self.state.status = RunStatus::Reviewing;
10586        self.state.save()
10587    }
10588
10589    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10590        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10591        self.state.merge_repairs[index].failure = Some(why.clone());
10592        self.state.status = RunStatus::Blocked;
10593        self.state.event("repair", why);
10594        self.state.save()
10595    }
10596
10597    // -------------------------------------------------------------- helpers
10598
10599    /// Fetch or create a seat, keeping its conversation across nodes.
10600    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10601        if let Some(existing) = self.state.seats.get(key)
10602            && existing.agent == agent
10603        {
10604            return existing.clone();
10605        }
10606        // A seat that changes agent mints its session id from the agent too,
10607        // like a handover: the old agent's uuid is already taken by the CLI.
10608        let fresh = if self.state.seats.contains_key(key) {
10609            handover_seat(key, agent, self.state.next_seat_seed())
10610        } else {
10611            SeatState::new(key, agent, self.state.seed)
10612        };
10613        self.state.seats.insert(key.to_owned(), fresh.clone());
10614        fresh
10615    }
10616
10617    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10618    /// seat to another roster agent, in which case that agent. Nodes that
10619    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10620    /// reconsideration) must keep talking to whoever answered it, not slip
10621    /// back to the agent that failed it.
10622    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10623        match self.state.seats.get(key) {
10624            Some(s) if s.agent != spec.id => {
10625                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10626            }
10627            _ => spec,
10628        }
10629    }
10630
10631    /// A candidate rendered for judging, with the leak policy applied.
10632    fn view(&self, c: &Candidate) -> CandidateView {
10633        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10634            .unwrap_or_default();
10635        let (patch, _) = blind::sanitize_patch(
10636            &format!("candidate {} patch", c.label),
10637            &raw,
10638            &self.state.config.blind,
10639        );
10640        CandidateView {
10641            label: c.label,
10642            branch: c.branch.clone(),
10643            summary: c.summary.clone(),
10644            stat: c.stat.clone(),
10645            patch,
10646        }
10647    }
10648
10649    /// The full candidate set as prompt text, for seats with no live session.
10650    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10651        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10652        prompt::judge(
10653            "(see above)",
10654            &views,
10655            self.roles.judges.len(),
10656            base_short,
10657            "en",
10658        )
10659    }
10660
10661    /// The final-vote prompt with everything a seat that has no session of its
10662    /// own needs: the candidates, the seat's own ranking and reasons, and the
10663    /// anonymised deliberation it took part in (only when there was one, so a
10664    /// handed-over seat never sees more than the seat it replaces did). The
10665    /// `Final vote` heading stays first.
10666    fn vote_prompt_full(
10667        &self,
10668        j: usize,
10669        labels: &[char],
10670        language: &str,
10671        candidates: &[Candidate],
10672        base_short: &str,
10673    ) -> String {
10674        let mut text = format!(
10675            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10676            prompt::final_vote(labels, language),
10677            self.state.instruction,
10678            self.candidate_block(candidates, base_short)
10679        );
10680        if let Some(own) = self
10681            .state
10682            .judgements
10683            .get(j)
10684            .filter(|r| !r.ranking.is_empty())
10685        {
10686            let reasons = own
10687                .reasons
10688                .iter()
10689                .map(|(k, v)| format!("- {k}: {v}"))
10690                .collect::<Vec<_>>()
10691                .join("\n");
10692            text.push_str(&format!(
10693                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10694                own.ranking.iter().collect::<String>(),
10695                if reasons.is_empty() {
10696                    ""
10697                } else {
10698                    ", because:\n"
10699                }
10700            ));
10701        }
10702        if !self.state.deliberation.is_empty() {
10703            text.push_str("\n# What was argued before this vote\n");
10704            for t in self.transcript(&[], j) {
10705                text.push_str(&format!(
10706                    "\n## {}{}\n\n{}\n",
10707                    t.who,
10708                    if t.is_self { " (you)" } else { "" },
10709                    t.body.trim()
10710                ));
10711            }
10712        }
10713        text
10714    }
10715
10716    /// Anonymised transcript for judge `self_idx`.
10717    ///
10718    /// The initial rankings are always the opening statements. Seeding them
10719    /// only when no turn had been taken yet meant every judge after the first
10720    /// argued against a single voice instead of against the actual split — the
10721    /// disagreement is the information, so it is always on the table.
10722    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10723        let mut turns = Vec::new();
10724        for j in &self.state.judgements {
10725            if j.ranking.is_empty() {
10726                continue;
10727            }
10728            let reasons = j
10729                .reasons
10730                .iter()
10731                .map(|(k, v)| format!("- {k}: {v}"))
10732                .collect::<Vec<_>>()
10733                .join("\n");
10734            turns.push(Turn {
10735                who: format!("Judge {} (opening ranking)", j.judge),
10736                is_self: j.judge == self_idx + 1,
10737                body: format!(
10738                    "Ranked {}{}{reasons}",
10739                    j.ranking.iter().collect::<String>(),
10740                    if reasons.is_empty() {
10741                        ""
10742                    } else {
10743                        ", because:\n"
10744                    }
10745                ),
10746            });
10747        }
10748        for t in self
10749            .state
10750            .deliberation
10751            .iter()
10752            .flat_map(|r| r.turns.iter())
10753            .chain(current)
10754        {
10755            turns.push(Turn {
10756                who: format!("Judge {}", t.judge),
10757                is_self: t.judge == self_idx + 1,
10758                body: t.body.clone(),
10759            });
10760        }
10761        turns
10762    }
10763}
10764
10765/// Does this seat still hold the context a follow-up prompt would rely on?
10766fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10767    agent::has_session(spec.kind, seat, sessions)
10768}
10769
10770/// The next entry in `roster` after `start`, never wrapping back to the
10771/// front, whose id is not in `tried` yet.
10772///
10773/// Starts one past `start` rather than at the front of `roster`: `start` is
10774/// the seat's own original position, and a seat whose candidate slot already
10775/// sits on the roster's second entry must fall through to the third next, not
10776/// restart at the first — which is very likely a different candidate's own
10777/// agent already. Never wraps back past `start`, for the same reason: an
10778/// entry earlier in the roster than the seat's own position is almost
10779/// certainly some *other* candidate slot's own agent, and once the tail of
10780/// the roster is exhausted there are no more untried agents for *this* seat
10781/// to fall through to — the caller's fallback chain ends there, exactly as
10782/// "no further untried agents remain in the list for that seat" asks for.
10783///
10784/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10785/// the same id twice (an operator's `roles.implementers` typo, or a
10786/// `[[agents]]` list reused across roles) must not let
10787/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10788/// over `roster` either finds an untried id or runs out, so this always
10789/// terminates regardless of duplicates.
10790fn next_untried_in_roster<'a>(
10791    roster: &'a [AgentSpec],
10792    start: usize,
10793    tried: &BTreeSet<String>,
10794) -> Option<&'a AgentSpec> {
10795    roster
10796        .get(start + 1..)?
10797        .iter()
10798        .find(|s| !tried.contains(&s.id))
10799}
10800
10801/// The successor for a seat, shared by all four seat kinds (implement, judge,
10802/// review, advise). `others` holds the ids that *currently* occupy the other
10803/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10804/// sees them), so roster entries beyond the seat count act as spares: a failed
10805/// seat goes to an agent no other seat holds whenever the roster permits.
10806///
10807/// `carried` is `Some` only for the review loop's carried failure history.
10808/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10809/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10810/// whole roster: untried and not another seat's occupant; (3) the plain walk
10811/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10812/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10813/// a better outcome than an empty seat, and it keeps the answer to "is there
10814/// a successor at all" exactly what it was before occupants were considered,
10815/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10816/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10817/// carried failure is a cheaper bet than doubling an agent on the panel, and
10818/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10819/// the same round are handled one at a time, so a seat later in the batch
10820/// sees an earlier one's new occupant but not yet its own freed agent.
10821fn pick_successor<'a>(
10822    roster: &'a [AgentSpec],
10823    start: usize,
10824    tried: &BTreeSet<String>,
10825    carried: Option<&BTreeSet<String>>,
10826    others: &BTreeSet<String>,
10827) -> Option<&'a AgentSpec> {
10828    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10829    roster
10830        .get(start + 1..)
10831        .and_then(|tail| {
10832            tail.iter()
10833                .filter(free)
10834                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10835        })
10836        .or_else(|| {
10837            carried
10838                .is_some()
10839                .then(|| roster.iter().find(free))
10840                .flatten()
10841        })
10842        .or_else(|| match carried {
10843            Some(c) => next_for_seat(roster, start, tried, c),
10844            None => next_untried_in_roster(roster, start, tried),
10845        })
10846}
10847
10848/// The next agent for a seat that carries its failure history across rounds
10849/// (the review loop). `round_tried` is this round's own bound and starts
10850/// empty every round; `carried_failed` only decides priority.
10851///
10852/// First: an id walking forward from `start`, never wrapping, that is neither
10853/// tried this round nor failed in an earlier one. Only when that is exhausted
10854/// does it rescue: the first roster id (in roster order, so this one *does*
10855/// look before `start`) not yet tried this round, which is by then a carried
10856/// failure. Each id is rescued at most once per round, so it cannot loop.
10857fn next_for_seat<'a>(
10858    roster: &'a [AgentSpec],
10859    start: usize,
10860    round_tried: &BTreeSet<String>,
10861    carried_failed: &BTreeSet<String>,
10862) -> Option<&'a AgentSpec> {
10863    roster
10864        .get(start + 1..)?
10865        .iter()
10866        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10867        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10868}
10869
10870/// Where a reviewer seat starts a round: the agent that last answered it when
10871/// it is still on the roster and not marked failed, else the spec's own agent
10872/// unless it failed, else the next roster agent that has not failed, else the
10873/// spec's own agent again (the whole roster failed). Ids no longer on the
10874/// roster are ignored. An empty roster has no handover, so the spec stands.
10875fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10876    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10877        return spec;
10878    };
10879    let ok = |id: &str| !h.failed.contains(id);
10880    if let Some(last) = h.last_ok.as_deref()
10881        && ok(last)
10882        && let Some(s) = roster.iter().find(|s| s.id == last)
10883    {
10884        return s.clone();
10885    }
10886    if ok(&spec.id) {
10887        return spec;
10888    }
10889    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10890    roster
10891        .get(from + 1..)
10892        .into_iter()
10893        .flatten()
10894        .chain(roster.iter())
10895        .find(|s| ok(&s.id))
10896        .cloned()
10897        .unwrap_or(spec)
10898}
10899
10900/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10901/// seed so a CLI that mints its session id up front (`--session-id`) never
10902/// reuses the uuid the previous agent already opened under the same seat key.
10903pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10904    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10905}
10906
10907/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10908/// so the classifier below and the code that builds the message cannot drift.
10909const TIMED_OUT: &str = "timed out";
10910
10911impl FailClass {
10912    /// `None` for an answer; otherwise how the turn failed.
10913    fn of(out: &AgentOutcome) -> Option<Self> {
10914        match out {
10915            AgentOutcome::Ok(_) => None,
10916            AgentOutcome::Quota(_) => Some(Self::Quota),
10917            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10918            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10919            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10920            // Not a failure of the agent. Callers check for it first; `None`
10921            // here means "no class to hand over on".
10922            AgentOutcome::ResourceBlocked(_) => None,
10923        }
10924    }
10925
10926    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10927    fn stem_word(&self) -> &'static str {
10928        match self {
10929            Self::Quota => "quota",
10930            _ => "handover",
10931        }
10932    }
10933}
10934
10935/// The message's first line with its variable parts removed — digit runs and
10936/// path-like tokens — so "exit code 2" and "exit code 7" read
10937/// as one kind of failure.
10938fn failure_signature(msg: &str) -> String {
10939    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10940    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10941    // the historical machine key while the process diagnosis uses readable prose.
10942    if let Some(code) = line
10943        .strip_prefix("process exited with no usable output (exit code ")
10944        .and_then(|s| s.strip_suffix(')'))
10945        .and_then(|s| s.parse::<i32>().ok())
10946    {
10947        line = format!("exited with some({code}) and no usable output");
10948    } else if matches!(
10949        line.as_str(),
10950        "process exited with no usable output (no exit code reported)"
10951            | "process exited with no usable output (exit code unavailable)"
10952    ) {
10953        line = "exited with none and no usable output".to_owned();
10954    }
10955    let mut out = Vec::new();
10956    for word in line.split_whitespace() {
10957        if word.contains('/') || word.contains('\\') {
10958            out.push("<path>".to_owned());
10959            continue;
10960        }
10961        let mut w = String::new();
10962        let mut in_digits = false;
10963        for c in word.chars() {
10964            if c.is_ascii_digit() {
10965                if !in_digits {
10966                    w.push('#');
10967                }
10968                in_digits = true;
10969            } else {
10970                in_digits = false;
10971                w.push(c);
10972            }
10973        }
10974        out.push(w);
10975    }
10976    out.join(" ").chars().take(120).collect()
10977}
10978
10979/// Whether a seat that just failed with `cur` may go to the next roster agent.
10980/// A quota or a timeout always may. Any other failure may not when the agent
10981/// before it failed the same way: an error the prompt causes would otherwise
10982/// walk the whole roster. `prev` is the class of the immediately preceding
10983/// agent's failure, so a quota or timeout in between breaks the run of
10984/// identical failures by itself.
10985fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10986    match cur {
10987        FailClass::Quota | FailClass::Timeout => true,
10988        FailClass::Other(_) => prev != Some(cur),
10989    }
10990}
10991
10992/// A short human reason for a failed outcome, for the handover record.
10993fn fail_reason(out: &AgentOutcome) -> String {
10994    match out {
10995        AgentOutcome::Ok(_) => String::new(),
10996        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10997        AgentOutcome::Dropped(o) => format!(
10998            "the CLI dropped the stream ({})",
10999            o.dropped
11000                .as_ref()
11001                .map(|d| d.why.as_str())
11002                .unwrap_or("it ended without delivering its answer")
11003        ),
11004        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11005            e.lines().next().unwrap_or("").chars().take(160).collect()
11006        }
11007    }
11008}
11009
11010/// Note one handover in the run: the structured record and, in the timeline,
11011/// the sentence a person reads. A quota keeps the wording it always had.
11012pub(crate) fn record_handover(
11013    state: &mut RunState,
11014    node: &str,
11015    seat: &str,
11016    from: &str,
11017    to: &str,
11018    class: &FailClass,
11019    reason: &str,
11020) {
11021    let message = if *class == FailClass::Quota {
11022        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11023    } else {
11024        format!("{seat}: handed over {from} -> {to} ({reason})")
11025    };
11026    state.event(node, message);
11027    state.handovers.push(Handover {
11028        at: Timestamp::now(),
11029        node: node.to_owned(),
11030        seat: seat.to_owned(),
11031        from: from.to_owned(),
11032        to: to.to_owned(),
11033        reason: reason.to_owned(),
11034    });
11035}
11036
11037/// Did this reply report running a command whose own CLI never confirmed an
11038/// exit status?
11039///
11040/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11041/// command *finished* (see that type's own doc), so this can only be `true`
11042/// for a command whose completion event carried no readable exit code — not
11043/// for one that simply is not mentioned at all. That is the one signal this
11044/// crate can read, from the same record `state.jobs` renders, about a reply
11045/// standing next to work its own CLI cannot vouch for finishing; it is
11046/// deliberately not a check on the exit code's *value* (a fixer legitimately
11047/// runs a command that fails mid-iteration before it succeeds) and not a
11048/// guess at a command still running in the background (which emits no event
11049/// at all, and so leaves no evidence here to find).
11050fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11051    commands.iter().any(|c| c.exit_code.is_none())
11052}
11053
11054/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11055/// adoption guard.
11056#[derive(Debug, Clone, PartialEq, Eq)]
11057enum NoopClaimVerdict {
11058    /// Reply did not open with `NO CHANGE NEEDED:`.
11059    Absent,
11060    /// Structured evidence passed schema, CLI command, and repository checks.
11061    Accepted,
11062    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11063    /// concrete reason.
11064    Rejected(String),
11065}
11066
11067fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11068    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11069    cmd.description.trim() == check.method.trim()
11070}
11071
11072/// Checks cited by `requirements` plus the final check, deduplicated in order.
11073fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11074    let mut out = report.cited_checks();
11075    if let Some(last) = report.checks.last()
11076        && !out
11077            .iter()
11078            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11079    {
11080        out.push(last);
11081    }
11082    out
11083}
11084
11085/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11086/// when the backend reported commands. Empty `commands` is allowed because not
11087/// every backend emits structured command events.
11088fn check_command_evidence(
11089    report: &verdict::VerifiedNoopReport,
11090    commands: &[agent::CommandEvidence],
11091) -> std::result::Result<(), String> {
11092    if commands.is_empty() {
11093        return Ok(());
11094    }
11095    for check in checks_to_cross_verify(report) {
11096        let matching: Vec<&agent::CommandEvidence> = commands
11097            .iter()
11098            .filter(|cmd| command_matches_check(cmd, check))
11099            .collect();
11100        match check.kind {
11101            verdict::NoopEvidenceKind::Command
11102            | verdict::NoopEvidenceKind::Test
11103            | verdict::NoopEvidenceKind::Path => {
11104                let Some(last_cmd) = matching.last() else {
11105                    return Err(format!(
11106                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11107                         but no matching command was recorded by the CLI",
11108                        check.id.trim(),
11109                        check.kind,
11110                        check.target.trim()
11111                    ));
11112                };
11113                if last_cmd.exit_code != Some(0) {
11114                    return Err(format!(
11115                        "contradictory command evidence: check `{}` claims `{}` passed, \
11116                         but its last recorded CLI command (`{}`) exited with {}",
11117                        check.id.trim(),
11118                        check.target.trim(),
11119                        last_cmd.description.trim(),
11120                        crate::notices::exit_status(last_cmd.exit_code)
11121                    ));
11122                }
11123                if check.kind == verdict::NoopEvidenceKind::Test
11124                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11125                {
11126                    return Err(format!(
11127                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11128                         but its last recorded CLI output reports failure or no passing tests",
11129                        check.id.trim(),
11130                        check.target.trim()
11131                    ));
11132                }
11133            }
11134            verdict::NoopEvidenceKind::Commit => {
11135                if let Some(last_cmd) = matching.last()
11136                    && last_cmd.exit_code != Some(0)
11137                {
11138                    return Err(format!(
11139                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11140                         but its last recorded CLI command (`{}`) exited with {}",
11141                        check.id.trim(),
11142                        check.target.trim(),
11143                        last_cmd.description.trim(),
11144                        crate::notices::exit_status(last_cmd.exit_code)
11145                    ));
11146                }
11147            }
11148        }
11149    }
11150    Ok(())
11151}
11152
11153/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11154/// exit, confirmed commands, strict structured JSON validation, and
11155/// `CommandEvidence` consistency.
11156fn evaluate_noop_claim(
11157    usable: bool,
11158    commands: &[agent::CommandEvidence],
11159    text: &str,
11160) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11161    if !text
11162        .trim_start()
11163        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11164    {
11165        return Ok(None);
11166    }
11167    if !usable {
11168        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11169    }
11170    if has_unconfirmed_command(commands) {
11171        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11172    }
11173    let Some(parsed) = verdict::parse_verified_noop(text) else {
11174        return Ok(None);
11175    };
11176    let report = parsed?;
11177    check_command_evidence(&report, commands)?;
11178    Ok(Some(report))
11179}
11180
11181/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11182/// structured no-op report against the candidate's real Git history and
11183/// worktree. Existence alone never satisfies a requirement (the report still
11184/// had to carry concrete passing checks), while a missing commit/path or a
11185/// commit not on `base_commit` disqualifies the claim.
11186async fn verify_noop_repo_evidence(
11187    report: &verdict::VerifiedNoopReport,
11188    worktree: &Path,
11189    base_commit: &str,
11190) -> std::result::Result<(), String> {
11191    let wt_canon = std::fs::canonicalize(worktree).ok();
11192    for check in checks_to_cross_verify(report) {
11193        match check.kind {
11194            verdict::NoopEvidenceKind::Commit => {
11195                let target = check.target.trim();
11196                let Some(sha) = git::commit_of(worktree, target).await else {
11197                    return Err(format!(
11198                        "check `{}` cites commit `{target}`, which does not exist in git history",
11199                        check.id.trim()
11200                    ));
11201                };
11202                if !git::is_ancestor(worktree, &sha, base_commit).await {
11203                    return Err(format!(
11204                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11205                        check.id.trim(),
11206                        short(base_commit)
11207                    ));
11208                }
11209            }
11210            verdict::NoopEvidenceKind::Path => {
11211                let target = check.target.trim();
11212                let rel = verdict::strip_path_locator(target);
11213                let full = worktree.join(rel);
11214                if !full.exists() {
11215                    return Err(format!(
11216                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11217                        check.id.trim()
11218                    ));
11219                }
11220                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11221                    && !path_canon.starts_with(wt_canon)
11222                {
11223                    return Err(format!(
11224                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11225                        check.id.trim()
11226                    ));
11227                }
11228            }
11229            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11230        }
11231    }
11232    Ok(())
11233}
11234
11235/// Full adoption guard for an implementer reply, including real Git history and
11236/// worktree path verification.
11237async fn verified_noop_claim_in_worktree(
11238    usable: bool,
11239    commands: &[agent::CommandEvidence],
11240    text: &str,
11241    worktree: &Path,
11242    base_commit: &str,
11243) -> NoopClaimVerdict {
11244    let report = match evaluate_noop_claim(usable, commands, text) {
11245        Ok(Some(r)) => r,
11246        Ok(None) => return NoopClaimVerdict::Absent,
11247        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11248    };
11249    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11250        return NoopClaimVerdict::Rejected(reason);
11251    }
11252    NoopClaimVerdict::Accepted
11253}
11254
11255/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11256/// trusted as a verified no-op — the adoption guard's pure text-and-command
11257/// half (repository history/path verification runs in
11258/// [`verified_noop_claim_in_worktree`]).
11259///
11260/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11261/// timed out): a marker only earns the benefit of the doubt from a turn the
11262/// CLI itself vouches for finishing properly, the same house style
11263/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11264/// *fix* report to for `commands`. A candidate that timed out, exited
11265/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11266/// or failed structured validation returns `None`.
11267#[cfg(test)]
11268fn verified_noop_claim(
11269    usable: bool,
11270    commands: &[agent::CommandEvidence],
11271    text: &str,
11272) -> Option<String> {
11273    evaluate_noop_claim(usable, commands, text)
11274        .ok()
11275        .flatten()
11276        .map(|report| report.summary_text())
11277}
11278
11279fn short(commit: &str) -> String {
11280    commit.chars().take(7).collect()
11281}
11282
11283fn make_executable(path: &Path) -> Result<()> {
11284    #[cfg(unix)]
11285    {
11286        use std::os::unix::fs::PermissionsExt as _;
11287        let mut perms = std::fs::metadata(path)?.permissions();
11288        perms.set_mode(0o755);
11289        std::fs::set_permissions(path, perms)?;
11290    }
11291    #[cfg(not(unix))]
11292    {
11293        let _ = path;
11294    }
11295    Ok(())
11296}
11297
11298/// What every seat in one batch shares: where the answers are attributed, the
11299/// prompt overlay they inherit, and the build cache they are told to use.
11300///
11301/// A struct rather than four more parameters: `wave` also needs the run's
11302/// state (to record who is answering right now) and the attempt number, and
11303/// eight positional arguments is both unreadable and a clippy error.
11304struct WaveCtx<'a> {
11305    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11306    /// paid for it.
11307    run: &'a str,
11308    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11309    node: &'a str,
11310    prompts: &'a Prompts,
11311    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11312    cache: Option<&'a Path>,
11313    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11314    /// `JobRecord::round`. `None` for every other node.
11315    round: Option<usize>,
11316    /// Carry each seat's failed-agent history across waves (the review loop
11317    /// only): start-of-round priority and handover choice read
11318    /// [`RunState::seat_history`], and every answer or failure writes it.
11319    carry_seats: bool,
11320    /// The run's park / interrupt requests, so a wait for a shared resource
11321    /// can be abandoned the moment the operator asks to park.
11322    pauses: Option<(&'a Pause, &'a Pause)>,
11323}
11324
11325/// Shared scheduling policy for operations and spawned seat invocations.
11326fn repository_wait(
11327    state: &RunState,
11328    pauses: Option<(&Pause, &Pause)>,
11329) -> crate::repo_lock::WaitPolicy {
11330    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11331    let inherited = crate::repo_lock::WaitPolicy::current();
11332    crate::repo_lock::WaitPolicy::new(
11333        Duration::from_secs(state.config.graph.timeout_resource_wait),
11334        move || {
11335            inherited.cancelled()
11336                || pauses
11337                    .as_ref()
11338                    .is_some_and(|(a, b)| a.parked() || b.parked())
11339        },
11340    )
11341}
11342
11343fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11344    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11345        state.event("resource", timeout.0.description());
11346        state.resource_block = Some(timeout.0.clone());
11347        return;
11348    }
11349    if error.is::<crate::repo_lock::ResourceBlocked>() {
11350        state.resource_block = Some(crate::run::ResourceBlock {
11351            cause: crate::run::ResourceBlockCause::Other,
11352            node: "repository".into(),
11353            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11354                "disk admission"
11355            } else if error.to_string().contains("disk pressure") {
11356                "disk pressure"
11357            } else if error.to_string().contains("disk admission") {
11358                "disk admission"
11359            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11360                "incremental cache admission"
11361            } else {
11362                "repository coordination"
11363            }
11364            .into(),
11365            detail: format!("{error:#}"),
11366            at: Timestamp::now(),
11367        });
11368        state.event("resource", error.to_string());
11369    }
11370}
11371
11372async fn coordinate_operation(
11373    state: &mut RunState,
11374    cwd: &Path,
11375    wait: &crate::repo_lock::WaitPolicy,
11376) -> Result<Option<crate::repo_lock::SeatLease>> {
11377    let result =
11378        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11379            .await;
11380    if let Err(e) = &result {
11381        record_repository_block(state, e);
11382    }
11383    result
11384}
11385
11386/// Run one job, honouring the parallelism budget.
11387async fn run_one(
11388    job: SeatJob,
11389    sem: Arc<Semaphore>,
11390    ctx: &WaveCtx<'_>,
11391    state: &mut RunState,
11392    attempt: usize,
11393) -> (SeatState, AgentOutcome) {
11394    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11395        .await
11396        .pop()
11397        .expect("one job in, one result out");
11398    (seat, out)
11399}
11400
11401/// Run every job concurrently, capped by the semaphore, preserving order.
11402///
11403/// Every seat in the batch is recorded into [`RunState::active`] before the
11404/// wave starts and cleared as each answer lands, so the run's own record says
11405/// who is still being waited on rather than only who finished.
11406async fn wave(
11407    jobs: Vec<SeatJob>,
11408    sem: Arc<Semaphore>,
11409    ctx: &WaveCtx<'_>,
11410    state: &mut RunState,
11411    attempt: usize,
11412) -> Vec<(usize, SeatState, AgentOutcome)> {
11413    let WaveCtx {
11414        run,
11415        node,
11416        prompts,
11417        cache,
11418        round,
11419        carry_seats: _,
11420        pauses,
11421    } = *ctx;
11422    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11423    for job in &jobs {
11424        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11425    }
11426    if let Err(e) = state.save() {
11427        // A failed persist of "who is answering right now" must not abort the
11428        // wave: the seats are already being asked, and the alternative is
11429        // losing the answers to save a status line nobody may even be
11430        // watching.
11431        tracing::warn!("could not persist in-progress seats: {e:#}");
11432    }
11433    // Shared-mode waves keep their existing single lease. Isolated writers
11434    // acquire their own checkout's target at seat admission.
11435    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11436    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11437    // never borrowed from a job's agent budget (and never charged to it either,
11438    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11439    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11440    let cache_guard = if let Some(cache_dir) = cache {
11441        if jobs_had_a_writer {
11442            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11443            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11444            match acquire_cache_lease(
11445                state,
11446                cache_dir,
11447                &owner,
11448                resource_limit,
11449                node,
11450                node,
11451                &cancel,
11452            )
11453            .await
11454            {
11455                Ok(Some(g)) => Some(g),
11456                // Parking: leave without spawning anything. The run parks at
11457                // the next boundary and the seats are asked afresh on resume.
11458                Ok(None) => {
11459                    if let Some(block) = &mut state.resource_block {
11460                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11461                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11462                        };
11463                    }
11464                    return block_wave(
11465                        jobs,
11466                        state,
11467                        node,
11468                        attempt,
11469                        "parked while waiting for the shared build cache",
11470                    );
11471                }
11472                // An unreadable lease is not contention: keep the old
11473                // fallback (no shared cache for this wave's seats).
11474                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11475                Err(e) => {
11476                    // Writing seats may not build into a cache this run does
11477                    // not hold, and an agent that cannot be given one is not
11478                    // asked at all: the run stops resumably instead.
11479                    let why = format!("{e:#}");
11480                    state.event(
11481                        "resource",
11482                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11483                    );
11484                    return block_wave(jobs, state, node, attempt, &why);
11485                }
11486            }
11487        } else {
11488            None
11489        }
11490    } else {
11491        None
11492    };
11493    // Every job keeps its whole budget: the wait above was not the agent's.
11494    // Restart the seats' clocks so "started" means "being spawned now".
11495    state.seats_spawning(node, attempt);
11496    if let Err(e) = state.save() {
11497        tracing::warn!("could not persist the start of a wave: {e:#}");
11498    }
11499    // Queueing behind this wave's own seats for a parallelism slot is normal
11500    // (each of them is bounded by its own agent timeout); only a wait beyond
11501    // all of them plus the resource limit means the slots never came back.
11502    let slot_limit = resource_limit
11503        + jobs
11504            .iter()
11505            .map(|j| j.timeout)
11506            .max()
11507            .unwrap_or_default()
11508            .saturating_mul(jobs.len() as u32);
11509    let mut set = tokio::task::JoinSet::new();
11510    // Seats announce themselves here the moment they hold a parallelism
11511    // permit, i.e. just before their CLI is spawned.
11512    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11513    let overlay = prompts.overlay(node);
11514    let repository_wait = repository_wait(state, pauses);
11515    for (i, mut job) in jobs.into_iter().enumerate() {
11516        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11517        if cache.is_some() {
11518            job.prompt.push('\n');
11519            job.prompt
11520                .push_str(&prompt::build_cache_note(node, job.allow_write));
11521        }
11522        let sem = Arc::clone(&sem);
11523        let run = run.to_owned();
11524        let node = node.to_owned();
11525        // Only implementers were told about the task's attachments, so only
11526        // their seats get the directory widened for reading.
11527        let attachments = if node == "implement" {
11528            state.attachments.clone()
11529        } else {
11530            Vec::new()
11531        };
11532        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11533        // `prompt::build_cache_note`'s doc for why setting it anyway is
11534        // exactly how a sandboxed reviewer's write refusal got reported as a
11535        // defect in the patch, not a property of its own seat. And a
11536        // write-allowed one is handed it only when the lease above was
11537        // actually acquired: a wave that could not get it (`cache_guard` is
11538        // `None`, see its own comment) must not send seats to build into a
11539        // directory this run does not hold - that is the exact concurrent,
11540        // unmanaged-write race this module exists to prevent, not something
11541        // "proceeding anyway" is allowed to reintroduce.
11542        let cache = cache
11543            .filter(|_| job.allow_write && cache_guard.is_some())
11544            .map(Path::to_path_buf);
11545        let spawned_tx = spawned_tx.clone();
11546        let repository_wait = repository_wait.clone();
11547        let coordination = state.config.coordination.clone();
11548        let fetched_base = state.fetched_base.clone();
11549        set.spawn(async move {
11550            // A wait for a parallelism slot is scheduling, not the agent: it
11551            // is bounded by its own limit and ends as a resource block, never
11552            // as a timeout of the agent that was not started.
11553            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11554                Ok(p) => p,
11555                Err(_) => {
11556                    return (
11557                        i,
11558                        job.seat,
11559                        AgentOutcome::ResourceBlocked(format!(
11560                            "no parallel slot became free within {}s",
11561                            slot_limit.as_secs()
11562                        )),
11563                        None,
11564                        false,
11565                    );
11566                }
11567            };
11568            spawned_tx.send(job.seat.key.clone()).ok();
11569            let mut seat = job.seat;
11570            let out = repository_wait
11571                .scope(agent::invoke(
11572                    &job.spec,
11573                    &mut seat,
11574                    &Invocation {
11575                        coordination: coordination.as_ref(),
11576                        fetched_base: fetched_base.as_ref(),
11577                        cwd: &job.cwd,
11578                        prompt: &job.prompt,
11579                        timeout: job.timeout,
11580                        allow_write: job.allow_write,
11581                        sessions: job.sessions,
11582                        artifacts: &job.artifacts,
11583                        stem: &job.stem,
11584                        run: &run,
11585                        node: &node,
11586                        cache_dir: cache.as_deref(),
11587                        attachments: &attachments,
11588                        writable: &[],
11589                    },
11590                ))
11591                .await;
11592            let cache_block = out
11593                .as_ref()
11594                .err()
11595                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11596                .map(|timeout| timeout.0.clone());
11597            let interrupted = out
11598                .as_ref()
11599                .err()
11600                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11601            let out = match out {
11602                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11603                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11604                // Billed work the CLI failed to hand over is not an ordinary
11605                // failure, but its text is the CLI's raw error JSON, not an
11606                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11607                // read it as one by forgetting to check. `usable()` is always
11608                // false here (dropped implies an empty response), so this has
11609                // to be checked before the catch-all `Failed` below or the
11610                // one shape this exists for is lost with the rest.
11611                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11612                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11613                Ok(o) => AgentOutcome::Failed(format!(
11614                    "process exited with no usable output ({})",
11615                    crate::notices::exit_status(o.exit_code)
11616                )),
11617                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11618                    AgentOutcome::ResourceBlocked(e.to_string())
11619                }
11620                Err(e) => AgentOutcome::Failed(e.to_string()),
11621            };
11622            (i, seat, out, cache_block, interrupted)
11623        });
11624    }
11625    drop(spawned_tx);
11626    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11627    loop {
11628        let joined = tokio::select! {
11629            Some(key) = spawned_rx.recv() => {
11630                // The clock of this seat starts now, not when it queued.
11631                state.seat_spawned(&key);
11632                if let Err(e) = state.save() {
11633                    tracing::warn!("could not persist a seat's start: {e:#}");
11634                }
11635                continue;
11636            }
11637            joined = set.join_next() => joined,
11638        };
11639        let Some(joined) = joined else {
11640            break;
11641        };
11642        let (i, seat, out, cache_block, interrupted) = match joined {
11643            Ok(v) => v,
11644            // No seat to clear: a panicked task never reported which one it
11645            // was. The defensive sweep below this loop is what stops that
11646            // seat's `active` entry from surviving forever.
11647            Err(e) => {
11648                tracing::error!("agent task panicked: {e}");
11649                continue;
11650            }
11651        };
11652        state.seat_finished(&seat.key);
11653        if interrupted
11654            && node == "implement"
11655            && let Some(label) = state
11656                .candidates
11657                .iter()
11658                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11659                .map(|candidate| candidate.label)
11660        {
11661            state.candidate_preservation.insert(
11662                label,
11663                "interrupted implementation awaiting persistence".into(),
11664            );
11665            state.interrupted_implementations.insert(label);
11666        }
11667        if let Some(block) = cache_block
11668            && state.resource_block.is_none()
11669        {
11670            state.event("resource", block.description());
11671            state.resource_block = Some(block);
11672        }
11673        if let AgentOutcome::ResourceBlocked(why) = &out
11674            && state.resource_block.is_none()
11675        {
11676            state.resource_block = Some(crate::run::ResourceBlock {
11677                cause: crate::run::ResourceBlockCause::Other,
11678                node: node.to_owned(),
11679                kind: if why.contains("disk pressure") {
11680                    "disk pressure"
11681                } else if why.contains("disk admission") {
11682                    "disk admission"
11683                } else if why.contains(crate::incremental::BLOCKED) {
11684                    "incremental cache admission"
11685                } else if why.contains(crate::build_target::KIND) {
11686                    crate::build_target::KIND
11687                } else if why.contains("repository coordination") {
11688                    "repository coordination"
11689                } else {
11690                    "parallel slot"
11691                }
11692                .to_owned(),
11693                detail: why.clone(),
11694                at: Timestamp::now(),
11695            });
11696            let activity = if interrupted {
11697                "agent execution interrupted"
11698            } else {
11699                "no agent was started"
11700            };
11701            state.event("resource", format!("{node}: {activity} - {why}"));
11702        }
11703        record_jobs(state, node, round, &seat.key, &out);
11704        if let Err(e) = state.save() {
11705            tracing::warn!("could not persist a seat's completion: {e:#}");
11706        }
11707        if collected.len() <= i {
11708            collected.resize_with(i + 1, || None);
11709        }
11710        collected[i] = Some((i, seat, out));
11711    }
11712    // Belt-and-braces for the panic branch above: every seat this exact batch
11713    // started shares this `(node, attempt)` pair, and every seat that finished
11714    // normally already cleared itself, so anything left tagged with it here
11715    // can only be a panicked task's leftover. Cleared unconditionally rather
11716    // than left to read as still answering forever.
11717    if state
11718        .active
11719        .values()
11720        .any(|a| a.node == node && a.attempt == attempt)
11721    {
11722        state
11723            .active
11724            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11725        if let Err(e) = state.save() {
11726            tracing::warn!("could not persist the end of a wave: {e:#}");
11727        }
11728    }
11729    // Whether or not the lease above was actually held, several worktrees
11730    // may just have built into the cache with nothing here able to name one
11731    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11732    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11733    // clean it might not have strictly needed; trusting a stale match would
11734    // cost it a wrong answer.
11735    if let Some(cache_dir) = cache
11736        && jobs_had_a_writer
11737    {
11738        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11739    }
11740    if let Some(guard) = cache_guard {
11741        guard.release();
11742    }
11743    collected.into_iter().flatten().collect()
11744}
11745
11746/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11747/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11748/// this is data collection, not the fix-specific completion contract in
11749/// [`Runner::continue_fix_report`], and applies regardless of which node
11750/// asked.
11751///
11752/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11753/// evidence from; `Failed` does not, and correctly contributes nothing — a
11754/// timeout or crash is not itself evidence about a command the seat may have
11755/// started.
11756fn record_jobs(
11757    state: &mut RunState,
11758    node: &str,
11759    round: Option<usize>,
11760    seat: &str,
11761    out: &AgentOutcome,
11762) {
11763    let commands: &[agent::CommandEvidence] = match out {
11764        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11765        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11766    };
11767    let checked_at = Timestamp::now();
11768    for c in commands {
11769        state.jobs.push(JobRecord {
11770            node: node.to_owned(),
11771            round,
11772            seat: seat.to_owned(),
11773            id: c.id.clone(),
11774            description: c.description.clone(),
11775            checked_at,
11776            status: match c.exit_code {
11777                Some(0) => JobStatus::Completed,
11778                Some(_) => JobStatus::Failed,
11779                None => JobStatus::Unknown,
11780            },
11781            exit_code: c.exit_code,
11782            result_summary: c.result_summary.clone(),
11783            source: c.source.clone(),
11784        });
11785    }
11786}
11787
11788/// Is a review round clean, given how many reviewer seats answered against
11789/// how many the round expected?
11790///
11791/// A seat that never answered (timeout, crash, unparsable output) is not a
11792/// seat that read the patch and found nothing — treating it as such is
11793/// exactly the bug this function exists to close. Under the default `block`
11794/// policy a missing seat can never be clean; `warn` still requires the seats
11795/// that *did* answer to have found nothing blocking and verification to be
11796/// green.
11797///
11798/// `quota_missing` narrows that `block` default for exactly one cause of
11799/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11800/// a session limit lifts by the very next round buys nothing — the seat is
11801/// asked again with the same quota — so once every missing seat is accounted
11802/// for by a quota loss (and at least one seat *did* answer, so a decision has
11803/// something to rest on) the round is decided on the panel that could answer,
11804/// same as `warn` would. A panel that lost every seat to quota is not
11805/// decided here: `answered == 0` falls through to the existing `block`
11806/// fallback so a fully collapsed panel still waits rather than landing on no
11807/// review at all.
11808fn round_is_clean(
11809    blocking: usize,
11810    e2e_ok: bool,
11811    answered: usize,
11812    expected: usize,
11813    quota_missing: usize,
11814    policy: IncompleteReviewPolicy,
11815) -> bool {
11816    if blocking != 0 || !e2e_ok {
11817        return false;
11818    }
11819    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11820        return true;
11821    }
11822    answered > 0 && expected - answered <= quota_missing
11823}
11824
11825/// The review loop's own conclusion, derived entirely from its persisted
11826/// round records and the round budget that produced them — never from
11827/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11828/// recomputes the identical answer regardless of what an earlier node in the
11829/// same walk, or a previous walk, did to `status`.
11830///
11831/// `None` while more rounds remain to try, including when review never ran
11832/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11833/// gone clean, or the budget is spent, or the tree has stopped moving (see
11834/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11835///
11836/// - An incomplete panel that raised nothing is missing input, not a
11837///   verified tree — never a hand-off candidate, whatever verification said
11838///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11839/// - Otherwise, green e2e on the last round hands off (see
11840///   [`Runner::stop_reviewing`]); red e2e blocks.
11841///
11842/// A last round whose own verification is still `ResourceBlocked` — magi
11843/// itself never got a command to run, not evidence the patch is broken —
11844/// is neither: this returns `None` for it too, the same as "more rounds
11845/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11846/// handling of that shape) instead of this cheap recomputation guessing a
11847/// verdict a real attempt never produced.
11848pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11849    if max_rounds == 0
11850        || reviews.last().is_some_and(|r| {
11851            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11852        })
11853    {
11854        return Some(RunStatus::Gating);
11855    }
11856    let last = reviews.last()?;
11857    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11858    if reviews.len() < max_rounds && !stagnant {
11859        return None;
11860    }
11861    if last.incomplete() && last.blocking == 0 {
11862        return Some(RunStatus::Blocked);
11863    }
11864    if last.e2e_status() == E2eStatus::ResourceBlocked
11865        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11866    {
11867        return None;
11868    }
11869    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11870        RunStatus::Gating
11871    } else {
11872        RunStatus::Blocked
11873    })
11874}
11875
11876/// How long a re-ask may take, given the budget the first attempt had.
11877///
11878/// A `nudged` retry is a request to restate an answer the seat has already
11879/// worked out: it carries no new work, so it does not deserve the original
11880/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11881/// 133 seconds while a third sat for over ten minutes on a resumed session
11882/// holding 410 KB of prior output - and because the retry had inherited the
11883/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11884/// judging round whose other seats were long finished.
11885///
11886/// A quarter of the budget, with a floor so that a deliberately short timeout
11887/// does not collapse to nothing. A retry that re-sends the whole prompt
11888/// (because the seat kept no context) is the original job again, and keeps the
11889/// original budget.
11890pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11891    if nudged {
11892        (full / 4).max(Duration::from_secs(120)).min(full)
11893    } else {
11894        full
11895    }
11896}
11897
11898/// Run a wave and parse each reply, re-asking the seats whose reply was
11899/// unusable.
11900///
11901/// The re-ask is a nudge rather than the whole prompt again when the seat still
11902/// holds its conversation, which is the difference between a cheap retry and
11903/// paying for the entire candidate set twice.
11904///
11905/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11906/// successor in `roster` is handed to it instead of being re-asked: the
11907/// handover is the retry. A seat with no successor left (a single-agent
11908/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11909/// the asks to one seat in one node number at most
11910/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11911/// is asked once (a dropped stream is nudged first), and only the last agent
11912/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11913/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11914/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11915/// other failure stops the chain when the previous agent failed the same way
11916/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11917/// [`has_context`] is false and the job's own full prompt and full budget are
11918/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11919/// intermediate ones are not losses) and is returned as a failure like any
11920/// other absent seat — the caller decides whether the panel still has a
11921/// quorum. An empty `roster` disables handover: failures are nudged as they
11922/// always were, and a quota is simply lost. A reply that fails to parse or
11923/// validate is the prompt's doing and is only ever nudged, never handed over.
11924///
11925/// The returned [`SeatState`] names the agent that answered (or tried last).
11926#[allow(clippy::too_many_arguments)]
11927async fn ask_json_wave<T>(
11928    jobs: Vec<SeatJob>,
11929    sem: Arc<Semaphore>,
11930    retries: usize,
11931    roster: &[AgentSpec],
11932    ctx: &WaveCtx<'_>,
11933    losses: &mut Vec<QuotaLoss>,
11934    state: &mut RunState,
11935    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11936) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11937where
11938    T: serde::de::DeserializeOwned + Send + 'static,
11939{
11940    ask_wave_with(
11941        jobs,
11942        sem,
11943        retries,
11944        roster,
11945        ctx,
11946        losses,
11947        state,
11948        &|text: &str| {
11949            let v = verdict::extract_json::<T>(text)?;
11950            validate(&v)?;
11951            Ok(v)
11952        },
11953    )
11954    .await
11955}
11956
11957/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11958/// a node whose answer is prose (deliberation) shares the same handover,
11959/// failure classification, quota bookkeeping and bounds instead of a copy.
11960///
11961/// A seat handed to another roster agent is sent the job's `handover` prompt
11962/// (when it has one) rather than `prompt`: the new agent has no session, so a
11963/// resume-style prompt would be incomplete. That holds for the handover ask
11964/// and for every nudge to that agent whose `has_context` is false.
11965#[allow(clippy::too_many_arguments)]
11966async fn ask_wave_with<T>(
11967    jobs: Vec<SeatJob>,
11968    sem: Arc<Semaphore>,
11969    retries: usize,
11970    roster: &[AgentSpec],
11971    ctx: &WaveCtx<'_>,
11972    losses: &mut Vec<QuotaLoss>,
11973    state: &mut RunState,
11974    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11975) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11976where
11977    T: Send + 'static,
11978{
11979    let n = jobs.len();
11980    let originals: Vec<SeatJob> = jobs;
11981    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11982    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11983    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11984    // answer, N once it has gone through N nudges. Read back once this
11985    // returns, so a caller building a history record (`ReviewRecord`) can
11986    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11987    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11988    // field's own doc.
11989    let mut nudges: Vec<usize> = vec![0; n];
11990    // The agent now occupying each seat, the ids it has already been through,
11991    // where in the roster the walk began, the class of the last failure, and
11992    // the stem word of a handover not yet asked (full prompt, full budget).
11993    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11994    let mut tried: Vec<BTreeSet<String>> = specs
11995        .iter()
11996        .map(|s| BTreeSet::from([s.id.clone()]))
11997        .collect();
11998    let starts: Vec<usize> = specs
11999        .iter()
12000        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12001        .collect();
12002    let carry = ctx.carry_seats && !roster.is_empty();
12003    // Carried across rounds: ids that failed the seat earlier, and how the
12004    // last failure went (so a repeat of it is not handed over again).
12005    let carried: Vec<BTreeSet<String>> = originals
12006        .iter()
12007        .map(|j| {
12008            state
12009                .seat_history
12010                .get(&j.seat.key)
12011                .filter(|_| carry)
12012                .map(|h| h.failed.clone())
12013                .unwrap_or_default()
12014        })
12015        .collect();
12016    let mut prev: Vec<Option<FailClass>> = originals
12017        .iter()
12018        .map(|j| {
12019            state
12020                .seat_history
12021                .get(&j.seat.key)
12022                .filter(|_| carry)
12023                .and_then(|h| h.last_fail.clone())
12024        })
12025        .collect();
12026    let next_agent =
12027        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12028            let others: BTreeSet<String> = specs
12029                .iter()
12030                .enumerate()
12031                .filter(|(j, _)| *j != i)
12032                .map(|(_, s)| s.id.clone())
12033                .collect();
12034            pick_successor(
12035                roster,
12036                starts[i],
12037                tried,
12038                carry.then(|| &carried[i]),
12039                &others,
12040            )
12041            .cloned()
12042        };
12043    let mut fresh: Vec<Option<String>> = vec![None; n];
12044    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12045    let mut pending: Vec<usize> = (0..n).collect();
12046
12047    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12048    // asks: an agent with a successor is asked once and handed over, and only
12049    // a seat with no successor spends `retries` nudges on the same agent. This
12050    // only guarantees the loop's own termination whatever those say.
12051    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12052    for round in 0..max_rounds {
12053        if pending.is_empty() {
12054            break;
12055        }
12056        let mut batch = Vec::with_capacity(pending.len());
12057        let mut renudged: Vec<&str> = Vec::new();
12058        for &i in &pending {
12059            let src = &originals[i];
12060            // A seat now held by another agent than the job named has no
12061            // session of its own: it gets the full-context prompt whenever
12062            // it is asked in full (the handover ask, a nudge it cannot
12063            // resume).
12064            let full: &str = match &src.handover {
12065                Some(h) if specs[i].id != src.spec.id => h,
12066                _ => &src.prompt,
12067            };
12068            // The prompt and the budget are one decision: a nudge restates
12069            // finished work, a re-sent prompt redoes it.
12070            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12071                (
12072                    full.to_owned(),
12073                    src.timeout,
12074                    format!("{}-{word}-{}", src.stem, specs[i].id),
12075                )
12076            } else if nudges[i] == 0 {
12077                (full.to_owned(), src.timeout, src.stem.clone())
12078            } else {
12079                renudged.push(src.seat.key.as_str());
12080                let why = done[i]
12081                    .as_ref()
12082                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12083                    .unwrap_or_else(|| "no parsable answer".to_owned());
12084                let nudge = prompt::nudge(&why);
12085                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12086                let prompt = if nudged {
12087                    nudge
12088                } else {
12089                    format!("{full}\n\n---\n\n{nudge}")
12090                };
12091                (
12092                    prompt,
12093                    retry_budget(src.timeout, nudged),
12094                    format!("{}-retry{}", src.stem, nudges[i]),
12095                )
12096            };
12097            batch.push(SeatJob {
12098                spec: specs[i].clone(),
12099                seat: seats[i].clone(),
12100                cwd: src.cwd.clone(),
12101                prompt,
12102                timeout,
12103                allow_write: src.allow_write,
12104                sessions: src.sessions,
12105                artifacts: src.artifacts.clone(),
12106                stem,
12107                handover: None,
12108            });
12109        }
12110
12111        if !renudged.is_empty() {
12112            state.event(
12113                ctx.node,
12114                format!("retry {round}: re-asking {}", renudged.join(", ")),
12115            );
12116        }
12117        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12118        let mut still = Vec::new();
12119        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12120            seats[i] = seat;
12121            // No agent was asked: nothing to hand over, nudge, remember or
12122            // charge. The caller sees `resource_block` and stops the node.
12123            if let AgentOutcome::ResourceBlocked(why) = &out {
12124                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12125                continue;
12126            }
12127            let class = FailClass::of(&out);
12128            // A dropped stream is nudged first (the conversation is still
12129            // there to pick up); only a seat whose nudges are spent hands over.
12130            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12131                && nudges[i] < retries
12132                && !roster.is_empty();
12133            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12134                let next = should_hand_over(prev[i].as_ref(), &cur)
12135                    .then(|| next_agent(i, &tried[i], &specs))
12136                    .flatten();
12137                if carry {
12138                    let h = state
12139                        .seat_history
12140                        .entry(originals[i].seat.key.clone())
12141                        .or_default();
12142                    h.failed.insert(specs[i].id.clone());
12143                    h.last_fail = Some(cur.clone());
12144                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12145                        h.last_ok = None;
12146                    }
12147                    // Saved before the next agent is asked, so a restart in
12148                    // between does not forget who failed.
12149                    if let Err(e) = state.save() {
12150                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12151                    }
12152                }
12153                if let Some(next) = next {
12154                    record_handover(
12155                        state,
12156                        ctx.node,
12157                        &originals[i].seat.key,
12158                        &specs[i].id,
12159                        &next.id,
12160                        &cur,
12161                        &fail_reason(&out),
12162                    );
12163                    tried[i].insert(next.id.clone());
12164                    prev[i] = Some(cur.clone());
12165                    seats[i] =
12166                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12167                    specs[i] = next;
12168                    fresh[i] = Some(cur.stem_word().to_owned());
12169                    nudges[i] = 0;
12170                    done[i] = Some(Err(anyhow::anyhow!(
12171                        "handed over after: {}",
12172                        fail_reason(&out)
12173                    )));
12174                    still.push(i);
12175                    continue;
12176                }
12177            }
12178            if carry
12179                && !nudge_first
12180                && let Some(cur) = class.clone()
12181            {
12182                // The chain ended here (no successor, or a repeated failure).
12183                let h = state
12184                    .seat_history
12185                    .entry(originals[i].seat.key.clone())
12186                    .or_default();
12187                h.failed.insert(specs[i].id.clone());
12188                h.last_fail = Some(cur);
12189            }
12190            let parsed = match out {
12191                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12192                AgentOutcome::Quota(o) => {
12193                    last_quota[i] = o.quota.clone();
12194                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12195                }
12196                // Not a parseable answer: the nudge loop re-asks it, which is
12197                // exactly what a dropped stream needs. Just don't hand its raw
12198                // error JSON to `extract_json`.
12199                AgentOutcome::Dropped(o) => {
12200                    let why = o
12201                        .dropped
12202                        .as_ref()
12203                        .map(|d| d.why.as_str())
12204                        .unwrap_or("the CLI ended the stream without delivering its answer");
12205                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12206                }
12207                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12208                    Err(anyhow::anyhow!(e))
12209                }
12210            };
12211            let quota = class == Some(FailClass::Quota);
12212            let failed = parsed.is_err();
12213            if !failed && matches!(ctx.node, "judge" | "vote") {
12214                // A validated answer restores this seat's quorum presence,
12215                // including on the normal path after an all-seat block.
12216                state
12217                    .quota
12218                    .retain(|loss| loss.seat != originals[i].seat.key);
12219            }
12220            done[i] = Some(parsed);
12221            if carry && !failed {
12222                let h = state
12223                    .seat_history
12224                    .entry(originals[i].seat.key.clone())
12225                    .or_default();
12226                h.failed.remove(&specs[i].id);
12227                h.last_ok = Some(specs[i].id.clone());
12228                h.last_fail = None;
12229            }
12230            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12231            // fail the same way; and never re-ask a seat that already parsed.
12232            // A failed agent that still has a successor is not re-asked
12233            // either: the handover was its remedy and has just been refused
12234            // (the chain stops on a repeated failure class). A seat with no
12235            // successor left (a single-agent roster, the roster's tail, or an
12236            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12237            let agent_failure = class.is_some()
12238                && !nudge_first
12239                && !roster.is_empty()
12240                && next_agent(i, &tried[i], &specs).is_some();
12241            if failed && !quota && !agent_failure && nudges[i] < retries {
12242                nudges[i] += 1;
12243                still.push(i);
12244            }
12245        }
12246        pending = still;
12247    }
12248
12249    // One loss per seat whose chain ended on a quota: the intermediate ones
12250    // were absorbed by a handover and are not losses.
12251    for (i, q) in last_quota.into_iter().enumerate() {
12252        if let Some(quota) = q {
12253            losses.push(QuotaLoss::from_report(
12254                originals[i].seat.key.clone(),
12255                ctx.node,
12256                Some(&quota),
12257            ));
12258        }
12259    }
12260
12261    // A stalled quorum already has its own recovery checkpoint. Refresh
12262    // its missing seats before deciding whether it can resume.
12263    if state.status != RunStatus::Stalled
12264        && ctx.node != "deliberate"
12265        && n > 0
12266        && losses.len() == n
12267        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12268    {
12269        block_machine_outage(state, ctx.node, losses);
12270        state.quota.append(losses);
12271    }
12272
12273    seats
12274        .into_iter()
12275        .zip(done)
12276        .zip(nudges)
12277        .map(|((seat, res), attempts)| {
12278            (
12279                seat,
12280                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12281                attempts,
12282            )
12283        })
12284        .collect()
12285}
12286
12287/// A node with no available agent has no task verdict. Preserve the node
12288/// checkpoint and record why a subsequent explicit resume is needed.
12289pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12290    let mut auth: Vec<_> = losses
12291        .iter()
12292        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12293        .map(|loss| loss.agent.clone())
12294        .collect();
12295    auth.sort();
12296    auth.dedup();
12297    let (kind, detail) = if auth.is_empty() {
12298        (
12299            "agent usage limit",
12300            "All seats reached their agent usage limits; resume after usage is available"
12301                .to_owned(),
12302        )
12303    } else {
12304        (
12305            "agent authentication",
12306            format!(
12307                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12308                auth.join(", ")
12309            ),
12310        )
12311    };
12312    state.resource_block = Some(crate::run::ResourceBlock {
12313        node: node.to_owned(),
12314        kind: kind.to_owned(),
12315        cause: crate::run::ResourceBlockCause::Other,
12316        detail: detail.clone(),
12317        at: Timestamp::now(),
12318    });
12319    state.event(node, detail);
12320}
12321
12322/// Did the wave end without asking any agent (see [`block_wave`])?
12323fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12324    results
12325        .iter()
12326        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12327}
12328
12329/// Settle a wave that never spawned anything: every job answers
12330/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12331/// else about the seat (session, history, quota) is touched.
12332fn block_wave(
12333    jobs: Vec<SeatJob>,
12334    state: &mut RunState,
12335    node: &str,
12336    attempt: usize,
12337    why: &str,
12338) -> Vec<(usize, SeatState, AgentOutcome)> {
12339    state.resource_wait = None;
12340    state
12341        .active
12342        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12343    if let Err(e) = state.save() {
12344        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12345    }
12346    jobs.into_iter()
12347        .enumerate()
12348        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12349        .collect()
12350}
12351
12352/// Acquire the shared build cache's lease, waiting out contention within
12353/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12354/// unbounded wait is never acceptable).
12355///
12356/// A first, non-blocking check happens before ever waiting; if it finds the
12357/// lease busy, that fact is logged as a `verify` event *and* flushed with
12358/// [`RunState::save`] immediately — not only once the wait finally succeeds
12359/// or gives up — so a `magi show` run by a different process while this one
12360/// is still waiting reads a `run.json` that says so, rather than whatever it
12361/// looked like before the wait started. The same applies to the terminal
12362/// failure: logged and saved before this returns `Err`, so a caller that
12363/// could not get the lease at all still leaves a legible record of why.
12364async fn acquire_cache_lease(
12365    state: &mut RunState,
12366    cache_dir: &Path,
12367    owner: &crate::cache::Owner,
12368    budget: Duration,
12369    node: &str,
12370    context: &str,
12371    cancel: &(dyn Fn() -> bool + Sync),
12372) -> Result<Option<crate::cache::Guard>> {
12373    let home = crate::run::home();
12374    let kind = if crate::build_target::isolated(&state.config) {
12375        crate::build_target::KIND
12376    } else {
12377        "shared build cache"
12378    };
12379    let started = Instant::now();
12380    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12381        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12382        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12383        Err(e) => {
12384            state.event(
12385                "verify",
12386                format!(
12387                    "{context}: could not check the {kind} at {}: {e:#}",
12388                    cache_dir.display()
12389                ),
12390            );
12391            if let Err(e2) = state.save() {
12392                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12393            }
12394            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12395        }
12396    };
12397    state.event(
12398        "verify",
12399        format!(
12400            "{context}: waiting for the {kind} at {} ({})",
12401            cache_dir.display(),
12402            busy.describe()
12403        ),
12404    );
12405    // Seats of this node are waiting, not running: say so, so the countdown a
12406    // reader sees only ever measures an agent that has been spawned.
12407    state.resource_wait = Some(crate::run::ResourceWait {
12408        node: context.to_owned(),
12409        kind: kind.to_owned(),
12410        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12411        since: Timestamp::now(),
12412        limit_secs: budget.as_secs(),
12413    });
12414    if let Err(e) = state.save() {
12415        tracing::warn!("could not persist a cache wait: {e:#}");
12416    }
12417    let remaining = budget.saturating_sub(started.elapsed());
12418    let waited = crate::cache::wait_for_unless(
12419        &home,
12420        cache_dir,
12421        owner,
12422        remaining,
12423        Duration::from_secs(5),
12424        cancel,
12425    )
12426    .await;
12427    state.resource_wait = None;
12428    let cause = match &waited {
12429        Ok(Some(_)) => None,
12430        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12431        Err(error)
12432            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12433        {
12434            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12435                target: cache_dir.to_owned(),
12436                waited_secs: started.elapsed().as_secs(),
12437                limit_secs: budget.as_secs(),
12438            })
12439        }
12440        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12441            Some(crate::run::ResourceBlockCause::Timeout {
12442                waited_secs: started.elapsed().as_secs(),
12443                limit_secs: budget.as_secs(),
12444            })
12445        }
12446        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12447    };
12448    if let Some(cause) = cause {
12449        let detail = match &waited {
12450            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12451            Err(error) => format!("{error:#}"),
12452        };
12453        state.resource_block = Some(crate::run::ResourceBlock {
12454            cause,
12455            node: node.to_owned(),
12456            kind: kind.into(),
12457            detail: format!("{}: {detail}", cache_dir.display()),
12458            at: Timestamp::now(),
12459        });
12460        state.event(
12461            "resource",
12462            state.resource_block.as_ref().unwrap().description(),
12463        );
12464    }
12465    if let Err(error) = state.save() {
12466        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12467    }
12468    waited
12469}
12470
12471/// The lease state could not be read at all (unreadable lease file, a
12472/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12473/// known to be contended, so a wave degrades to running without a shared cache
12474/// instead of stopping on a hold that [`crate::triage`] could never release.
12475#[derive(Debug)]
12476struct CacheCheckError(String);
12477
12478impl std::fmt::Display for CacheCheckError {
12479    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12480        f.write_str(&self.0)
12481    }
12482}
12483
12484impl std::error::Error for CacheCheckError {}
12485
12486/// Keep a specific acquisition outcome when the caller adds command evidence.
12487fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12488    let kind = if crate::build_target::isolated(&state.config) {
12489        crate::build_target::KIND
12490    } else {
12491        "shared build cache"
12492    };
12493    state
12494        .resource_block
12495        .get_or_insert_with(|| crate::run::ResourceBlock {
12496            cause: crate::run::ResourceBlockCause::Other,
12497            node: node.to_owned(),
12498            kind: kind.into(),
12499            detail: format!("{error:#}"),
12500            at: Timestamp::now(),
12501        });
12502    if let Err(error) = state.save() {
12503        tracing::warn!("could not persist cache resource block: {error:#}");
12504    }
12505}
12506
12507tokio::task_local! {
12508    static VERIFY_TARGET: PathBuf;
12509}
12510
12511/// Run `body` — a verify command batch — while holding the shared build
12512/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12513/// never interleave with another borrower's build against the same
12514/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12515/// timeout, or a human's own `magi review`. See the `cache` module doc for
12516/// why this matters more than Cargo's own per-target locking covers — two
12517/// *different* worktrees building the same package name/version into one
12518/// cache directory is a staleness bug, not a lock contention one.
12519///
12520/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12521/// agent waves do. Repository scheduling also has its own bounded,
12522/// cancellable resource-wait policy. Contention must not consume the
12523/// verification budget: `body` receives the full `budget` after both leases
12524/// are acquired and the cache is fresh. Without a shared cache, only
12525/// repository coordination is acquired before handing over the full budget.
12526///
12527/// A lease that cannot be acquired within the resource wait is reported as a single
12528/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12529/// verification — the same shape a spawn failure already takes in
12530/// [`run_commands`], so a caller need not special-case it.
12531#[allow(clippy::too_many_arguments)]
12532async fn with_cache_lease<'s, F, Fut>(
12533    state: &'s mut RunState,
12534    cache_dir: Option<&Path>,
12535    node: &str,
12536    seat: &str,
12537    worktree: &Path,
12538    head: &str,
12539    budget: Duration,
12540    context: &str,
12541    wait: &crate::repo_lock::WaitPolicy,
12542    body: F,
12543) -> Result<(Vec<CommandOutcome>, bool)>
12544where
12545    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12546    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12547{
12548    // Match editing waves: cache first, repository second. In particular,
12549    // pre_gate must never hold the repository while waiting for a wave's cache.
12550    let started = Instant::now();
12551    let home = crate::run::home();
12552    let isolated = crate::build_target::isolated(&state.config);
12553    let planned_target = if isolated {
12554        let plan = (|| -> Result<PathBuf> {
12555            crate::build_target::supports(&state.config)?;
12556            crate::build_target::resolve(&home, worktree)
12557        })();
12558        match plan {
12559            Ok(path) => Some(path),
12560            Err(error) => {
12561                record_cache_error(state, node, &error);
12562                return Ok((
12563                    vec![CommandOutcome {
12564                        command: "(planning isolated build cache)".into(),
12565                        code: None,
12566                        output_tail: format!("{error:#}"),
12567                        duration_ms: 0,
12568                        resource_blocked: true,
12569                        ..Default::default()
12570                    }],
12571                    false,
12572                ));
12573            }
12574        }
12575    } else {
12576        None
12577    };
12578    let cache_dir = planned_target.as_deref().or(cache_dir);
12579    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12580    let guard = if let Some(cache_dir) = cache_dir {
12581        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12582        match acquire_cache_lease(
12583            state,
12584            cache_dir,
12585            &owner,
12586            resource_limit,
12587            node,
12588            context,
12589            &|| wait.cancelled(),
12590        )
12591        .await
12592        .and_then(|g| {
12593            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12594        }) {
12595            Ok(g) => Some(g),
12596            Err(e) => {
12597                record_cache_error(state, node, &e);
12598                return Ok((
12599                    vec![CommandOutcome {
12600                        command: if isolated {
12601                            "(waiting for the isolated build cache)"
12602                        } else {
12603                            "(waiting for the shared build cache)"
12604                        }
12605                        .into(),
12606                        code: None,
12607                        output_tail: e.to_string(),
12608                        duration_ms: started.elapsed().as_millis() as u64,
12609                        resource_blocked: true,
12610                        ..Default::default()
12611                    }],
12612                    false,
12613                ));
12614            }
12615        }
12616    } else {
12617        None
12618    };
12619    let _coordination = coordinate_operation(state, worktree, wait).await?;
12620    if let Some(path) = &planned_target {
12621        state.event(node, format!("isolated build target: {}", path.display()));
12622    }
12623    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12624        let identity = crate::cache::Identity::new(worktree, head);
12625        let fresh = crate::cache::ensure_fresh(
12626            &home,
12627            cache_dir,
12628            &identity,
12629            &state.config.verify.cargo_manifests(),
12630        );
12631        if let Err(e) = fresh {
12632            record_cache_error(state, node, &e);
12633            state.event(
12634                "verify",
12635                format!(
12636                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12637                    worktree.display(),
12638                    short(head)
12639                ),
12640            );
12641            if let Some(guard) = guard {
12642                guard.release();
12643            }
12644            return Ok((
12645                vec![CommandOutcome {
12646                    command: "(confirming the build cache is fresh)".into(),
12647                    code: None,
12648                    output_tail: e.to_string(),
12649                    duration_ms: started.elapsed().as_millis() as u64,
12650                    resource_blocked: true,
12651                    ..Default::default()
12652                }],
12653                false,
12654            ));
12655        }
12656    }
12657    let future = body(state, budget);
12658    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12659        VERIFY_TARGET.scope(target, future).await
12660    } else {
12661        future.await
12662    };
12663    if !timed_out_pids.is_empty() {
12664        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12665    }
12666    // Drop repository coordination before releasing the cache, reversing the
12667    // acquisition order. A cancelled/error future also drops both guards.
12668    drop(_coordination);
12669    if let Some(guard) = guard {
12670        guard.release();
12671    }
12672    Ok((outcomes, retried))
12673}
12674
12675/// Poll `pids` — commands [`run_commands`] reports as still running when its
12676/// own timeout elapsed — until every one is confirmed gone, or
12677/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12678///
12679/// Real confirmation where confirmation is possible, not a substitute for
12680/// full process-tree observation: a grandchild the timed-out process spawned
12681/// and that survives independently of it is invisible to a pid check the
12682/// same way it always was, and continuing to observe and collect *that*
12683/// stays a different piece of work with its own owner. This only narrows a
12684/// fixed blind wait into an actual check of the pids this process does know
12685/// about.
12686async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12687    wait_for_pids_with(
12688        pids,
12689        crate::proc::pid_alive,
12690        LEASE_RELEASE_POLL,
12691        LEASE_RELEASE_MAX_WAIT,
12692    )
12693    .await;
12694}
12695
12696/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12697/// interval and ceiling supplied by the caller, so the polling *logic* -
12698/// returns as soon as every pid reports dead, gives up at the ceiling
12699/// otherwise - is testable on millisecond durations without asking the real
12700/// OS about a pid at all.
12701async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12702    pids: &[u32],
12703    alive: F,
12704    poll: Duration,
12705    max_wait: Duration,
12706) {
12707    let deadline = Instant::now() + max_wait;
12708    loop {
12709        if pids.iter().all(|&pid| !alive(pid)) {
12710            return;
12711        }
12712        if Instant::now() >= deadline {
12713            return;
12714        }
12715        tokio::time::sleep(poll).await;
12716    }
12717}
12718
12719/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12720/// admission that it could not even get a verify command to run, as opposed
12721/// to evidence the command actually produced? A caller that would otherwise
12722/// read a resource-blocked outcome as a red command must check this first:
12723/// see [`Runner::gate`], which retries rather than records `Blocked` when
12724/// this is true.
12725fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12726    outcomes.iter().any(|o| o.resource_blocked)
12727}
12728
12729/// What [`Runner::gate_fix_round`] decided.
12730pub(crate) enum GateFix {
12731    /// The tree changed and `verify.e2e` is still green: run the gate again.
12732    Retry,
12733    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12734    /// last failure stands and the run ends blocked.
12735    Stop,
12736    /// `verify.e2e` could not run after the fix (magi's own contention):
12737    /// decide nothing now, a later reentry retries.
12738    Defer,
12739}
12740
12741/// Is every red command in `outcomes` an ordinary failure the code could
12742/// explain: it ran, exited non-zero, and said something?
12743///
12744/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12745/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12746/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12747/// what the command is stays the gate's business.
12748pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12749    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12750    red.peek().is_some()
12751        && red.all(|o| {
12752            !o.resource_blocked
12753                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12754                && !o.output_tail.trim().is_empty()
12755        })
12756}
12757
12758/// Describe one verify command's outcome for the event log, distinguishing a
12759/// build/link failure — the toolchain never produced a binary to run — from
12760/// an actual test failure, since only the latter is a verdict on the patch.
12761fn e2e_outcome_label(o: &CommandOutcome) -> String {
12762    if o.ok() {
12763        return "pass".to_owned();
12764    }
12765    let reason = if o.build_failed() {
12766        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12767    } else {
12768        format!("FAIL ({:?})", o.code)
12769    };
12770    format!(
12771        "{reason}\n{}",
12772        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12773    )
12774}
12775
12776/// Does `outcomes` hold a failure worth one more run on the same commit?
12777///
12778/// Only an ordinary test result qualifies: every red command ran, exited
12779/// non-zero and said which way (not a build/link failure, a timeout or kill,
12780/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12781/// evidence about the machine or the toolchain, never about a flaky test.
12782fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12783    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12784    red.peek().is_some()
12785        && !verify_inconclusive(outcomes)
12786        && red.all(|o| {
12787            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12788        })
12789}
12790
12791/// Run `verify.e2e`, retrying once if the first attempt could not build or
12792/// link — a build/link failure is frequently a race against a shared
12793/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12794/// `verify` event per command, tagged with `context` (normally `"round N"`)
12795/// so the call sites that need this — the ordinary per-round leg in
12796/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12797/// will ever call a round green, `verify_current_head` and the gate-repair
12798/// check — read identically in the event log.
12799///
12800/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12801/// only after the failed commands have run once more on the same commit, in
12802/// the same worktree and — because the caller holds it around this whole
12803/// function — under the same cache lease, with a full `timeout` of their own
12804/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12805/// flake: the head is verified, the first failure is recorded and filed
12806/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12807/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12808/// preserving bounded evidence and artifact references for both attempts;
12809/// it claims a matching reproduction only when both attempts yield identical
12810/// confirmed terminal test failures. One verification is therefore run at most
12811/// three times: the build/link retry, then this one rerun. `round` is the
12812/// review round the verification belongs to, if any.
12813async fn run_e2e_with_retry(
12814    state: &mut RunState,
12815    shell: &[String],
12816    commands: &[String],
12817    worktree: &Path,
12818    timeout: Duration,
12819    context: &str,
12820    round: Option<usize>,
12821) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12822    let (mut e2e, mut timed_out_pids) = run_commands(
12823        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12824    )
12825    .await;
12826    for o in &e2e {
12827        state.event(
12828            "verify",
12829            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12830        );
12831    }
12832    // A build/link failure is not a verdict on the patch — it is frequently a
12833    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12834    // one retry before letting a red like that decide the round.
12835    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12836    if verify_retried {
12837        state.event(
12838            "verify",
12839            format!(
12840                "{context}: verify could not build/link, not a test result — retrying once \
12841                 before concluding"
12842            ),
12843        );
12844        let retried = run_commands(
12845            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12846        )
12847        .await;
12848        e2e = retried.0;
12849        // Both attempts' timeouts matter, not just the last one: the first
12850        // attempt's descendants may still be alive alongside the retry's.
12851        timed_out_pids.extend(retried.1);
12852        for o in &e2e {
12853            state.event(
12854                "verify",
12855                format!(
12856                    "{context}: retry `{}` -> {}",
12857                    o.command,
12858                    e2e_outcome_label(o)
12859                ),
12860            );
12861        }
12862    }
12863    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12864        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12865        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12866        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12867        state.event(
12868            "verify",
12869            format!(
12870                "{context}: {} failed with a test result — running it once more on the same \
12871                 commit {} before deciding",
12872                rerun_commands
12873                    .iter()
12874                    .map(|c| format!("`{c}`"))
12875                    .collect::<Vec<_>>()
12876                    .join(", "),
12877                short(&head)
12878            ),
12879        );
12880        let (second, pids) = run_commands(
12881            state,
12882            "verify",
12883            "e2e",
12884            1 + usize::from(verify_retried),
12885            shell,
12886            &rerun_commands,
12887            worktree,
12888            timeout,
12889        )
12890        .await;
12891        timed_out_pids.extend(pids);
12892        for o in &second {
12893            state.event(
12894                "verify",
12895                format!(
12896                    "{context}: rerun `{}` -> {}",
12897                    o.command,
12898                    e2e_outcome_label(o)
12899                ),
12900            );
12901        }
12902        for (slot, &i) in failed.iter().enumerate() {
12903            let Some(again) = second.get(slot) else {
12904                break;
12905            };
12906            let first = std::mem::replace(&mut e2e[i], again.clone());
12907            if again.ok() {
12908                let signature = crate::flake::signature(&first.output_tail, first.code);
12909                let flake = crate::run::VerifyFlake {
12910                    round,
12911                    context: context.to_owned(),
12912                    head: head.clone(),
12913                    command: first.command.clone(),
12914                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12915                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12916                    at: Timestamp::now(),
12917                    task: None,
12918                    filed: false,
12919                    filing_error: None,
12920                };
12921                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12922            } else if !again.resource_blocked {
12923                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
12924                let message = crate::verify_evidence::rerun_event_message(
12925                    context,
12926                    &e2e[i].command,
12927                    &comparison,
12928                );
12929                e2e[i].rerun_comparison = Some(comparison);
12930                state.event("verify", message);
12931            }
12932        }
12933    }
12934    (e2e, verify_retried, timed_out_pids)
12935}
12936
12937/// Run configured shell commands in `cwd`, in order. The second element is
12938/// the pid of every command that hit `timeout` and was still running when
12939/// this stopped waiting on it (best-effort: `None` when the platform did not
12940/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12941/// that releases a shared resource afterward needs to know.
12942///
12943/// Records `task` into [`RunState::active`] at every command boundary
12944/// (`RunState::task_command`) and clears it once the whole list has run
12945/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12946/// for minutes with no seat and no output of its own to show for it (see
12947/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12948/// apart from "not yet run" without this), and this is the only place that
12949/// knows which command is running right now and how many are left. Three
12950/// saves per command — start, not per second — matching the same "only at a
12951/// boundary" rule [`wave`] already follows for seats.
12952#[allow(clippy::too_many_arguments)]
12953async fn run_commands(
12954    state: &mut RunState,
12955    node: &str,
12956    task: &str,
12957    attempt: usize,
12958    shell: &[String],
12959    commands: &[String],
12960    cwd: &Path,
12961    timeout: Duration,
12962) -> (Vec<CommandOutcome>, Vec<u32>) {
12963    let isolated = crate::build_target::isolated(&state.config);
12964    if isolated && let Some(block) = &state.resource_block {
12965        return (
12966            vec![CommandOutcome {
12967                command: "(isolated build admission)".into(),
12968                code: None,
12969                output_tail: block.description(),
12970                duration_ms: 0,
12971                resource_blocked: true,
12972                ..Default::default()
12973            }],
12974            Vec::new(),
12975        );
12976    }
12977    if commands.is_empty() {
12978        // Nothing to mark as running and nothing to clear — an empty list
12979        // means "not configured", and touching `active` (or the disk) over
12980        // that would be a write for every round of a repo with no
12981        // `verify.e2e` / `verify.gate` commands at all.
12982        return (Vec::new(), Vec::new());
12983    }
12984    let mut out = Vec::new();
12985    let mut timed_out_pids = Vec::new();
12986    let total = commands.len();
12987    for (idx, command) in commands.iter().enumerate() {
12988        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12989        if let Err(e) = state.save() {
12990            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12991        }
12992        let started = Instant::now();
12993        let mut cmd = tokio::process::Command::new(&shell[0]);
12994        cmd.quiet();
12995        // Verify the checkout as a standalone caller. Worker ownership and
12996        // pinned executable selection belong to this driver, not to tests or
12997        // tools it runs. Preserve home/seat context and Running's containment.
12998        for key in crate::worker::INVOCATION_ENV {
12999            cmd.env_remove(key);
13000        }
13001        cmd.env_remove(crate::build_id::EXPECT_ENV);
13002        cmd.args(&shell[1..])
13003            .current_dir(cwd)
13004            .stdin(std::process::Stdio::null())
13005            .stdout(std::process::Stdio::piped())
13006            .stderr(std::process::Stdio::piped())
13007            .kill_on_drop(true);
13008        let mut outputs = Vec::new();
13009        let mut cache = None;
13010        let home = crate::run::home();
13011        let head = if isolated {
13012            Some(git::rev_parse(cwd, "HEAD").await)
13013        } else {
13014            None
13015        };
13016        let protected = (|| -> Result<()> {
13017            crate::incremental::configure(&mut cmd, cwd)?;
13018            cache = if isolated {
13019                let target = VERIFY_TARGET
13020                    .try_with(Clone::clone)
13021                    .context("isolated verification has no target lease")?;
13022                cmd.arg(crate::build_target::command::normalize(command)?);
13023                crate::build_target::command::configure(&mut cmd, &target)?;
13024                Some(target)
13025            } else {
13026                crate::build_target::command::clear(&mut cmd)?;
13027                cmd.arg(command);
13028                state.config.cache_dir()
13029            };
13030            let mut paths = vec![cwd.to_owned()];
13031            if let Some(cache) = &cache {
13032                paths.push(cache.clone());
13033            }
13034            let admit = if isolated {
13035                crate::retention::OutputLease::admit_isolated
13036            } else {
13037                crate::retention::OutputLease::admit
13038            };
13039            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13040            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13041                outputs.push(guard);
13042            }
13043            if let Some(cache) = &cache {
13044                outputs.push(crate::retention::OutputLease::cache(
13045                    &crate::run::home(),
13046                    cache,
13047                    false,
13048                )?);
13049                if let Some(head) = head {
13050                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13051                    if task == "pre_gate" {
13052                        crate::cache::invalidate_identity(&home, cache);
13053                    }
13054                }
13055            }
13056            Ok(())
13057        })();
13058        if let Err(e) = protected {
13059            let detail = format!("execution admission unavailable: {e:#}");
13060            state.resource_block = Some(crate::run::ResourceBlock {
13061                cause: crate::run::ResourceBlockCause::Other,
13062                node: node.to_owned(),
13063                kind: if detail.contains("disk admission") {
13064                    "disk admission"
13065                } else {
13066                    "output ownership"
13067                }
13068                .to_owned(),
13069                detail: detail.clone(),
13070                at: Timestamp::now(),
13071            });
13072            out.push(CommandOutcome {
13073                command: command.clone(),
13074                code: None,
13075                output_tail: detail,
13076                duration_ms: 0,
13077                resource_blocked: true,
13078                ..Default::default()
13079            });
13080            break;
13081        }
13082        let spawned = if isolated {
13083            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13084        } else {
13085            crate::seat_process::Running::spawn(cmd, None, outputs)
13086        };
13087        let (code, out_text, err_text, body) = match spawned {
13088            Ok(mut running) => {
13089                let pid = running.child().id();
13090                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13091                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13092                let mut paths = vec![cwd.to_owned()];
13093                if let Some(cache) = cache {
13094                    paths.push(cache);
13095                }
13096                let mut pressure = None;
13097                let status = tokio::select! {
13098                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13099                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13100                        pressure = Some(reason); None
13101                    }
13102                };
13103                let (code, failure) = match status {
13104                    Some(Ok(Ok(status))) => (
13105                        status.code(),
13106                        status
13107                            .code()
13108                            .is_none()
13109                            .then(|| format!("command terminated: {status}")),
13110                    ),
13111                    Some(Ok(Err(error))) => {
13112                        (None, Some(format!("failed waiting for command: {error}")))
13113                    }
13114                    Some(Err(_)) => {
13115                        // Leased cleanup confirms process-tree death itself.
13116                        // Unleased commands still need the caller's PID check
13117                        // after kill-on-drop, before releasing cache ownership.
13118                        if !running.coordinated()
13119                            && let Some(pid) = pid
13120                        {
13121                            timed_out_pids.push(pid);
13122                        }
13123                        (
13124                            None,
13125                            Some(format!("timed out after {}s", timeout.as_secs())),
13126                        )
13127                    }
13128                    None => (None, None),
13129                };
13130                running.finish().await;
13131                if let Some(reason) = pressure {
13132                    state.resource_block = Some(crate::run::ResourceBlock {
13133                        cause: crate::run::ResourceBlockCause::Other,
13134                        node: node.to_owned(),
13135                        kind: "disk pressure".to_owned(),
13136                        detail: reason.clone(),
13137                        at: Timestamp::now(),
13138                    });
13139                    out.push(CommandOutcome {
13140                        command: command.clone(),
13141                        code: None,
13142                        output_tail: reason,
13143                        duration_ms: started.elapsed().as_millis() as u64,
13144                        resource_blocked: true,
13145                        ..Default::default()
13146                    });
13147                    break;
13148                }
13149                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13150                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13151                let mut body = out_text.clone();
13152                body.push_str(&err_text);
13153                if let Some(failure) = failure {
13154                    body.push('\n');
13155                    body.push_str(&failure);
13156                }
13157                (code, out_text, err_text, body)
13158            }
13159            Err(e) if isolated => {
13160                let e = anyhow::Error::new(e)
13161                    .context(format!("could not start managed build `{}`", shell[0]));
13162                record_cache_error(state, node, &e);
13163                out.push(CommandOutcome {
13164                    command: command.clone(),
13165                    code: None,
13166                    output_tail: format!("{e:#}"),
13167                    duration_ms: 0,
13168                    resource_blocked: true,
13169                    ..Default::default()
13170                });
13171                break;
13172            }
13173            Err(e) => (
13174                None,
13175                String::new(),
13176                String::new(),
13177                format!("failed to spawn `{}`: {e}", shell[0]),
13178            ),
13179        };
13180        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13181        let mut artifact = None;
13182        if !body.is_empty() {
13183            // The full text is kept whatever the summary dropped. A fresh
13184            // name per command so a resume or retry never overwrites an
13185            // earlier run's output. A failed write changes no verdict.
13186            match crate::run::write_verification_artifact(state, task, &body) {
13187                Ok(name) => {
13188                    let rel = format!("artifacts/{name}");
13189                    if summary != body {
13190                        summary = format!("[full output: {rel}]\n{summary}");
13191                    }
13192                    artifact = Some(rel);
13193                }
13194                Err(e) => {
13195                    let warning = format!("could not save the full {task} output: {e:#}");
13196                    tracing::warn!("{warning}");
13197                    state.event(node, warning);
13198                    if summary != body {
13199                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13200                    }
13201                }
13202            }
13203        }
13204        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13205        let mut outcome = CommandOutcome {
13206            command: command.clone(),
13207            code,
13208            output_tail: summary,
13209            duration_ms: started.elapsed().as_millis() as u64,
13210            resource_blocked,
13211            artifact,
13212            failure_evidence: None,
13213            rerun_comparison: None,
13214        };
13215        if !outcome.ok() && !outcome.resource_blocked {
13216            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13217                code,
13218                outcome.build_failed(),
13219                &out_text,
13220                &err_text,
13221            ));
13222        }
13223        out.push(outcome);
13224        if resource_blocked {
13225            state.resource_block = Some(crate::run::ResourceBlock {
13226                cause: crate::run::ResourceBlockCause::Other,
13227                node: node.to_owned(),
13228                kind: "incremental cache admission".into(),
13229                detail: body,
13230                at: Timestamp::now(),
13231            });
13232            break;
13233        }
13234    }
13235    state.task_finished(task);
13236    if let Err(e) = state.save() {
13237        tracing::warn!("could not persist the end of {task}: {e:#}");
13238    }
13239    (out, timed_out_pids)
13240}
13241
13242/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13243/// section (`report::run`) and in the `merge` event this node records — for
13244/// the operator to run by hand.
13245///
13246/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13247/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13248/// merge commits", or "require linear history") rejects the push a `--no-ff`
13249/// merge would produce, which is exactly the guidance this function replaces.
13250/// `message`'s first line becomes the squash commit's subject, matching the
13251/// note `report::run` prints alongside this command — see that function for
13252/// why an explicit subject is not optional there.
13253fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13254    let repo = repo.display();
13255    match style {
13256        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13257        MergeStyle::Squash => {
13258            // The subject sits inside double quotes, and a title an agent
13259            // wrote may carry the characters that break out of them.
13260            let subject = message
13261                .lines()
13262                .next()
13263                .unwrap_or(branch)
13264                .replace(['\\', '"', '$', '`'], "");
13265            format!(
13266                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13267            )
13268        }
13269        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13270    }
13271}
13272
13273/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13274/// under the hood, rejects a `title` over 256 characters and the whole
13275/// command fails — no PR at all, for a run whose body was otherwise fine
13276/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13277/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13278/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13279/// this bound. It is a margin, not a guarantee — a title packed
13280/// with multi-unit characters could still in principle land close to the
13281/// edge, but a real task title's occasional emoji or accented letter fits
13282/// comfortably inside it.
13283const PR_TITLE_MAX: usize = 240;
13284
13285/// A pull request title from the opening line of `text`, or `None` when that
13286/// line is not English (GitHub text is) or has no letters.
13287///
13288/// A line within `max` is kept as is. A longer one is cut at the end of its
13289/// first sentence when that falls inside `max`, else at a word boundary with a
13290/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13291/// make every merely-truncated title look non-English). The language check
13292/// runs on the kept text before any mark is added, so only what GitHub will
13293/// show is judged: an English opening followed by non-ASCII far past the cut
13294/// still passes.
13295fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13296    let line = queue::first_line(text)?;
13297    let chars: Vec<char> = line.chars().collect();
13298    let (kept, mark) = if chars.len() <= max {
13299        (line.to_owned(), "")
13300    } else if let Some(end) = sentence_end(&chars, max) {
13301        (chars[..end].iter().collect::<String>(), "")
13302    } else {
13303        let room = max.saturating_sub(3);
13304        // Cut at the last space inside the room; when the char just past the
13305        // room is a space the room already ends on a word.
13306        let cut = if chars[room].is_whitespace() {
13307            room
13308        } else {
13309            chars[..room]
13310                .iter()
13311                .rposition(|c| c.is_whitespace())
13312                .unwrap_or(room)
13313        };
13314        let head: String = chars[..cut].iter().collect();
13315        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13316        (head.to_owned(), "...")
13317    };
13318    if kept.is_empty() {
13319        return None;
13320    }
13321    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13322        return None;
13323    }
13324    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13325        return None;
13326    }
13327    Some(format!("{kept}{mark}"))
13328}
13329
13330/// The char length of the first sentence of `chars` when it ends within `max`
13331/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13332/// abbreviations so `e.g. foo` does not end a title early.
13333fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13334    const MIN: usize = 20;
13335    for i in MIN..max.min(chars.len()) {
13336        if !matches!(chars[i], '.' | '!' | '?') {
13337            continue;
13338        }
13339        let Some(&next) = chars.get(i + 1) else {
13340            continue;
13341        };
13342        if !next.is_whitespace() {
13343            continue;
13344        }
13345        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13346        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13347            continue;
13348        }
13349        let word: String = chars[..i]
13350            .iter()
13351            .rev()
13352            .take_while(|c| !c.is_whitespace())
13353            .collect::<Vec<_>>()
13354            .into_iter()
13355            .rev()
13356            .collect();
13357        let word = word.to_ascii_lowercase();
13358        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13359            continue;
13360        }
13361        let end = chars[..i]
13362            .iter()
13363            .rposition(|c| !c.is_whitespace())
13364            .map_or(i, |p| p + 1);
13365        return Some(end);
13366    }
13367    None
13368}
13369
13370/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13371/// change: a title and a body describing what was *implemented*, not the task
13372/// that asked for it. A task reads as a request; a reader of the merged
13373/// history wants the change.
13374struct PrMessage {
13375    title: String,
13376    body: String,
13377}
13378
13379impl PrMessage {
13380    /// Title, blank line, body. The first line is the squash/merge commit
13381    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13382    /// has to stay one sensible line.
13383    fn commit_message(&self) -> String {
13384        format!("{}\n\n{}", self.title, self.body)
13385    }
13386}
13387
13388/// The text after a leading `TITLE:` (any case) on `line`.
13389fn title_marker(line: &str) -> Option<&str> {
13390    let line = line.trim();
13391    let head = line.get(..6)?;
13392    head.eq_ignore_ascii_case("title:")
13393        .then(|| line[6..].trim())
13394}
13395
13396/// The implementer's own one-line title: the `TITLE:` line the implement
13397/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13398/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13399/// source, and a title that says as much is refused here too.
13400fn summary_title(summary: &str) -> Option<String> {
13401    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13402    let raw = title_marker(first)?;
13403    if raw.is_empty() {
13404        return None;
13405    }
13406    let title = queue::title_from(raw, PR_TITLE_MAX);
13407    let lower = title.to_ascii_lowercase();
13408    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13409        return None;
13410    }
13411    Some(title)
13412}
13413
13414/// How `open_review`'s instruction begins; see [`landing_title`].
13415const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13416
13417/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13418pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13419
13420/// Does this run review work that already existed, rather than implement a
13421/// task? Runs recorded before `reviewed_commits` existed carry only the
13422/// candidate marker.
13423pub(crate) fn is_review_run(state: &RunState) -> bool {
13424    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13425}
13426
13427/// The title of a review-only run: the subject of the oldest commit under
13428/// review. Later commits are usually fixups, and `instruction` is the review
13429/// prompt, which says nothing about the change. GitHub text is English, so a
13430/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13431fn review_title(state: &RunState) -> Option<String> {
13432    english_subject(
13433        state.reviewed_commits.as_ref()?.first()?,
13434        state.config.graph.github_english(),
13435    )
13436}
13437
13438/// `raw` as a pull request title, or `None` when it is blank, not English
13439/// (GitHub text is), or one of magi's own candidate commit subjects.
13440fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13441    let raw = raw.trim();
13442    if raw.is_empty() {
13443        return None;
13444    }
13445    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13446        return None;
13447    }
13448    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13449        return None;
13450    }
13451    let title = queue::title_from(raw, PR_TITLE_MAX);
13452    let lower = title.to_ascii_lowercase();
13453    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13454        return None;
13455    }
13456    Some(title)
13457}
13458
13459/// What a review-only run's branch says about itself, read at the moment the
13460/// pull request is opened.
13461#[derive(Debug, Clone, PartialEq, Eq)]
13462struct BranchFacts {
13463    /// `(subject, body)` of each commit, oldest first.
13464    commits: Vec<(String, String)>,
13465    /// Trimmed `git diff --stat`.
13466    stat: String,
13467}
13468
13469/// Longest diff stat shown: this many file lines plus the summary line.
13470const STAT_FILE_LINES: usize = 25;
13471/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13472const COMMITS_MAX_CHARS: usize = 20_000;
13473
13474/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13475/// say or finds nothing, so the caller falls back to what the run recorded.
13476async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13477    let commits = git::commit_log(repo, base, branch).await.ok()?;
13478    if commits.is_empty() {
13479        return None;
13480    }
13481    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13482    let lines: Vec<&str> = stat.lines().collect();
13483    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13484        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13485        let more = format!(" ... {omitted} more file(s)");
13486        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13487        kept.push(&more);
13488        kept.push(lines[lines.len() - 1]);
13489        kept.join("\n")
13490    } else {
13491        lines.join("\n")
13492    };
13493    Some(BranchFacts { commits, stat })
13494}
13495
13496/// Defang what would break the surrounding markdown: a closing `</details>`
13497/// and a code fence.
13498fn markdown_safe(text: &str) -> String {
13499    text.replace("</details>", "&lt;/details&gt;")
13500        .replace("\x60\x60\x60", "~~~")
13501}
13502
13503fn neutral_title(state: &RunState, winner: char) -> String {
13504    format!(
13505        "chore: land candidate {} of run {}",
13506        winner.to_ascii_uppercase(),
13507        state.id
13508    )
13509}
13510
13511/// Reuse the graph's bounded fixer without starting another graph or driver.
13512/// Copy the working state back even on errors so spent rounds remain visible.
13513pub(crate) async fn repair_landing_gate(
13514    state: &mut RunState,
13515    winner: &Candidate,
13516    outcomes: &[CommandOutcome],
13517) -> Result<GateFix> {
13518    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13519        return Ok(GateFix::Stop);
13520    }
13521    let mut runner = Runner {
13522        roles: state.config.resolve_roles()?,
13523        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13524        state: state.clone(),
13525        pause: Pause::new(),
13526        interrupt: Pause::new(),
13527    };
13528    let result = runner.gate_fix_round(winner, outcomes).await;
13529    *state = runner.state;
13530    result
13531}
13532
13533/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13534/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13535pub(crate) async fn verify_current_head(
13536    state: &mut RunState,
13537    winner: &Candidate,
13538    wait: &crate::repo_lock::WaitPolicy,
13539) -> Result<bool> {
13540    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13541    // Preserve the previous record before replacing it, including on crash recovery.
13542    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13543        state
13544            .verification_history
13545            .push(crate::run::VerificationEvidence {
13546                superseded_by: Some(head.clone()),
13547                archived_at: Some(Timestamp::now()),
13548                fixes_spent: Some(state.gate_fixes.len()),
13549                gate_head: None,
13550                gate_ran: false,
13551                gate: Vec::new(),
13552                e2e: state.head_e2e.take(),
13553            });
13554    }
13555    if let Some(e) = &state.head_e2e
13556        && e.head == head
13557    {
13558        if e.passed {
13559            return Ok(true);
13560        }
13561        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13562            state.status = RunStatus::Blocked;
13563            state.save()?;
13564            return Ok(false);
13565        }
13566    } else if state.reviews.last().is_some_and(|r| {
13567        r.verified_head.as_deref() == Some(head.as_str())
13568            && (r.e2e_status() == E2eStatus::Passed
13569                || (r.e2e_status() == E2eStatus::NotConfigured
13570                    && state.config.verify.e2e.is_empty()))
13571    }) || state
13572        .gate_repair_e2e
13573        .as_ref()
13574        .is_some_and(|e| e.head == head && e.passed)
13575    {
13576        return Ok(true);
13577    }
13578    if let Some(e) = &state.gate_repair_e2e
13579        && e.head == head
13580        && !e.passed
13581        && !e.outcomes.is_empty()
13582        && !verify_inconclusive(&e.outcomes)
13583    {
13584        state.status = RunStatus::Blocked;
13585        state.save()?;
13586        return Ok(false);
13587    }
13588    // Bind the result to the base used by the candidate, not a tracking ref
13589    // that the background fetch can advance independently of verification.
13590    let base_commit = state
13591        .base_sync
13592        .as_ref()
13593        .map(|s| s.tip.clone())
13594        .filter(|tip| !tip.is_empty())
13595        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13596    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13597        head.clone(),
13598        false,
13599        Vec::new(),
13600    ));
13601    state.save()?;
13602    let commands = state.config.verify.e2e.clone();
13603    let shell = state.config.shell();
13604    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13605    let cache_dir = state.config.cache_dir();
13606    let outcomes = if commands.is_empty() {
13607        Vec::new()
13608    } else {
13609        let (outcomes, _) = with_cache_lease(
13610            state,
13611            cache_dir.as_deref(),
13612            "e2e",
13613            "e2e",
13614            &winner.worktree,
13615            &head,
13616            timeout,
13617            "current head e2e",
13618            wait,
13619            |state, budget| async move {
13620                run_e2e_with_retry(
13621                    state,
13622                    &shell,
13623                    &commands,
13624                    &winner.worktree,
13625                    budget,
13626                    "current head e2e",
13627                    None,
13628                )
13629                .await
13630            },
13631        )
13632        .await?;
13633        outcomes
13634    };
13635    let unresolved = verify_inconclusive(&outcomes);
13636    let passed = !unresolved
13637        && outcomes.iter().all(CommandOutcome::ok)
13638        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13639    if !outcomes.is_empty() && !unresolved {
13640        state.record_base_progress(&head);
13641    }
13642    let generation = Some(state.verification_history.len());
13643    let pass = state.passes.last().map(|p| p.index);
13644    let recorded_at = Some(Timestamp::now());
13645    let resumption_generation = state.entry_resumption_generation;
13646    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13647    record.base_commit = base_commit;
13648    record.generation = generation;
13649    record.pass = pass;
13650    record.recorded_at = recorded_at;
13651    record.resumption_generation = resumption_generation;
13652    if !passed && !unresolved {
13653        let detail = state
13654            .head_e2e
13655            .as_ref()
13656            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13657            .map(|d| format!(" ({d})"))
13658            .unwrap_or_default();
13659        state.status = RunStatus::Blocked;
13660        state.event(
13661            "e2e",
13662            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13663        );
13664        record.recorded_events = Some(state.events.len());
13665    }
13666    state.head_e2e = Some(record);
13667    state.save()?;
13668    Ok(passed)
13669}
13670
13671/// Recheck a repair's e2e requirement across failures, resource deferrals and
13672/// process interruptions. A successful result only applies to its exact SHA.
13673pub(crate) async fn check_gate_repair_e2e(
13674    state: &mut RunState,
13675    winner: &Candidate,
13676    wait: &crate::repo_lock::WaitPolicy,
13677) -> Result<GateFix> {
13678    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13679        return Ok(GateFix::Retry);
13680    }
13681    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13682    if let Some(record) = &state.gate_repair_e2e
13683        && record.head == head
13684    {
13685        if record.passed {
13686            return Ok(GateFix::Retry);
13687        }
13688        if !record.outcomes.is_empty()
13689            && record.outcomes.iter().all(|o| {
13690                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13691            })
13692        {
13693            return Ok(GateFix::Stop);
13694        }
13695    }
13696    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13697        head.clone(),
13698        false,
13699        Vec::new(),
13700    ));
13701    state.save()?;
13702    let commands = state.config.verify.e2e.clone();
13703    let outcomes = if commands.is_empty() {
13704        Vec::new()
13705    } else {
13706        let shell = state.config.shell();
13707        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13708        let cache_dir = state.config.cache_dir();
13709        let (outcomes, _) = with_cache_lease(
13710            state,
13711            cache_dir.as_deref(),
13712            "e2e",
13713            "e2e",
13714            &winner.worktree,
13715            &head,
13716            timeout,
13717            "gate repair e2e",
13718            wait,
13719            |state, budget| async move {
13720                run_e2e_with_retry(
13721                    state,
13722                    &shell,
13723                    &commands,
13724                    &winner.worktree,
13725                    budget,
13726                    "gate repair e2e",
13727                    None,
13728                )
13729                .await
13730            },
13731        )
13732        .await?;
13733        outcomes
13734    };
13735    let deferred = verify_inconclusive(&outcomes);
13736    let passed = outcomes.iter().all(CommandOutcome::ok)
13737        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13738    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
13739    state.save()?;
13740    if deferred {
13741        Ok(GateFix::Defer)
13742    } else if !passed {
13743        let detail = state
13744            .gate_repair_e2e
13745            .as_ref()
13746            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13747            .map(|d| format!(" ({d})"))
13748            .unwrap_or_default();
13749        state.event(
13750            "gate",
13751            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13752        );
13753        Ok(GateFix::Stop)
13754    } else {
13755        Ok(GateFix::Retry)
13756    }
13757}
13758
13759/// Run the same configured gate for a landing head and a fresh graph.
13760pub(crate) async fn run_landing_gate(
13761    state: &mut RunState,
13762    winner: &Candidate,
13763    wait: &crate::repo_lock::WaitPolicy,
13764) -> Result<Vec<CommandOutcome>> {
13765    let shell = state.config.shell();
13766    let gate_commands = state.config.verify.gate.clone();
13767    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13768    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13769        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13770        Vec::new()
13771    } else {
13772        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13773        let cache_dir = state.config.cache_dir();
13774        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13775        let (outcomes, _) = with_cache_lease(
13776            state,
13777            cache_dir.as_deref(),
13778            "gate",
13779            "gate",
13780            &winner.worktree,
13781            &head,
13782            timeout,
13783            "final gate",
13784            wait,
13785            |state, budget| {
13786                let shell = shell.clone();
13787                let gate_commands = gate_commands.clone();
13788                let winner = winner.clone();
13789                async move {
13790                    Runner::run_pre_gate(state, &winner).await;
13791                    // Bind command evidence after mechanical fixes, before commands start.
13792                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13793                    let (outcomes, timed_out_pids) = run_commands(
13794                        state,
13795                        "gate",
13796                        "gate",
13797                        0,
13798                        &shell,
13799                        &gate_commands,
13800                        &winner.worktree,
13801                        budget,
13802                    )
13803                    .await;
13804                    (outcomes, false, timed_out_pids)
13805                }
13806            },
13807        )
13808        .await?;
13809        outcomes
13810    };
13811    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13812    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13813        let mut outcomes = outcomes;
13814        outcomes.push(CommandOutcome {
13815            command: "gate head stability".into(), code: None,
13816            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13817            duration_ms: 0, resource_blocked: false,
13818            ..Default::default()
13819        });
13820        return Ok(outcomes);
13821    }
13822    if outcomes.is_empty() {
13823        // Nothing configured to check — distinct from every other
13824        // silence in this run's event log, since an empty `gate` alone
13825        // no longer says whether the gate ran at all (see
13826        // `RunState::gate_ran`'s own doc).
13827        state.event("gate", "no gate commands configured; not tested");
13828    }
13829    for o in &outcomes {
13830        state.event(
13831            "gate",
13832            format!(
13833                "`{}` -> {}",
13834                o.command,
13835                if o.ok() {
13836                    "pass".to_owned()
13837                } else {
13838                    format!(
13839                        "FAIL ({:?})\n{}",
13840                        o.code,
13841                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13842                    )
13843                }
13844            ),
13845        );
13846    }
13847    Ok(outcomes)
13848}
13849
13850/// The pull request title to hand to `land::merge_subject`. A review-only run
13851/// opened by an earlier build titled its pull request with the review prompt;
13852/// that title is dropped (empty, so the fallback applies) rather than landed.
13853/// Any other title, including an operator's rename, passes through untouched,
13854/// and so does every title of a run that implements a task.
13855pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13856    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13857        ""
13858    } else {
13859        pr_title
13860    }
13861}
13862
13863/// What the squash subject falls back to when the pull request title is empty
13864/// or candidate-shaped: for a review-only run the derived title, never the
13865/// review prompt held in `instruction`.
13866pub fn landing_subject_source(state: &RunState) -> String {
13867    if is_review_run(state) {
13868        let winner = state.candidates.first().map_or('A', |c| c.label);
13869        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13870    }
13871    state.instruction.clone()
13872}
13873
13874/// `summary` without its `TITLE:` line, which the pull request title already
13875/// carries.
13876fn summary_without_title(summary: &str) -> String {
13877    let mut lines = summary.trim().lines().peekable();
13878    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13879        lines.next();
13880    }
13881    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13882}
13883
13884/// The pull request title and body for the winning candidate.
13885///
13886/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13887/// the task's own opening line via [`queue::title_from`] when there is none.
13888/// `state.instruction` can open with blank lines (`task_text` only rejects a
13889/// body that is blank *entirely*), which `title_from` skips.
13890///
13891/// Publishing uses an independent description generated from the final diff
13892/// and structured evidence. Internal summaries and reports remain local.
13893/// Non-publishing previews may display the original task and candidate summary.
13894/// The footer retains the run and candidate provenance.
13895#[cfg(test)]
13896fn pr_message(state: &RunState, winner: char) -> PrMessage {
13897    pr_message_with(state, winner, None)
13898}
13899
13900/// [`pr_message`] with what the branch of a review-only run says about itself.
13901/// `facts` is ignored for a run that implements a task.
13902#[cfg(test)]
13903fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13904    let raw = pr_message_raw(
13905        state,
13906        winner,
13907        facts,
13908        crate::pr_outcome::FinalHead::Unreported,
13909        ChangeNote::NotAsked,
13910    );
13911    let id = crate::scrub::Identity::current();
13912    PrMessage {
13913        title: crate::scrub::scrub(&raw.title, &id),
13914        body: crate::scrub::scrub(&raw.body, &id),
13915    }
13916}
13917
13918/// What the public description may say about the change itself.
13919#[derive(Debug, Clone, Copy)]
13920enum ChangeNote<'a> {
13921    /// A local preview or non-publishing merge mode: no public generation needed.
13922    NotAsked,
13923    /// A summary written from the final diff.
13924    Summary(&'a crate::run::ChangeSummary),
13925    /// A summary was asked for and could not be produced; the text says why.
13926    Unavailable(&'a str),
13927}
13928
13929fn pr_message_raw(
13930    state: &RunState,
13931    winner: char,
13932    facts: Option<&BranchFacts>,
13933    head: crate::pr_outcome::FinalHead<'_>,
13934    change: ChangeNote<'_>,
13935) -> PrMessage {
13936    if !matches!(change, ChangeNote::NotAsked) {
13937        let (title, mut body) = match change {
13938            ChangeNote::Summary(c) => (
13939                c.title.clone(),
13940                format!("## Summary\n\n{}\n\n", c.body.trim()),
13941            ),
13942            ChangeNote::Unavailable(why) => (
13943                neutral_title(state, winner),
13944                format!(
13945                    "## 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"
13946                ),
13947            ),
13948            ChangeNote::NotAsked => unreachable!(),
13949        };
13950        body.push_str(&public_pr_evidence(state, head));
13951        body.push_str(&format!(
13952            "\n---\nmagi:run/{} magi:candidate-{}\n",
13953            state.id,
13954            winner.to_ascii_lowercase()
13955        ));
13956        return PrMessage { title, body };
13957    }
13958    pr_preview(state, winner, facts, head)
13959}
13960
13961/// Append public facts from the run records after every prose generation,
13962/// including posting-gate rewrites. The agent cannot drop this provenance.
13963fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13964    let mut body = crate::pr_outcome::review_rounds(state);
13965    body.push_str(&crate::pr_outcome::final_verification(state, head));
13966    let open = state.last_round_findings();
13967    if !open.is_empty() {
13968        body.push_str("## Open review findings\n\n");
13969        for f in open {
13970            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13971        }
13972        body.push('\n');
13973    }
13974    if let Some(c) = state.change_summary.as_ref()
13975        && head == crate::pr_outcome::FinalHead::At(&c.head)
13976    {
13977        body.push_str(&format!(
13978            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13979            c.base, c.head
13980        ));
13981    }
13982    body
13983}
13984
13985/// Local-only preview of the operator's task and candidate summary.
13986fn pr_preview(
13987    state: &RunState,
13988    winner: char,
13989    facts: Option<&BranchFacts>,
13990    head: crate::pr_outcome::FinalHead<'_>,
13991) -> PrMessage {
13992    let summary = state
13993        .candidates
13994        .iter()
13995        .find(|c| c.label == winner)
13996        .map(|c| c.summary.as_str())
13997        .unwrap_or_default();
13998    // The fallback is the operator's own words and may not be English; GitHub
13999    // text always is, so a non-English task gets a neutral title instead.
14000    let review = is_review_run(state);
14001    let title = if review {
14002        facts
14003            .and_then(|f| {
14004                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14005            })
14006            .or_else(|| review_title(state))
14007            .or_else(|| {
14008                state
14009                    .candidates
14010                    .iter()
14011                    .find(|c| c.label == winner)
14012                    .filter(|c| !c.branch.starts_with("magi/"))
14013                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14014            })
14015            .unwrap_or_else(|| neutral_title(state, winner))
14016    } else {
14017        summary_title(summary).unwrap_or_else(|| {
14018            english_title(
14019                &state.instruction,
14020                PR_TITLE_MAX,
14021                state.config.graph.github_english(),
14022            )
14023            .unwrap_or_else(|| neutral_title(state, winner))
14024        })
14025    };
14026
14027    let mut body = String::new();
14028    let what = summary_without_title(summary);
14029    if !what.is_empty() {
14030        body.push_str("## Summary\n\n");
14031        body.push_str(&what);
14032        body.push_str("\n\n");
14033    }
14034
14035    // Review history uses structured facts across all rounds, never reports.
14036    body.push_str(&crate::pr_outcome::review_rounds(state));
14037    body.push_str(&crate::pr_outcome::final_verification(state, head));
14038    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14039
14040    let open = state.open_findings();
14041    if !open.is_empty() {
14042        body.push_str("## Open review findings\n\n");
14043        for f in &open {
14044            body.push_str(&format!(
14045                "- `{}` [{:?}] {}\n",
14046                f.id, f.severity, "Context retained in local review records."
14047            ));
14048        }
14049        body.push('\n');
14050    }
14051
14052    if let Some(fix) = fix
14053        && !fix.rejected.is_empty()
14054    {
14055        body.push_str("## Declined by the fixer\n\n");
14056        for r in &fix.rejected {
14057            body.push_str(&format!(
14058                "- `{}`: {}\n",
14059                r.id, "Reason retained in local review records."
14060            ));
14061        }
14062        body.push('\n');
14063    }
14064
14065    if review {
14066        // The review prompt is not the task; list what the branch carries.
14067        body.push_str("## Commits under review\n\n");
14068        if let Some(facts) = facts {
14069            let mut left = COMMITS_MAX_CHARS;
14070            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14071                let mut entry = format!("- {}\n", markdown_safe(subject));
14072                for l in markdown_safe(text).lines() {
14073                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14074                }
14075                if left == 0 {
14076                    body.push_str(&format!(
14077                        "- ... {} more commit(s)\n",
14078                        facts.commits.len() - i
14079                    ));
14080                    break;
14081                }
14082                if entry.len() > left {
14083                    // Even the first commit is cut: one huge body must not
14084                    // push the whole description past GitHub's limit.
14085                    let mut end = left;
14086                    while !entry.is_char_boundary(end) {
14087                        end -= 1;
14088                    }
14089                    entry.truncate(end);
14090                    entry.push_str("\n  ... (truncated)\n");
14091                    left = 0;
14092                } else {
14093                    left -= entry.len();
14094                }
14095                body.push_str(&entry);
14096            }
14097            if !facts.stat.trim().is_empty() {
14098                body.push_str(&format!(
14099                    "\n## Diff stat\n\n```\n{}\n```\n",
14100                    markdown_safe(facts.stat.trim())
14101                ));
14102            }
14103        } else {
14104            match &state.reviewed_commits {
14105                Some(subjects) => {
14106                    for s in subjects {
14107                        body.push_str(&format!("- {}\n", s.trim()));
14108                    }
14109                }
14110                None => {
14111                    // An older run kept only the prompt, with the commit list
14112                    // after its first paragraph.
14113                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14114                    body.push_str(rest.trim());
14115                    body.push('\n');
14116                }
14117            }
14118        }
14119    } else {
14120        let task = state.instruction.trim();
14121        let task = if task.is_empty() {
14122            "(empty task)"
14123        } else {
14124            task
14125        };
14126        body.push_str(&format!(
14127            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14128            task.replace("</details>", "&lt;/details&gt;")
14129        ));
14130    }
14131
14132    body.push_str(&format!(
14133        "\n---\nmagi:run/{} magi:candidate-{}\n",
14134        state.id,
14135        winner.to_ascii_lowercase()
14136    ));
14137
14138    PrMessage { title, body }
14139}
14140
14141/// Source imports have already been prepared from structured inputs. Legacy
14142/// inferred references must never instruct a seat to reconstruct those imports.
14143fn seeded_instruction(state: &RunState) -> String {
14144    let mut inputs = Vec::new();
14145    if let Some(start) = &state.sources.start_from {
14146        inputs.push(format!(
14147            "Start from `{}` at `{}` (including ancestry).",
14148            start.token, start.sha
14149        ));
14150    }
14151    for pick in &state.sources.pick_commits {
14152        inputs.push(format!(
14153            "Pick `{}` at `{}` (single commit).",
14154            pick.token, pick.sha
14155        ));
14156    }
14157    if inputs.is_empty() {
14158        state.instruction.clone()
14159    } else {
14160        format!(
14161            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14162            state.instruction,
14163            inputs.join("\n")
14164        )
14165    }
14166}
14167
14168/// Does the winner have no commits ahead of the base it would land on?
14169/// Any failure to find out reads as "not empty": the merge then behaves as it
14170/// always did rather than refusing on a guess.
14171async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14172    let base = &state.base_branch;
14173    let mut against = base.clone();
14174    if mode == MergeMode::Pr {
14175        // A pull request lands on the remote's base, never the local branch
14176        // of the same name: if that cannot be read, "not empty" is the safe
14177        // answer.
14178        let remote = &state.config.merge.remote;
14179        let tracking = format!("{remote}/{base}");
14180        let fetched = git::fetch(repo, remote, base).await;
14181        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14182            against = tracking;
14183        } else {
14184            return false;
14185        }
14186    }
14187    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14188}
14189
14190/// Why nothing was opened for an empty winner, with what the task's own
14191/// references resolved to.
14192fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14193    let mut detail = format!(
14194        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14195         nothing to open a pull request for"
14196    );
14197    detail.push_str(
14198        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14199    );
14200    detail
14201}
14202
14203/// What the `Pr` merge does once it knows whether the branch already has an
14204/// open pull request.
14205#[derive(Debug, PartialEq, Eq)]
14206enum PrPlan {
14207    Create,
14208    Adopt { url: String, title: String },
14209    Stop(String),
14210}
14211
14212/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14213/// a failed lookup -> stop with the real reason. Never guesses.
14214fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14215    match found {
14216        Ok(land::OpenPr::None) => PrPlan::Create,
14217        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14218        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14219            "several open pull requests exist for this branch, not picking one: {}",
14220            urls.join(" ")
14221        )),
14222        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14223    }
14224}
14225
14226/// `gh pr create`, returning the PR url.
14227pub(crate) async fn gh_pr_create(
14228    cwd: &Path,
14229    base: &str,
14230    head: &str,
14231    title: &str,
14232    body: &str,
14233) -> Result<String> {
14234    let out = tokio::process::Command::new("gh")
14235        .args([
14236            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14237        ])
14238        .current_dir(cwd)
14239        .quiet()
14240        .stdin(std::process::Stdio::null())
14241        .output()
14242        .await
14243        .context("spawn gh")?;
14244    if out.status.success() {
14245        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14246    } else {
14247        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14248    }
14249}
14250
14251/// Never force deletion of uncommitted work, including unknown legacy trees.
14252async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14253    match std::fs::symlink_metadata(path) {
14254        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14255            // A previous cleanup may have removed the tree before a branch
14256            // deletion or state save failed. Unregister it if still present.
14257            git::worktree_remove_clean(repo, path).await?;
14258            return Ok(());
14259        }
14260        Err(e) => return Err(e.into()),
14261        Ok(_) => {}
14262    }
14263    if !git::is_clean(path).await? {
14264        bail!(
14265            "worktree has uncommitted work; refusing removal: {}",
14266            path.display()
14267        );
14268    }
14269    if !git::worktree_remove_clean(repo, path).await? {
14270        bail!("worktree removal refused: {}", path.display());
14271    }
14272    Ok(())
14273}
14274
14275/// Read seats return replies, not working-tree changes. Only registered,
14276/// detached seats directly inside this run's root may discard those changes.
14277async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14278    if !crate::retention::read_seat(path) || !path.exists() {
14279        return remove_preserved_worktree(&state.repo, path).await;
14280    }
14281    let owned = std::fs::symlink_metadata(path)?.is_dir()
14282        && path.parent().map(Path::canonicalize).transpose()?
14283            == Some(state.worktree_root().canonicalize()?)
14284        && crate::retention::worktrees(state)
14285            .await?
14286            .contains(&path.canonicalize()?);
14287    let common = crate::repo_lock::common_dir(&state.repo).await?;
14288    if !owned
14289        || common.is_none()
14290        || crate::repo_lock::common_dir(path).await? != common
14291        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14292            .await?
14293            .ok()
14294        || state.candidates.iter().any(|c| c.worktree == path)
14295    {
14296        return remove_preserved_worktree(&state.repo, path).await;
14297    }
14298    let changes = git::status_porcelain(path).await?;
14299    if !git::worktree_remove(&state.repo, path).await? {
14300        bail!(
14301            "read-only seat worktree removal refused: {}",
14302            path.display()
14303        );
14304    }
14305    if !changes.is_empty() {
14306        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14307        let paths: String = paths.chars().take(1024).collect();
14308        state.event(
14309            "fold",
14310            format!(
14311                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14312                path.file_name().unwrap_or_default().to_string_lossy(),
14313                changes.lines().count()
14314            ),
14315        );
14316    }
14317    Ok(())
14318}
14319
14320fn fold_target(
14321    home: &Path,
14322    root: &Path,
14323    path: &Path,
14324    isolated: bool,
14325) -> Option<crate::build_target::FoldTarget> {
14326    if !isolated {
14327        return None;
14328    }
14329    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14330        Ok(target) => target,
14331        Err(error) => {
14332            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14333            None
14334        }
14335    }
14336}
14337
14338fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14339    if let Some(target) = target
14340        && let Err(error) = target.reclaim_orphaned_target(home)
14341    {
14342        tracing::warn!(%error, "isolated target retained after fold");
14343    }
14344}
14345
14346/// Tear a run's worktrees and branches down.
14347///
14348/// `home` is where the updated `run.json` is saved (via
14349/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14350/// a housekeeping pass already has its own honest `home` handed to it, and
14351/// falling through to the global here would write back through whichever
14352/// directory some other process or test pinned into that `OnceLock` first,
14353/// not the one the caller actually resolved its `runs` and `state` from.
14354pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14355    fold_run_with_policy(state, drop_winner, home, false).await
14356}
14357
14358/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14359pub async fn fold_run_overriding_recovery_retention(
14360    state: &mut RunState,
14361    drop_winner: bool,
14362    home: &Path,
14363) -> Result<Vec<String>> {
14364    fold_run_with_policy(state, drop_winner, home, true).await
14365}
14366
14367async fn fold_run_with_policy(
14368    state: &mut RunState,
14369    drop_winner: bool,
14370    home: &Path,
14371    override_recovery_retention: bool,
14372) -> Result<Vec<String>> {
14373    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14374        && !override_recovery_retention
14375    {
14376        bail!("refusing fold: {reason}");
14377    }
14378    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14379        bail!("candidate preservation incomplete; refusing cleanup");
14380    }
14381    // Serialize ordinary folding with the same starts/resumes as target-only
14382    // eviction. Otherwise a second janitor could remove the whole worktree
14383    // around a live output borrower even though target eviction was fenced.
14384    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
14385    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
14386    // An override must use current durable ownership, not a pre-lock snapshot.
14387    if override_recovery_retention {
14388        *state = RunState::load_under(&state.id, home)?;
14389        anyhow::ensure!(
14390            state.status.done() && !state.status.resumable(),
14391            "recovery retention override requires a finished, non-resumable run"
14392        );
14393        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
14394        anyhow::ensure!(
14395            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14396            "run is live or its ownership is unknown"
14397        );
14398        anyhow::ensure!(
14399            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
14400            "candidate preservation incomplete; refusing cleanup"
14401        );
14402    }
14403    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14404    if let Some(reason) = &retention_reason
14405        && !override_recovery_retention
14406    {
14407        bail!("refusing fold: {reason}");
14408    }
14409    let _driver = crate::driver::maintenance(home, &state.id)?;
14410    let mut output_guards = Vec::new();
14411    for entry in std::fs::read_dir(state.worktree_root())
14412        .into_iter()
14413        .flatten()
14414        .flatten()
14415    {
14416        if entry.path().join(".git").is_file() {
14417            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
14418        }
14419    }
14420    let repo = state.repo.clone();
14421    // CLI, Web and automatic cleanup all enter here, independently of
14422    // Runner::fold_losers. Protect deletion and shared config release too.
14423    let wait = repository_wait(state, None);
14424    let _coordination = match coordinate_operation(state, &repo, &wait).await {
14425        Ok(lease) => lease,
14426        Err(e) => {
14427            state.save_under(home)?;
14428            return Err(e);
14429        }
14430    };
14431    // Confirmed merges dispose of their owned sources after durable evidence
14432    // capture. Preflight every source before removing anything.
14433    let _source_outputs = if retention_reason.is_some()
14434        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14435    {
14436        verify_merged_fold_sources(state, drop_winner, home).await?
14437    } else {
14438        Vec::new()
14439    };
14440    if let Some(reason) = retention_reason {
14441        state.event(
14442            "fold",
14443            format!(
14444                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14445                state.id
14446            ),
14447        );
14448        state.save_under(home)?;
14449    }
14450    let root = state.worktree_root();
14451    let winner = state.tally.as_ref().map(|t| t.winner);
14452    let mut removed = Vec::new();
14453    let isolated = crate::build_target::isolated(&state.config);
14454
14455    for i in 0..state.candidates.len() {
14456        let c = state.candidates[i].clone();
14457        let is_winner = Some(c.label) == winner;
14458        if is_winner && !drop_winner {
14459            continue;
14460        }
14461        let existed = c.worktree.exists();
14462        let target = fold_target(home, &root, &c.worktree, isolated);
14463        // A vanished directory can still have a Git registration that keeps
14464        // its branch checked out. Remove that registration before the branch.
14465        remove_preserved_worktree(&repo, &c.worktree).await?;
14466        reclaim_fold_target(home, target);
14467        if existed {
14468            removed.push(c.worktree.to_string_lossy().into_owned());
14469        }
14470        // A branch handed to a later run (and its pull request) is not this
14471        // run's to delete.
14472        let handed_over = state.released_branches.contains(&c.branch);
14473        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14474            if !git::branch_delete(&repo, &c.branch).await? {
14475                bail!("candidate branch removal refused");
14476            }
14477            removed.push(c.branch.clone());
14478        }
14479        state.candidates[i].folded = true;
14480    }
14481
14482    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14483        let path = name.path();
14484        let keep = !drop_winner
14485            && winner.is_some_and(|w| {
14486                path.file_name()
14487                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14488            });
14489        if keep {
14490            continue;
14491        }
14492        let target = fold_target(home, &root, &path, isolated);
14493        remove_read_seat_worktree(state, &path).await?;
14494        reclaim_fold_target(home, target);
14495        removed.push(path.to_string_lossy().into_owned());
14496    }
14497
14498    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14499    // judge worktrees, so once the loop above has cleared all of them out,
14500    // the parent is a bare directory nobody else was ever going to remove -
14501    // git only ever managed what was inside it. Left alone, one of these
14502    // accumulates per fully-folded run; the operator's own machine had 74.
14503    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14504    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14505    // so does anything a run never claimed that happens to share the bay.
14506    remove_if_empty(&root);
14507
14508    if state.enabled_worktree_config && drop_winner {
14509        // A release, not a raw disable: some sibling run in this repository
14510        // may still hold its own reference (see `git::acquire_worktree_config`),
14511        // and only the last release actually turns the setting back off.
14512        git::release_worktree_config(&repo).await.ok();
14513        state.enabled_worktree_config = false;
14514    }
14515    state.save_under(home)?;
14516    Ok(removed)
14517}
14518
14519async fn verify_merged_fold_sources(
14520    state: &RunState,
14521    drop_winner: bool,
14522    home: &Path,
14523) -> Result<Vec<std::fs::File>> {
14524    let winner = state.tally.as_ref().map(|t| t.winner);
14525    let mut heads = BTreeSet::new();
14526    for candidate in &state.candidates {
14527        if Some(candidate.label) == winner && !drop_winner {
14528            continue;
14529        }
14530        anyhow::ensure!(
14531            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14532            "candidate recovery source is outside the inventoried run root: {}",
14533            candidate.worktree.display()
14534        );
14535        match std::fs::symlink_metadata(&candidate.worktree) {
14536            Ok(_) => {}
14537            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14538            Err(error) => return Err(error.into()),
14539        }
14540        if !state.released_branches.contains(&candidate.branch)
14541            && git::branch_exists(&state.repo, &candidate.branch).await?
14542        {
14543            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14544        }
14545    }
14546    let mut cargo_guards = Vec::new();
14547    let entries = match std::fs::read_dir(state.worktree_root()) {
14548        Ok(entries) => Some(entries),
14549        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14550        Err(error) => return Err(error.into()),
14551    };
14552    for entry in entries.into_iter().flatten() {
14553        let path = entry?.path();
14554        let metadata = std::fs::symlink_metadata(&path)?;
14555        anyhow::ensure!(
14556            metadata.is_dir() && !metadata.file_type().is_symlink(),
14557            "non-directory or symlink recovery source retained: {}",
14558            path.display()
14559        );
14560        if !drop_winner
14561            && winner.is_some_and(|w| {
14562                path.file_name()
14563                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14564            })
14565        {
14566            continue;
14567        }
14568        anyhow::ensure!(
14569            path.join(".git").is_file(),
14570            "unregistered recovery source retained: {}",
14571            path.display()
14572        );
14573        anyhow::ensure!(
14574            git::git(
14575                &path,
14576                &[
14577                    "status",
14578                    "--porcelain",
14579                    "--untracked-files=all",
14580                    "--ignored",
14581                    "--",
14582                    ".",
14583                    ":(exclude)target"
14584                ]
14585            )
14586            .await?
14587            .is_empty(),
14588            "source changes or ignored recovery files retained: {}",
14589            path.display()
14590        );
14591        match std::fs::symlink_metadata(path.join("target")) {
14592            Ok(_) => {
14593                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14594            }
14595            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14596            Err(error) => return Err(error.into()),
14597        }
14598        for checkpoint in [
14599            "rebase-merge",
14600            "rebase-apply",
14601            "sequencer",
14602            "CHERRY_PICK_HEAD",
14603            "MERGE_HEAD",
14604            "REBASE_HEAD",
14605            "REVERT_HEAD",
14606            "BISECT_LOG",
14607            "AUTO_MERGE",
14608            "MERGE_MSG",
14609        ] {
14610            let location = git::git(
14611                &path,
14612                &[
14613                    "rev-parse",
14614                    "--path-format=absolute",
14615                    "--git-path",
14616                    checkpoint,
14617                ],
14618            )
14619            .await?;
14620            anyhow::ensure!(
14621                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14622                if e.kind() == std::io::ErrorKind::NotFound),
14623                "Git recovery checkpoint retained: {checkpoint}"
14624            );
14625        }
14626        heads.insert(git::rev_parse(&path, "HEAD").await?);
14627    }
14628    crate::fold_evidence::preserve(state, home, &heads).await?;
14629
14630    Ok(cargo_guards)
14631}
14632
14633/// Remove `dir` if it exists and has nothing in it.
14634///
14635/// Best-effort and silent by design: a directory that is not empty (a run
14636/// whose winner is still parked there, a stray file some other process left)
14637/// is exactly the case this must refuse, and a directory that is already gone
14638/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14639/// already refuses a non-empty directory, so the emptiness check below is
14640/// belt, not suspenders - it is what keeps this from ever attempting the
14641/// removal in the case that matters, rather than trusting `remove_dir`'s
14642/// error path to have no side effects if it ever changed.
14643fn remove_if_empty(dir: &Path) {
14644    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14645        std::fs::remove_dir(dir).ok();
14646    }
14647}
14648
14649/// Severity of the worst open finding in the last review round, for reporting.
14650pub fn worst_open(state: &RunState) -> Option<Severity> {
14651    state
14652        .reviews
14653        .last()?
14654        .reviews
14655        .iter()
14656        .flat_map(|r| r.findings.iter())
14657        .map(|f| f.severity)
14658        .max()
14659}
14660
14661/// `[worktree] setup` hides its products per worktree, which needs
14662/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14663/// worktrees, like the hook's; every place that runs setup calls this first.
14664async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14665    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14666        git::acquire_worktree_config(repo).await?;
14667        state.enabled_worktree_config = true;
14668    }
14669    Ok(())
14670}
14671
14672#[cfg(test)]
14673mod tests {
14674    #[tokio::test]
14675    async fn launcher_base_fetch_requires_remote_success() {
14676        let tmp = tempfile::tempdir().unwrap();
14677        let repo = tmp.path().join("repo");
14678        let remote = tmp.path().join("remote");
14679        std::fs::create_dir(&repo).unwrap();
14680        std::fs::create_dir(&remote).unwrap();
14681        git::git(&remote, &["init", "--bare", "-b", "main"])
14682            .await
14683            .unwrap();
14684        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14685        git::git(
14686            &repo,
14687            &[
14688                "-c",
14689                "user.name=Fixture",
14690                "-c",
14691                "user.email=fixture@example.invalid",
14692                "commit",
14693                "--allow-empty",
14694                "-m",
14695                "fixture",
14696            ],
14697        )
14698        .await
14699        .unwrap();
14700        git::git(
14701            &repo,
14702            &["remote", "add", "origin", remote.to_str().unwrap()],
14703        )
14704        .await
14705        .unwrap();
14706        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14707        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14708        assert_eq!(
14709            resolve_base(&repo, "main", "origin", None)
14710                .await
14711                .unwrap()
14712                .commit,
14713            head
14714        );
14715        #[cfg(unix)]
14716        {
14717            let policy: crate::config::Coordination = toml::from_str(
14718                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14719            ).unwrap();
14720            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14721            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14722            let held = crate::repo_lock::SeatLease::operation_with(
14723                &repo,
14724                Some(&policy),
14725                &crate::repo_lock::WaitPolicy::default(),
14726            )
14727            .await
14728            .unwrap();
14729            assert!(held.is_some());
14730            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14731            tokio::pin!(fetch);
14732            assert!(
14733                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14734                    .await
14735                    .is_err()
14736            );
14737            assert!(
14738                !repo.join(".git/FETCH_HEAD").exists(),
14739                "no fetch before admission"
14740            );
14741            drop(held);
14742            let fetched = fetch.await.unwrap();
14743            assert_eq!(fetched.commit, head);
14744            assert_eq!(fetched.remote, "origin");
14745            assert_eq!(fetched.branch, "main");
14746        }
14747        // A surviving tracking ref is not successful fetch evidence.
14748        git::git(
14749            &repo,
14750            &[
14751                "remote",
14752                "set-url",
14753                "origin",
14754                tmp.path().join("missing").to_str().unwrap(),
14755            ],
14756        )
14757        .await
14758        .unwrap();
14759        let error = resolve_base(&repo, "main", "origin", None)
14760            .await
14761            .unwrap_err()
14762            .to_string();
14763        assert!(error.contains("cannot read origin/main"));
14764        assert!(error.contains("refusing to branch off"));
14765    }
14766
14767    #[test]
14768    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14769        let leaked = vec!["chore(deps): update a crate".to_owned()];
14770        let own = "fix(daemon): apply a chosen action";
14771        assert!(should_retitle("", own, &leaked));
14772        assert!(should_retitle(
14773            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14774            own,
14775            &leaked
14776        ));
14777        assert!(should_retitle(
14778            "chore: land candidate A of run 1",
14779            own,
14780            &leaked
14781        ));
14782        assert!(should_retitle(
14783            "magi: candidate A (uncommitted work)",
14784            own,
14785            &leaked
14786        ));
14787        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14788        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14789        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14790    }
14791
14792    #[test]
14793    fn pr_merge_plan_creates_adopts_or_stops() {
14794        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14795        assert_eq!(
14796            pr_merge_plan(Ok(land::OpenPr::One {
14797                url: "u".into(),
14798                title: "t".into()
14799            })),
14800            PrPlan::Adopt {
14801                url: "u".into(),
14802                title: "t".into()
14803            }
14804        );
14805        let PrPlan::Stop(many) =
14806            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14807        else {
14808            panic!("many must stop");
14809        };
14810        assert!(many.contains('a') && many.contains('b'));
14811        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14812            panic!("a failed lookup must stop");
14813        };
14814        assert!(err.contains("bad token"));
14815    }
14816
14817    use super::*;
14818    use crate::run::GateStatus;
14819    use std::collections::BTreeMap;
14820    use std::time::Duration;
14821
14822    fn conductor() -> AgentSpec {
14823        AgentSpec {
14824            id: "conductor".to_owned(),
14825            kind: crate::config::AgentKind::Command,
14826            model: None,
14827            command: vec!["true".to_owned()],
14828            extra_args: Vec::new(),
14829            env: BTreeMap::new(),
14830            prompt_delivery: None,
14831            max_turn_secs: None,
14832        }
14833    }
14834
14835    fn spec(id: &str) -> AgentSpec {
14836        AgentSpec {
14837            id: id.to_owned(),
14838            kind: crate::config::AgentKind::Command,
14839            model: None,
14840            command: vec!["true".to_owned()],
14841            extra_args: Vec::new(),
14842            env: BTreeMap::new(),
14843            prompt_delivery: None,
14844            max_turn_secs: None,
14845        }
14846    }
14847
14848    fn ids(xs: &[&str]) -> BTreeSet<String> {
14849        xs.iter().map(|s| (*s).to_owned()).collect()
14850    }
14851
14852    #[test]
14853    fn pick_successor_skips_an_agent_another_seat_holds() {
14854        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14855        let roster = [spec("a"), spec("b"), spec("c")];
14856        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14857        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14858    }
14859
14860    #[test]
14861    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14862        // The other seat started on c but was handed to d; c is free again.
14863        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14864        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14865        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14866        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14867        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14868    }
14869
14870    #[test]
14871    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14872        let roster = [spec("a"), spec("b")];
14873        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14874        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14875        let carried = ids(&["b"]);
14876        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14877        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14878    }
14879
14880    #[test]
14881    fn pick_successor_returns_none_without_any_untried_successor() {
14882        let roster = [spec("a"), spec("b")];
14883        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14884        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14885        let carried = ids(&["a"]);
14886        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14887    }
14888
14889    #[test]
14890    fn pick_successor_rescue_avoids_another_seats_occupant() {
14891        // b is a carried failure and free; a is held by the other seat.
14892        let roster = [spec("a"), spec("b"), spec("c")];
14893        let carried = ids(&["b", "c"]);
14894        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14895        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14896    }
14897
14898    #[test]
14899    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14900        let roster = [spec("a"), spec("b"), spec("c")];
14901        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14902        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14903    }
14904
14905    #[test]
14906    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14907        let roster = [spec("a"), spec("b"), spec("c")];
14908        let failed = ids(&["a", "b", "c"]);
14909        // Rescue looks at the whole roster, once per id, then runs out.
14910        let mut tried = ids(&["b"]);
14911        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14912        assert_eq!(first.id, "a");
14913        tried.insert(first.id.clone());
14914        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14915        assert_eq!(second.id, "c");
14916        tried.insert(second.id.clone());
14917        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14918    }
14919
14920    #[test]
14921    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14922        let roster = [spec("a"), spec("b")];
14923        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14924        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14925    }
14926
14927    #[test]
14928    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14929        let roster = [spec("a"), spec("b"), spec("c")];
14930        let h = SeatHistory {
14931            failed: ids(&["a"]),
14932            last_ok: Some("b".to_owned()),
14933            last_fail: None,
14934        };
14935        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14936        // A last answerer that left the roster, or later failed, is ignored.
14937        let gone = SeatHistory {
14938            last_ok: Some("zzz".to_owned()),
14939            ..h.clone()
14940        };
14941        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14942        let failed = SeatHistory {
14943            failed: ids(&["a", "b"]),
14944            last_ok: Some("b".to_owned()),
14945            last_fail: None,
14946        };
14947        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14948    }
14949
14950    #[test]
14951    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14952        let first = SeatState::new("review-1", "alpha", 7);
14953        let next = handover_seat("review-1", "gamma", 7);
14954        assert_ne!(first.claude_session, next.claude_session);
14955    }
14956
14957    #[test]
14958    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14959        let mut state = state_with_summary("x", "y");
14960        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14961        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14962        assert_ne!(a.claude_session, b.claude_session);
14963    }
14964
14965    #[test]
14966    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14967        let roster = [spec("a"), spec("b")];
14968        let h = SeatHistory {
14969            failed: ids(&["a", "b"]),
14970            ..SeatHistory::default()
14971        };
14972        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14973        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14974        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14975    }
14976
14977    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14978    // fallback loop depends on to terminate: it must walk forward from the
14979    // seat's own position, never restart at the front of the roster, and it
14980    // must never hand back an id already tried, however many times that id
14981    // happens to appear.
14982
14983    #[test]
14984    fn failure_signature_ignores_numbers_and_paths() {
14985        assert_eq!(
14986            failure_signature("exited with Some(2) and no usable output"),
14987            failure_signature("exited with Some(137) and no usable output")
14988        );
14989        assert_eq!(
14990            failure_signature("process exited with no usable output (exit code 2)"),
14991            failure_signature("process exited with no usable output (exit code 137)")
14992        );
14993        for (old, new) in [
14994            (
14995                "exited with Some(2) and no usable output",
14996                "process exited with no usable output (exit code 2)",
14997            ),
14998            (
14999                "exited with None and no usable output",
15000                "process exited with no usable output (exit code unavailable)",
15001            ),
15002        ] {
15003            let previous = FailClass::Other(failure_signature(old));
15004            let current = FailClass::Other(failure_signature(new));
15005            assert_eq!(previous, current, "resumption retains the failure class");
15006            assert!(!should_hand_over(Some(&previous), &current));
15007        }
15008        assert_eq!(
15009            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15010            failure_signature("cannot open /var/x.txt: denied")
15011        );
15012        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15013    }
15014
15015    #[test]
15016    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15017        let other = FailClass::Other("x".into());
15018        assert!(should_hand_over(None, &FailClass::Quota));
15019        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15020        assert!(should_hand_over(
15021            Some(&FailClass::Timeout),
15022            &FailClass::Timeout
15023        ));
15024        assert!(should_hand_over(None, &other));
15025        assert!(!should_hand_over(Some(&other), &other));
15026        assert!(should_hand_over(
15027            Some(&other),
15028            &FailClass::Other("y".into())
15029        ));
15030        // A quota or timeout in between ends the run of identical failures.
15031        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15032        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15033    }
15034
15035    #[test]
15036    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15037        let a = SeatState::new("judge-1", "alpha", 7);
15038        let b = handover_seat("judge-1", "beta", 7);
15039        assert_ne!(a.claude_session, b.claude_session);
15040        assert_eq!(b.turns, 0);
15041    }
15042
15043    #[test]
15044    fn a_timeout_is_classified_apart_from_other_failures() {
15045        assert_eq!(
15046            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15047            Some(FailClass::Timeout)
15048        );
15049        assert!(matches!(
15050            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15051            Some(FailClass::Other(_))
15052        ));
15053    }
15054
15055    #[test]
15056    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15057        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15058        let tried = BTreeSet::from(["beta".to_owned()]);
15059        // beta sits at index 1; the next candidate is gamma, never alpha —
15060        // which is very likely a different candidate slot's own agent.
15061        let next = next_untried_in_roster(&roster, 1, &tried);
15062        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15063    }
15064
15065    #[test]
15066    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15067        let roster = vec![spec("alpha"), spec("beta")];
15068        let tried = BTreeSet::from(["beta".to_owned()]);
15069        // beta is the roster's last entry: nothing follows it, and alpha —
15070        // earlier in the roster, almost certainly a different candidate
15071        // slot's own agent — must not be reached by wrapping back to it.
15072        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15073    }
15074
15075    #[test]
15076    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15077        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15078        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15079        // beta (index 1) and gamma (index 2, the only entry after it) have
15080        // both been tried; alpha (index 0) never has, but it comes before
15081        // beta's own position, so there is nothing further for this seat.
15082        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15083    }
15084
15085    #[test]
15086    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15087        let roster = vec![spec("a"), spec("a"), spec("b")];
15088        let tried = BTreeSet::from(["a".to_owned()]);
15089        let next = next_untried_in_roster(&roster, 0, &tried);
15090        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15091    }
15092
15093    #[test]
15094    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15095        let roster = vec![spec("a"), spec("b")];
15096        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15097        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15098    }
15099
15100    #[test]
15101    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15102        let dir = tempfile::tempdir().unwrap();
15103        let bay = dir.path().join("ffff");
15104
15105        // Not there yet: nothing to do, nothing to panic on.
15106        remove_if_empty(&bay);
15107        assert!(!bay.exists());
15108
15109        // Something still inside - the winner's worktree, or a stray file -
15110        // keeps the directory standing.
15111        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15112        remove_if_empty(&bay);
15113        assert!(bay.exists(), "non-empty directory must survive");
15114
15115        // Once the last entry is gone, so is the directory itself.
15116        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15117        remove_if_empty(&bay);
15118        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15119    }
15120
15121    // `round_is_clean` is the exact decision this task fixed: a round with a
15122    // seat that never answered must not read the same as a round every seat
15123    // actually reviewed. These are deterministic and process-free by design —
15124    // the equivalent end-to-end check (a real reviewer timing out under a
15125    // live graph run) is a genuine race against wall-clock contention, and a
15126    // spawn slow enough to blow even a generous budget under a loaded test
15127    // run must not turn this specific regression check flaky.
15128
15129    #[test]
15130    fn a_full_panel_that_found_nothing_is_clean() {
15131        assert!(round_is_clean(
15132            0,
15133            true,
15134            2,
15135            2,
15136            0,
15137            IncompleteReviewPolicy::Block
15138        ));
15139    }
15140
15141    #[test]
15142    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15143        assert!(!round_is_clean(
15144            0,
15145            true,
15146            1,
15147            2,
15148            0,
15149            IncompleteReviewPolicy::Block
15150        ));
15151    }
15152
15153    #[test]
15154    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15155        assert!(!round_is_clean(
15156            1,
15157            true,
15158            1,
15159            2,
15160            0,
15161            IncompleteReviewPolicy::Warn
15162        ));
15163    }
15164
15165    #[test]
15166    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15167        assert!(round_is_clean(
15168            0,
15169            true,
15170            1,
15171            2,
15172            0,
15173            IncompleteReviewPolicy::Warn
15174        ));
15175    }
15176
15177    #[test]
15178    fn a_full_panel_with_an_open_finding_is_not_clean() {
15179        assert!(!round_is_clean(
15180            1,
15181            true,
15182            2,
15183            2,
15184            0,
15185            IncompleteReviewPolicy::Block
15186        ));
15187    }
15188
15189    #[test]
15190    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15191        assert!(!round_is_clean(
15192            0,
15193            false,
15194            2,
15195            2,
15196            0,
15197            IncompleteReviewPolicy::Block
15198        ));
15199    }
15200
15201    // The stall this task closes: under the default `block` policy, a seat
15202    // missing only because it was rate limited must not force a wait for a
15203    // session limit that will not lift by the next round. `round_is_clean`
15204    // is where that quorum carve-out lives; the review loop around it never
15205    // changes what a reviewer's vote or a finding's severity means.
15206
15207    #[test]
15208    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15209        // 1 of 2 answered, and the one missing was quota'd — the exact
15210        // "review-2 rate limited (quota)" shape from the field report.
15211        assert!(round_is_clean(
15212            0,
15213            true,
15214            1,
15215            2,
15216            1,
15217            IncompleteReviewPolicy::Block
15218        ));
15219    }
15220
15221    #[test]
15222    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15223        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15224        // not a quota loss (`quota_missing` stays 0) — worth another try.
15225        assert!(!round_is_clean(
15226            0,
15227            true,
15228            1,
15229            2,
15230            0,
15231            IncompleteReviewPolicy::Block
15232        ));
15233    }
15234
15235    #[test]
15236    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15237        assert!(!round_is_clean(
15238            1,
15239            true,
15240            1,
15241            2,
15242            1,
15243            IncompleteReviewPolicy::Block
15244        ));
15245        assert!(!round_is_clean(
15246            0,
15247            false,
15248            1,
15249            2,
15250            1,
15251            IncompleteReviewPolicy::Block
15252        ));
15253    }
15254
15255    #[test]
15256    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15257        // Every seat quota'd, nobody answered: there is no panel to decide
15258        // on, so this must fall through to the existing block-and-retry
15259        // fallback rather than call an unreviewed patch clean.
15260        assert!(!round_is_clean(
15261            0,
15262            true,
15263            0,
15264            2,
15265            2,
15266            IncompleteReviewPolicy::Block
15267        ));
15268    }
15269
15270    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15271        CommandOutcome {
15272            command: "test".to_owned(),
15273            code,
15274            output_tail: String::new(),
15275            duration_ms: 0,
15276            resource_blocked,
15277            ..Default::default()
15278        }
15279    }
15280
15281    #[cfg(unix)]
15282    #[tokio::test]
15283    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15284        ask_test_home();
15285        let temp = tempfile::tempdir().unwrap();
15286        let mut runner = runner_at(RunStatus::Gating);
15287        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15288        let commands = vec![
15289            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15290            "touch must-not-run".to_owned(),
15291        ];
15292        let (outcomes, retried, pids) = run_e2e_with_retry(
15293            &mut runner.state,
15294            &shell,
15295            &commands,
15296            temp.path(),
15297            Duration::from_secs(5),
15298            "fixture",
15299            None,
15300        )
15301        .await;
15302        assert_eq!(outcomes.len(), 1);
15303        assert!(outcomes[0].resource_blocked);
15304        assert!(!outcomes[0].build_failed());
15305        assert!(!retried);
15306        assert!(pids.is_empty());
15307        assert!(!temp.path().join("must-not-run").exists());
15308        assert_eq!(
15309            runner.state.resource_block.as_ref().unwrap().kind,
15310            "incremental cache admission"
15311        );
15312    }
15313
15314    #[test]
15315    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15316        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15317        assert!(
15318            !verify_inconclusive(&[outcome(Some(1), false)]),
15319            "an ordinary failure is still evidence about the patch"
15320        );
15321        assert!(verify_inconclusive(&[outcome(None, true)]));
15322        assert!(
15323            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15324            "one inconclusive outcome taints the whole batch"
15325        );
15326        assert!(!verify_inconclusive(&[]));
15327    }
15328
15329    #[tokio::test]
15330    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15331        // Alive for the first two checks, then dead - confirms the loop
15332        // actually re-polls rather than deciding once and sleeping out the
15333        // ceiling regardless.
15334        let calls = std::sync::atomic::AtomicUsize::new(0);
15335        let started = Instant::now();
15336        wait_for_pids_with(
15337            &[123],
15338            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15339            Duration::from_millis(5),
15340            Duration::from_secs(5),
15341        )
15342        .await;
15343        assert!(
15344            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15345            "must keep checking rather than deciding on the first answer"
15346        );
15347        assert!(
15348            started.elapsed() < Duration::from_secs(1),
15349            "must return the moment it is confirmed dead, not wait out the ceiling"
15350        );
15351    }
15352
15353    #[tokio::test]
15354    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15355        let started = Instant::now();
15356        wait_for_pids_with(
15357            &[123],
15358            |_| true, // never reports dead
15359            Duration::from_millis(5),
15360            Duration::from_millis(30),
15361        )
15362        .await;
15363        let elapsed = started.elapsed();
15364        assert!(
15365            elapsed >= Duration::from_millis(30),
15366            "must not give up before its own ceiling: {elapsed:?}"
15367        );
15368        assert!(
15369            elapsed < Duration::from_secs(1),
15370            "must not wait past its own ceiling either: {elapsed:?}"
15371        );
15372    }
15373
15374    #[tokio::test]
15375    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15376        let started = Instant::now();
15377        wait_for_pids_with(
15378            &[],
15379            |_| true,
15380            Duration::from_secs(5),
15381            Duration::from_secs(5),
15382        )
15383        .await;
15384        assert!(
15385            started.elapsed() < Duration::from_millis(200),
15386            "an empty pid list has nothing to confirm"
15387        );
15388    }
15389
15390    // `review_conclusion` is the exact decision the review hand-off task
15391    // fixed: a round budget spent (or a tree that stopped moving) must not
15392    // collapse into `Blocked` regardless of what verification actually
15393    // said. Deterministic and process-free for the same reason the
15394    // `round_is_clean` family above is.
15395    fn review_round(
15396        clean: bool,
15397        blocking: usize,
15398        answered: usize,
15399        expected: usize,
15400        progressed: bool,
15401        e2e_ok: bool,
15402    ) -> ReviewRound {
15403        ReviewRound {
15404            round: 1,
15405            head: "h".to_owned(),
15406            verified_head: None,
15407            verified_at: None,
15408            reviews: Vec::new(),
15409            e2e: vec![CommandOutcome {
15410                command: "test".to_owned(),
15411                code: Some(if e2e_ok { 0 } else { 1 }),
15412                output_tail: String::new(),
15413                duration_ms: 0,
15414                resource_blocked: false,
15415                ..Default::default()
15416            }],
15417            verify_retried: false,
15418            e2e_deferred: false,
15419            e2e_defer_reason: None,
15420            fix: None,
15421            blocking,
15422            answered,
15423            expected,
15424            clean,
15425            progressed,
15426            vote_split: false,
15427            reconsideration: Vec::new(),
15428            verdict: None,
15429        }
15430    }
15431
15432    #[test]
15433    fn review_conclusion_is_none_when_nothing_has_run() {
15434        assert_eq!(review_conclusion(&[], 3), None);
15435    }
15436
15437    #[test]
15438    fn review_conclusion_is_none_while_rounds_remain() {
15439        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15440        assert_eq!(review_conclusion(&rounds, 3), None);
15441    }
15442
15443    #[test]
15444    fn review_conclusion_is_gating_once_a_round_is_clean() {
15445        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15446        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15447    }
15448
15449    #[test]
15450    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15451        let rounds = vec![
15452            review_round(false, 1, 2, 2, true, true),
15453            review_round(false, 1, 2, 2, true, true),
15454        ];
15455        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15456    }
15457
15458    #[test]
15459    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15460        let rounds = vec![
15461            review_round(false, 1, 2, 2, true, true),
15462            review_round(false, 1, 2, 2, true, false),
15463        ];
15464        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15465    }
15466
15467    #[test]
15468    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15469        // Magi never got a command to run against this round's own head — a
15470        // resource-blocked attempt, not a red one — so this must never
15471        // settle on `Blocked` the way a genuine e2e failure would. `None`
15472        // here is what tells `Runner::review_loop` to retry the check
15473        // itself rather than trust this cheap recomputation with a verdict
15474        // it cannot actually produce.
15475        let mut blocked = review_round(false, 1, 2, 2, true, false);
15476        blocked.e2e[0].resource_blocked = true;
15477        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15478        assert_eq!(review_conclusion(&rounds, 2), None);
15479    }
15480
15481    #[test]
15482    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15483        // Missing input, not a verified tree — never a hand-off candidate.
15484        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15485        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15486    }
15487
15488    #[test]
15489    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15490        let rounds = vec![
15491            review_round(false, 1, 2, 2, false, true),
15492            review_round(false, 1, 2, 2, false, true),
15493        ];
15494        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15495    }
15496
15497    fn secs(n: u64) -> Duration {
15498        Duration::from_secs(n)
15499    }
15500
15501    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15502    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15503    #[tokio::test]
15504    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15505        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15506        if std::env::var_os(CHILD).is_none() {
15507            // Other tests reconcile every run in the process-global home,
15508            // briefly taking owner locks. This ancestry test expects an idle
15509            // predecessor, so give it its own process and pinned test home.
15510            let output = std::process::Command::new(std::env::current_exe().unwrap())
15511                .args([
15512                    "--exact",
15513                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15514                    "--nocapture",
15515                ])
15516                .env(CHILD, "1")
15517                .env_remove("MAGI_WORKER_HOME")
15518                .env_remove("MAGI_WORKER_ID")
15519                .output()
15520                .unwrap();
15521            assert!(
15522                output.status.success()
15523                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15524                "{}\n{}",
15525                String::from_utf8_lossy(&output.stdout),
15526                String::from_utf8_lossy(&output.stderr)
15527            );
15528            return;
15529        }
15530        ask_test_home();
15531        let tmp = tempfile::tempdir().unwrap();
15532        let repo = tmp.path().join("repo");
15533        std::fs::create_dir_all(&repo).unwrap();
15534        init_repo(&repo);
15535        let g = |args: &[&str]| {
15536            let out = std::process::Command::new("git")
15537                .args(args)
15538                .current_dir(&repo)
15539                .quiet()
15540                .output()
15541                .unwrap();
15542            assert!(
15543                out.status.success(),
15544                "{}",
15545                String::from_utf8_lossy(&out.stderr)
15546            );
15547        };
15548        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15549        g(&["checkout", "-b", "historical"]);
15550        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15551        g(&["add", "."]);
15552        g(&["commit", "-m", "old alternative"]);
15553        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15554        g(&["checkout", "-b", "magi/task-selected", &base]);
15555        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15556        g(&["add", "."]);
15557        g(&["commit", "-m", "measurement infrastructure"]);
15558        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15559        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15560        g(&["add", "."]);
15561        g(&["commit", "-m", "dependent implementation"]);
15562        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15563        g(&["checkout", "main"]);
15564        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15565        g(&["add", "."]);
15566        g(&["commit", "-m", "unrelated base change"]);
15567        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15568        let origin = tmp.path().join("origin.git");
15569        g(&[
15570            "clone",
15571            "--bare",
15572            repo.to_str().unwrap(),
15573            origin.to_str().unwrap(),
15574        ]);
15575        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15576        g(&["fetch", "origin"]);
15577        let selection = crate::pr_recovery::Selection {
15578            url: "https://example.test/project/pull/1".into(),
15579            branch: "magi/task-selected".into(),
15580            head: head.clone(),
15581            source_head: None,
15582            source_run: None,
15583            source_proof: None,
15584            disposition: Some(crate::pr_recovery::Disposition::Review),
15585            instruction: "preserve measured behavior".into(),
15586            approved_at: jiff::Timestamp::now(),
15587        };
15588        let mut template = runner_at(RunStatus::Reviewing);
15589        template.state.repo = repo.clone();
15590        template.state.base_commit = current.clone();
15591        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15592        template.state.origin = Some(crate::run::Origin::queue("selected"));
15593        template.state.pr_head = Some(selection.branch.clone());
15594        template.state.pr_recovery = Some(selection.clone());
15595        let mut runner =
15596            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15597                .await
15598                .unwrap();
15599        let wt = runner.state.winner().unwrap().worktree.clone();
15600        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15601        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15602        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15603        assert!(runner.state.seeds.is_empty());
15604        assert_eq!(runner.state.instruction, "preserve measured behavior");
15605        runner.sync_to_base().await.unwrap();
15606        assert_eq!(
15607            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15608            "prerequisite"
15609        );
15610        assert_eq!(
15611            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15612            "measured implementation"
15613        );
15614        assert_eq!(
15615            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15616            "current main change"
15617        );
15618        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15619        assert_eq!(
15620            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15621            head
15622        );
15623
15624        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15625        let mut partial = runner_at(RunStatus::Reviewing);
15626        partial.state.repo = repo.clone();
15627        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15628        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15629            run: Some("exit 1".into()),
15630            ..Default::default()
15631        }];
15632        let selection = runner.state.pr_recovery.clone().unwrap();
15633        partial.state.pr_recovery = Some(selection.clone());
15634        partial.state.pr_head = Some(selection.branch.clone());
15635        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15636        let id = partial.state.id.clone();
15637        let error = match Runner::open_selected(
15638            &repo,
15639            partial.state,
15640            partial.roles,
15641            1,
15642            runner.state.base_commit.clone(),
15643            selection,
15644        )
15645        .await
15646        {
15647            Ok(_) => panic!("setup must fail"),
15648            Err(e) => e,
15649        };
15650        assert_eq!(
15651            error
15652                .downcast_ref::<crate::run::StartupFailure>()
15653                .unwrap()
15654                .run,
15655            id
15656        );
15657        let failed = RunState::load(&id).unwrap();
15658        assert_eq!(failed.status, RunStatus::Failed);
15659        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15660        assert!(Runner::resume(&id).is_err());
15661        runner.state.status = RunStatus::Ready;
15662        runner.state.driver_exited = true;
15663        runner.state.save().unwrap();
15664        let mut retry = runner_at(RunStatus::Reviewing);
15665        retry.state.repo = repo.clone();
15666        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15667        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15668        reselected.approved_at = jiff::Timestamp::now();
15669        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15670        retry.state.pr_head = Some(reselected.branch.clone());
15671        retry.state.pr_recovery = Some(reselected.clone());
15672        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15673            .await
15674            .unwrap();
15675        let restarted = Runner::open_selected(
15676            &repo,
15677            retry.state,
15678            retry.roles,
15679            1,
15680            runner.state.base_commit.clone(),
15681            reselected,
15682        )
15683        .await
15684        .unwrap();
15685        assert_eq!(
15686            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15687                .await
15688                .unwrap(),
15689            head
15690        );
15691        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15692        assert_eq!(
15693            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15694            head
15695        );
15696    }
15697
15698    #[tokio::test]
15699    #[cfg(unix)]
15700    async fn fallback_and_interrupted_restoration_require_coordination() {
15701        use std::os::fd::AsRawFd as _;
15702        ask_test_home();
15703        let tmp = tempfile::tempdir().unwrap();
15704        let mut runner = registered_runner(tmp.path()).await;
15705        runner.state.config.graph.timeout_resource_wait = 1;
15706        let winner = runner.state.candidates[0].clone();
15707        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15708        let leftover = winner.worktree.join("leftover");
15709        std::fs::write(&leftover, "untrusted edits").unwrap();
15710        let next = tmp.path().join("next-fixer");
15711        let mut failed = spec("first");
15712        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15713        let mut successor = spec("second");
15714        successor.command = vec![
15715            "sh".into(),
15716            "-c".into(),
15717            format!("touch '{}'; echo done", next.display()),
15718        ];
15719        let attempts = vec![
15720            (failed.clone(), "first".into()),
15721            (successor.clone(), "second".into()),
15722        ];
15723        let lock_path = runner.state.repo.join(".git/updater.lock");
15724        let external = std::fs::File::create(&lock_path).unwrap();
15725        assert_eq!(
15726            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15727            0
15728        );
15729        let artifacts = tmp.path().join("artifacts");
15730        let build = |spec, seat| SeatJob {
15731            spec,
15732            seat,
15733            cwd: winner.worktree.clone(),
15734            prompt: "fixture".into(),
15735            timeout: Duration::from_secs(10),
15736            allow_write: true,
15737            sessions: false,
15738            artifacts: artifacts.clone(),
15739            stem: "fix".into(),
15740            handover: None,
15741        };
15742        let (_, _, out) = runner
15743            .ask_fixer_among(
15744                attempts.clone(),
15745                "graft",
15746                None,
15747                Some((&winner.worktree, &head)),
15748                build,
15749            )
15750            .await;
15751        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15752        assert!(leftover.exists(), "contention must prevent clean");
15753        assert!(!next.exists());
15754        assert!(runner.state.handovers.is_empty());
15755        // Early interrupted-repair rollback uses the same protected route.
15756        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15757            from_run: "earlier".into(),
15758            generation: 1,
15759            mode: crate::recovery::Mode::VerifyRepair,
15760            reasons: Vec::new(),
15761            reviewed_head: None,
15762            rounds: Vec::new(),
15763            open_findings: Vec::new(),
15764            evidence: None,
15765            criteria_inherited: true,
15766            repair: crate::recovery::Repair::Started {
15767                before: head.clone(),
15768            },
15769        });
15770        assert!(
15771            runner
15772                .recovery_repair(&winner)
15773                .await
15774                .unwrap_err()
15775                .is::<crate::repo_lock::ResourceBlocked>()
15776        );
15777        assert!(matches!(
15778            runner.state.recovery.as_ref().unwrap().repair,
15779            crate::recovery::Repair::Started { .. }
15780        ));
15781        assert!(leftover.exists());
15782        drop(external);
15783        runner.recovery_repair(&winner).await.unwrap();
15784        assert!(!leftover.exists());
15785        assert!(matches!(
15786            runner.state.recovery.as_ref().unwrap().repair,
15787            crate::recovery::Repair::Done { .. }
15788        ));
15789        // A hard lock-open failure also leaves HEAD and untracked work intact.
15790        std::fs::remove_file(&lock_path).unwrap();
15791        std::fs::create_dir(&lock_path).unwrap();
15792        std::fs::write(&leftover, "untrusted edits").unwrap();
15793        let (_, _, out) = runner
15794            .ask_fixer_among(
15795                attempts,
15796                "graft",
15797                None,
15798                Some((&winner.worktree, &head)),
15799                build,
15800            )
15801            .await;
15802        assert!(matches!(out, AgentOutcome::Failed(_)));
15803        assert!(leftover.exists());
15804        assert!(!next.exists());
15805        assert_eq!(
15806            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15807            head
15808        );
15809    }
15810
15811    #[cfg(unix)]
15812    async fn registered_runner(root: &Path) -> Runner {
15813        repository_runner(root, crate::config::test_coordination()).await
15814    }
15815
15816    async fn repository_runner(
15817        root: &Path,
15818        coordination: Option<crate::config::Coordination>,
15819    ) -> Runner {
15820        ask_test_home();
15821        let repo = root.join("repo");
15822        std::fs::create_dir_all(&repo).unwrap();
15823        init_repo(&repo);
15824        if coordination.is_some() {
15825            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15826        }
15827        let mut runner = runner_at(RunStatus::Prep);
15828        runner.state.repo = repo.clone();
15829        runner.state.config.coordination = coordination;
15830        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15831        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15832        runner.state.config.graph.advise = false;
15833        runner.roles.implementers = vec![spec("implement")];
15834        runner.roles.judges = vec![spec("judge")];
15835        runner.prep().await.unwrap();
15836        runner
15837    }
15838
15839    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15840
15841    #[tokio::test]
15842    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15843        let tmp = tempfile::tempdir().unwrap();
15844        let mut runner = repository_runner(tmp.path(), None).await;
15845        let prompts = runner.state.config.prompts.clone();
15846        let run = runner.state.id.clone();
15847        let ctx = WaveCtx {
15848            carry_seats: false,
15849            pauses: None,
15850            run: &run,
15851            node: "advise",
15852            prompts: &prompts,
15853            cache: None,
15854            round: None,
15855        };
15856        let jobs: Vec<_> = ["alpha", "beta"]
15857            .into_iter()
15858            .map(|id| SeatJob {
15859                spec: scripted(id, AUTH_OUTAGE),
15860                seat: SeatState::new(id, id, 7),
15861                prompt: "propose".into(),
15862                cwd: runner.state.candidates[0].worktree.clone(),
15863                timeout: Duration::from_secs(10),
15864                allow_write: false,
15865                sessions: false,
15866                artifacts: agent::artifacts_dir(&runner.state.dir()),
15867                stem: id.into(),
15868                handover: None,
15869            })
15870            .collect();
15871        let mut losses = Vec::new();
15872        let results = ask_wave_with(
15873            jobs.clone(),
15874            runner.sem.clone(),
15875            2,
15876            &[],
15877            &ctx,
15878            &mut losses,
15879            &mut runner.state,
15880            &|_: &str| Ok(()),
15881        )
15882        .await;
15883        assert!(
15884            results
15885                .iter()
15886                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15887        );
15888        assert_eq!(runner.state.quota.len(), 2);
15889        assert!(
15890            runner
15891                .state
15892                .quota
15893                .iter()
15894                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15895        );
15896        assert!(!runner.state.advise_attempted);
15897        runner.stop_for_resource().unwrap();
15898        assert_eq!(runner.state.status, RunStatus::Blocked);
15899        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15900        assert_eq!(
15901            runner.state.resource_block.as_ref().unwrap().kind,
15902            "agent authentication"
15903        );
15904        // A machine loss followed by an ordinary failure is not evidence
15905        // that the whole node was unavailable, and must not earn a refund.
15906        runner.state.resource_block = None;
15907        runner.state.quota.clear();
15908        let mut mixed = jobs;
15909        mixed[1].spec.command = vec!["false".into()];
15910        let results = ask_wave_with(
15911            mixed,
15912            runner.sem.clone(),
15913            0,
15914            &[],
15915            &ctx,
15916            &mut losses,
15917            &mut runner.state,
15918            &|_: &str| Ok(()),
15919        )
15920        .await;
15921        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15922        assert!(runner.state.resource_block.is_none());
15923        assert_eq!(losses.len(), 1);
15924    }
15925
15926    #[tokio::test]
15927    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15928        let tmp = tempfile::tempdir().unwrap();
15929        let mut runner = repository_runner(tmp.path(), None).await;
15930        let implementer = scripted("implement", AUTH_OUTAGE);
15931        runner.roles.implementers = vec![implementer.clone()];
15932        runner.state.config.agents = vec![implementer];
15933        runner.implement().await.unwrap();
15934        assert_eq!(runner.state.status, RunStatus::Blocked);
15935        assert_eq!(runner.state.quota.len(), 1);
15936        assert_eq!(
15937            runner.state.quota[0].cause,
15938            agent::QuotaCause::Authentication
15939        );
15940        let candidate = &runner.state.candidates[0];
15941        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15942        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15943    }
15944
15945    #[tokio::test]
15946    #[cfg(unix)]
15947    async fn parked_implementer_persists_completed_work() {
15948        for registered in [false, true] {
15949            let tmp = tempfile::tempdir().unwrap();
15950            let mut runner = registered_runner(tmp.path()).await;
15951            if !registered {
15952                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15953            }
15954            let marker = tmp.path().join("started");
15955            let release = tmp.path().join("release");
15956            let mut implementer = spec("implement");
15957            implementer.command = vec![
15958                "sh".into(),
15959                "-c".into(),
15960                format!(
15961                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15962                    marker.display(),
15963                    release.display()
15964                ),
15965            ];
15966            runner.roles.implementers = vec![implementer.clone()];
15967            runner.state.config.agents = vec![implementer];
15968            let pause = runner.pause.clone();
15969            let (result, ()) = tokio::join!(runner.implement(), async {
15970                tokio::time::timeout(Duration::from_secs(10), async {
15971                    while !marker.exists() {
15972                        tokio::time::sleep(Duration::from_millis(10)).await;
15973                    }
15974                })
15975                .await
15976                .unwrap();
15977                pause.park();
15978                std::fs::write(&release, "go").unwrap();
15979            });
15980            result.unwrap();
15981            let candidate = &runner.state.candidates[0];
15982            assert!(candidate.commits > 0, "{candidate:?}");
15983            assert!(candidate.summary.contains("saved-result"));
15984            assert_eq!(candidate.files, 1);
15985            let before = candidate.commits;
15986            runner.implement().await.unwrap();
15987            assert_eq!(runner.state.candidates[0].commits, before);
15988        }
15989    }
15990
15991    #[tokio::test]
15992    #[cfg(unix)]
15993    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15994        let tmp = tempfile::tempdir().unwrap();
15995        let mut runner = registered_runner(tmp.path()).await;
15996        let winner = runner.state.candidates[0].clone();
15997        let cache = tmp.path().join("cache");
15998        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15999        runner.state.config.graph.timeout_resource_wait = 0;
16000        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16001        let crate::cache::AcquireOutcome::Acquired(held) =
16002            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16003        else {
16004            panic!("cache must be free")
16005        };
16006        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16007            from_run: "earlier".into(),
16008            generation: 1,
16009            mode: crate::recovery::Mode::VerifyRepair,
16010            reasons: Vec::new(),
16011            reviewed_head: None,
16012            rounds: Vec::new(),
16013            open_findings: Vec::new(),
16014            evidence: None,
16015            criteria_inherited: true,
16016            repair: crate::recovery::Repair::NotStarted,
16017        });
16018        runner.recovery_repair(&winner).await.unwrap();
16019        assert!(matches!(
16020            runner.state.recovery.as_ref().unwrap().repair,
16021            crate::recovery::Repair::WaitingForRestore { .. }
16022        ));
16023        drop(held);
16024        runner.state.resource_block = None;
16025        runner.state.config.graph.timeout_resource_wait = 1;
16026        runner.recovery_repair(&winner).await.unwrap();
16027        assert!(matches!(
16028            runner.state.recovery.as_ref().unwrap().repair,
16029            crate::recovery::Repair::Done { .. }
16030        ));
16031        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16032    }
16033
16034    #[tokio::test]
16035    #[cfg(unix)]
16036    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16037        use std::os::fd::AsRawFd as _;
16038        for graft in [false, true] {
16039            let tmp = tempfile::tempdir().unwrap();
16040            let mut runner = registered_runner(tmp.path()).await;
16041            runner.state.config.graph.timeout_resource_wait = 1;
16042            let winner = runner.state.candidates[0].clone();
16043            let marker = tmp.path().join("fixer-started");
16044            let mut fixer = spec("fixer");
16045            fixer.command = vec![
16046                "sh".into(),
16047                "-c".into(),
16048                format!("echo started >> '{}'; echo done", marker.display()),
16049            ];
16050            runner.roles.fixer = Some(vec![fixer]);
16051            if graft {
16052                let mut loser = winner.clone();
16053                loser.label = 'B';
16054                loser.index = 1;
16055                runner.state.candidates.push(loser);
16056                runner.state.config.graph.graft_runner_up = true;
16057                runner.state.tally = Some(Tally {
16058                    first_choice: BTreeMap::new(),
16059                    borda: BTreeMap::new(),
16060                    winner: winner.label,
16061                    rankings: 1,
16062                    unanimous_initial: true,
16063                    deliberated: false,
16064                    changed_votes: 0,
16065                    unanimous_final: true,
16066                    tie_break: None,
16067                    judges: 1,
16068                    present: 1,
16069                    quorum: 1,
16070                    met_quorum: true,
16071                    uncontested: None,
16072                });
16073                runner.state.judgements.push(crate::run::Judgement {
16074                    judge: 1,
16075                    seat: "judge-1".into(),
16076                    agent: "judge".into(),
16077                    ranking: vec![winner.label, 'B'],
16078                    reasons: BTreeMap::new(),
16079                    confidence: None,
16080                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16081                    order: vec![0, 1],
16082                    failed: None,
16083                    duration_ms: 0,
16084                });
16085            } else {
16086                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16087                    from_run: "earlier".into(),
16088                    generation: 1,
16089                    mode: crate::recovery::Mode::VerifyRepair,
16090                    reasons: Vec::new(),
16091                    reviewed_head: None,
16092                    rounds: Vec::new(),
16093                    open_findings: Vec::new(),
16094                    evidence: None,
16095                    criteria_inherited: true,
16096                    repair: crate::recovery::Repair::NotStarted,
16097                });
16098            }
16099            let reader = crate::repo_lock::SeatLease::for_checkout(
16100                &winner.worktree,
16101                false,
16102                crate::config::test_coordination().as_ref(),
16103            )
16104            .await
16105            .unwrap();
16106            let pause = runner.pause.clone();
16107            let (result, ()) = tokio::join!(
16108                async {
16109                    if graft {
16110                        runner.graft().await
16111                    } else {
16112                        runner.recovery_repair(&winner).await
16113                    }
16114                },
16115                async {
16116                    tokio::time::sleep(Duration::from_millis(100)).await;
16117                    pause.park();
16118                }
16119            );
16120            result.unwrap();
16121            assert!(!marker.exists(), "a blocked seat must not spawn");
16122            // Exercise the persisted state, as a binary replacement/resume does.
16123            runner.state = RunState::load(&runner.state.id).unwrap();
16124            if graft {
16125                assert_eq!(
16126                    runner.state.graft.as_ref().unwrap().outcome,
16127                    GraftOutcome::WaitingForRestore
16128                );
16129            } else {
16130                assert!(matches!(
16131                    runner.state.recovery.as_ref().unwrap().repair,
16132                    crate::recovery::Repair::WaitingForRestore { .. }
16133                ));
16134            }
16135            drop(reader);
16136            runner.pause = Pause::new();
16137            runner.state.resource_block = None;
16138            // Deferred restoration must still respect an external lock owner.
16139            let external =
16140                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16141            assert_eq!(
16142                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16143                0
16144            );
16145            let leftover = winner.worktree.join("leftover");
16146            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16147            let result = if graft {
16148                runner.graft().await
16149            } else {
16150                runner.recovery_repair(&winner).await
16151            };
16152            assert!(
16153                result
16154                    .unwrap_err()
16155                    .is::<crate::repo_lock::ResourceBlocked>()
16156            );
16157            assert!(leftover.exists());
16158            assert!(!marker.exists());
16159            drop(external);
16160            runner.state.resource_block = None;
16161            let result = if graft {
16162                runner.graft().await
16163            } else {
16164                runner.recovery_repair(&winner).await
16165            };
16166            result.unwrap();
16167            assert!(!leftover.exists(), "restore must precede retry");
16168            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16169            if graft {
16170                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16171            } else {
16172                assert!(matches!(
16173                    runner.state.recovery.as_ref().unwrap().repair,
16174                    crate::recovery::Repair::Done { .. }
16175                ));
16176            }
16177        }
16178    }
16179
16180    #[tokio::test]
16181    #[cfg(unix)]
16182    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16183        use std::os::fd::AsRawFd as _;
16184        let tmp = tempfile::tempdir().unwrap();
16185        let mut runner = registered_runner(tmp.path()).await;
16186        runner.state.config.graph.timeout_resource_wait = 1;
16187        let winner = runner.state.candidates[0].clone();
16188        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16189        runner.state.tally = Some(Tally {
16190            first_choice: BTreeMap::new(),
16191            borda: BTreeMap::new(),
16192            winner: winner.label,
16193            rankings: 0,
16194            unanimous_initial: false,
16195            deliberated: false,
16196            changed_votes: 0,
16197            unanimous_final: false,
16198            tie_break: None,
16199            judges: 0,
16200            present: 0,
16201            quorum: 0,
16202            met_quorum: true,
16203            uncontested: Some("fixture".into()),
16204        });
16205        runner.state.graft = Some(GraftRecord {
16206            pre: pre.clone(),
16207            post: None,
16208            lines: None,
16209            limit: None,
16210            agent: None,
16211            outcome: GraftOutcome::Running,
16212            requested: Vec::new(),
16213            adoption: None,
16214            adoption_error: None,
16215        });
16216        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16217        git::commit_all(&winner.worktree, "unfinished graft")
16218            .await
16219            .unwrap();
16220        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16221        let leftover = winner.worktree.join("leftover");
16222        std::fs::write(&leftover, "untrusted edits").unwrap();
16223        let path = runner.state.repo.join(".git/updater.lock");
16224        let external = std::fs::File::create(&path).unwrap();
16225        assert_eq!(
16226            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16227            0
16228        );
16229        assert!(
16230            runner
16231                .graft()
16232                .await
16233                .unwrap_err()
16234                .is::<crate::repo_lock::ResourceBlocked>()
16235        );
16236        assert!(matches!(
16237            runner.state.graft.as_ref().unwrap().outcome,
16238            GraftOutcome::Running
16239        ));
16240        assert_eq!(
16241            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16242            unfinished
16243        );
16244        assert!(leftover.exists());
16245        drop(external);
16246        std::fs::remove_file(&path).unwrap();
16247        std::fs::create_dir(&path).unwrap();
16248        assert!(runner.graft().await.is_err());
16249        assert!(matches!(
16250            runner.state.graft.as_ref().unwrap().outcome,
16251            GraftOutcome::Running
16252        ));
16253        assert_eq!(
16254            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16255            unfinished
16256        );
16257        assert!(leftover.exists());
16258        std::fs::remove_dir(&path).unwrap();
16259        runner.graft().await.unwrap();
16260        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16261        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16262        assert!(!leftover.exists());
16263    }
16264
16265    #[tokio::test]
16266    #[cfg(unix)]
16267    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16268        use std::os::fd::AsRawFd as _;
16269        let tmp = tempfile::tempdir().unwrap();
16270        let mut runner = registered_runner(tmp.path()).await;
16271        runner.state.prep_complete = Some(false);
16272        runner.state.config.graph.timeout_resource_wait = 1;
16273        runner.state.save().unwrap();
16274        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16275        assert_eq!(
16276            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16277            0
16278        );
16279        runner.execute().await.unwrap();
16280        let disk = RunState::load(&runner.state.id).unwrap();
16281        assert!(disk.driver_exited);
16282        assert_eq!(disk.driver_pid, None);
16283        assert_eq!(runner.state.status, RunStatus::Blocked);
16284        assert_eq!(
16285            runner.state.resource_block.as_ref().unwrap().kind,
16286            "repository coordination"
16287        );
16288        assert!(runner.state.prep_failure.is_none());
16289        assert!(runner.state.seats.is_empty());
16290        runner.pause.park();
16291        // Include headroom for Git subprocesses under parallel test load;
16292        // the repository contention deadline itself remains one second.
16293        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16294            .await
16295            .unwrap()
16296            .unwrap();
16297        assert!(runner.state.parked);
16298        assert!(runner.state.prep_failure.is_none());
16299        let disk = RunState::load(&runner.state.id).unwrap();
16300        assert!(disk.driver_exited);
16301        assert_eq!(disk.driver_pid, None);
16302    }
16303
16304    #[tokio::test]
16305    #[cfg(unix)]
16306    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16307        use std::os::fd::AsRawFd as _;
16308        let tmp = tempfile::tempdir().unwrap();
16309        let mut runner = registered_runner(tmp.path()).await;
16310        runner.state.prep_complete = Some(false);
16311        runner.state.config.graph.timeout_resource_wait = 30;
16312        runner.state.save().unwrap();
16313        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16314        assert_eq!(
16315            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16316            0
16317        );
16318        assert!(
16319            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16320                .await
16321                .is_err()
16322        );
16323        let disk = RunState::load(&runner.state.id).unwrap();
16324        assert!(disk.driver_exited);
16325        assert_eq!(disk.driver_pid, None);
16326        assert!(disk.status.resumable());
16327        assert!(runner.state.driver_exited);
16328        assert_eq!(runner.state.driver_pid, None);
16329        runner.state.save().unwrap();
16330        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16331    }
16332
16333    #[tokio::test]
16334    #[cfg(unix)]
16335    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16336        let tmp = tempfile::tempdir().unwrap();
16337        let mut runner = registered_runner(tmp.path()).await;
16338        let winner = runner.state.candidates[0].clone();
16339        let cache = tmp.path().join("cache");
16340        let started = tmp.path().join("pre-gate-started");
16341        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16342        runner.state.config.verify.gate =
16343            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16344        let home = crate::run::home();
16345        let owner =
16346            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16347        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16348            crate::cache::AcquireOutcome::Acquired(g) => g,
16349            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16350        };
16351        let mut gate = Box::pin(runner.run_gate(&winner));
16352        assert!(
16353            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16354                .await
16355                .is_err()
16356        );
16357        assert!(!started.exists(), "pre-gate must wait for the cache too");
16358        // Simulate the wave that already owns the cache entering invoke.
16359        // It must obtain the editor reservation and finish without waiting
16360        // for the gate that is queued behind its cache.
16361        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16362        let editor = crate::repo_lock::SeatLease::checkout_with(
16363            &winner.worktree,
16364            true,
16365            crate::config::test_coordination().as_ref(),
16366            &wait,
16367        )
16368        .await
16369        .unwrap();
16370        drop(editor);
16371        guard.release();
16372        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16373            .await
16374            .unwrap()
16375            .unwrap();
16376        drop(gate);
16377        assert!(outcomes.iter().all(CommandOutcome::ok));
16378        assert!(started.exists());
16379    }
16380
16381    #[tokio::test]
16382    #[cfg(unix)]
16383    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16384        use std::os::fd::AsRawFd as _;
16385
16386        ask_test_home();
16387        let tmp = tempfile::tempdir().unwrap();
16388        let repo = tmp.path().join("repo");
16389        std::fs::create_dir_all(&repo).unwrap();
16390        init_repo(&repo);
16391        let common = repo.join(".git");
16392        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16393        let mut runner = runner_at(RunStatus::Prep);
16394        runner.state.repo = repo.clone();
16395        runner.state.config.coordination = crate::config::test_coordination();
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.graph.advise = false;
16399        runner.roles.implementers = vec![spec("implement")];
16400        runner.roles.judges = vec![spec("judge")];
16401        runner.prep().await.unwrap();
16402        let winner = runner.state.candidates[0].clone();
16403        // Emulate edits already left by a completed seat. The fixture CLI
16404        // only reports completion; it performs no repository operations.
16405        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16406        let completed = tmp.path().join("seat-completed");
16407        runner.roles.implementers[0].command = vec![
16408            "sh".into(),
16409            "-c".into(),
16410            format!("touch '{}'; echo completed", completed.display()),
16411        ];
16412        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16413        assert_eq!(
16414            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16415            0
16416        );
16417        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16418        let mut implement = Box::pin(runner.implement());
16419        tokio::select! {
16420            result = &mut implement => panic!("rescue must wait: {result:?}"),
16421            result = tokio::time::timeout(Duration::from_secs(10), async {
16422                while !completed.exists() {
16423                    tokio::time::sleep(Duration::from_millis(20)).await;
16424                }
16425            }) => result.unwrap(),
16426        }
16427        assert!(
16428            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16429                .await
16430                .is_err()
16431        );
16432        assert_eq!(
16433            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16434            before
16435        );
16436        assert_eq!(
16437            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16438            0
16439        );
16440        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16441            .await
16442            .unwrap()
16443            .unwrap();
16444        drop(implement);
16445        assert_ne!(
16446            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16447            before
16448        );
16449        assert!(git::is_clean(&winner.worktree).await.unwrap());
16450
16451        let started = tmp.path().join("pre-gate-started");
16452        let proceed = tmp.path().join("pre-gate-proceed");
16453        let checked = tmp.path().join("gate-ran");
16454        runner.state.config.verify.pre_gate = vec![format!(
16455            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16456            started.display(),
16457            proceed.display()
16458        )];
16459        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16460        assert_eq!(
16461            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16462            0
16463        );
16464        let mut gate = Box::pin(runner.run_gate(&winner));
16465        assert!(
16466            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16467                .await
16468                .is_err()
16469        );
16470        assert!(!started.exists());
16471        assert!(!checked.exists());
16472        assert!(git::is_clean(&winner.worktree).await.unwrap());
16473        assert_eq!(
16474            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16475            0
16476        );
16477        tokio::select! {
16478            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16479            result = tokio::time::timeout(Duration::from_secs(10), async {
16480                while !started.exists() {
16481                    tokio::time::sleep(Duration::from_millis(20)).await;
16482                }
16483            }) => result.unwrap(),
16484        }
16485        assert_eq!(
16486            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16487            -1,
16488            "mechanical edits must hold the real lock"
16489        );
16490        std::fs::write(proceed, "ready").unwrap();
16491        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16492            .await
16493            .unwrap()
16494            .unwrap();
16495        drop(gate);
16496        assert!(outcomes.iter().all(CommandOutcome::ok));
16497        assert!(checked.exists());
16498        assert!(runner.state.pre_gate_commit.is_some());
16499        assert!(git::is_clean(&winner.worktree).await.unwrap());
16500        assert_eq!(
16501            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16502            0,
16503            "gate completion must release coordination"
16504        );
16505        drop(outsider);
16506        std::fs::remove_file(common.join("updater.lock")).unwrap();
16507        std::fs::create_dir(common.join("updater.lock")).unwrap();
16508        std::fs::remove_file(&started).unwrap();
16509        std::fs::remove_file(&checked).unwrap();
16510        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16511        let error = runner.run_gate(&winner).await.unwrap_err();
16512        assert!(
16513            error
16514                .to_string()
16515                .contains("acquire mandatory repository lock")
16516        );
16517        assert!(
16518            !started.exists(),
16519            "failed acquisition must prevent pre-gate"
16520        );
16521        assert!(!checked.exists(), "failed acquisition must prevent gate");
16522        assert!(git::is_clean(&winner.worktree).await.unwrap());
16523        assert_eq!(
16524            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16525            head
16526        );
16527    }
16528
16529    #[tokio::test]
16530    #[cfg(unix)]
16531    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16532        use std::os::fd::AsRawFd as _;
16533        use std::time::Duration;
16534
16535        ask_test_home();
16536        let tmp = tempfile::tempdir().unwrap();
16537        let repo = tmp.path().join("repo");
16538        std::fs::create_dir_all(&repo).unwrap();
16539        init_repo(&repo);
16540        let common = repo.join(".git");
16541        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16542        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16543        assert_eq!(
16544            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16545            0
16546        );
16547        let mut runner = runner_at(RunStatus::Prep);
16548        runner.state.repo = repo.clone();
16549        runner.state.config.coordination = crate::config::test_coordination();
16550        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16551        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16552        runner.state.config.graph.advise = true;
16553        runner.state.config.graph.advisors = 1;
16554        runner.roles.implementers = vec![spec("implement")];
16555        runner.roles.judges = vec![spec("judge")];
16556        let root = runner.state.worktree_root();
16557        let started = tmp.path().join("setup-started");
16558        let proceed = tmp.path().join("setup-proceed");
16559        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16560            run: Some(format!(
16561                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16562                started.display(),
16563                proceed.display()
16564            )),
16565            ..Default::default()
16566        }];
16567        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16568        let config = git::git(&repo, &["config", "--local", "--list"])
16569            .await
16570            .unwrap();
16571        let mut prep = Box::pin(runner.prep());
16572        assert!(
16573            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16574                .await
16575                .is_err()
16576        );
16577        assert!(
16578            !root.exists(),
16579            "contention must prevent even checkout creation"
16580        );
16581        assert!(!started.exists(), "contention must prevent setup");
16582        assert_eq!(
16583            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16584            branches
16585        );
16586        assert_eq!(
16587            git::git(&repo, &["config", "--local", "--list"])
16588                .await
16589                .unwrap(),
16590            config
16591        );
16592        drop(lock);
16593        tokio::select! {
16594            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16595            result = tokio::time::timeout(Duration::from_secs(10), async {
16596                while !started.exists() {
16597                    tokio::time::sleep(Duration::from_millis(20)).await;
16598                }
16599            }) => result.unwrap(),
16600        }
16601        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16602        assert_eq!(
16603            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16604            -1
16605        );
16606        assert!(
16607            tokio::time::timeout(
16608                Duration::from_millis(100),
16609                crate::repo_lock::SeatLease::for_checkout(
16610                    &repo,
16611                    true,
16612                    crate::config::test_coordination().as_ref()
16613                )
16614            )
16615            .await
16616            .is_err(),
16617            "preparation must also exclude local editors"
16618        );
16619        std::fs::write(proceed, "ready").unwrap();
16620        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16621            .await
16622            .unwrap()
16623            .unwrap();
16624        drop(prep);
16625        assert_eq!(runner.state.prep_complete, Some(true));
16626        assert!(root.join("judge-1").exists());
16627        assert!(root.join("advisor-1").exists());
16628        assert_eq!(
16629            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16630            0
16631        );
16632    }
16633
16634    #[tokio::test]
16635    #[cfg(unix)]
16636    async fn preparation_lock_failure_prevents_repository_changes() {
16637        ask_test_home();
16638        let tmp = tempfile::tempdir().unwrap();
16639        let repo = tmp.path().join("repo");
16640        std::fs::create_dir_all(&repo).unwrap();
16641        init_repo(&repo);
16642        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16643        // A directory at the required lock path makes opening the real lock
16644        // fail, rather than merely exercising an invalid registration.
16645        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16646        let mut runner = runner_at(RunStatus::Prep);
16647        runner.state.repo = repo.clone();
16648        runner.state.config.coordination = crate::config::test_coordination();
16649        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16650        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16651        runner.roles.implementers = vec![spec("implement")];
16652        let error = runner.prep().await.unwrap_err();
16653        assert!(
16654            error
16655                .to_string()
16656                .contains("acquire mandatory repository lock")
16657        );
16658        assert!(!runner.state.worktree_root().exists());
16659        assert!(runner.state.candidates.is_empty());
16660        assert!(!repo.join(".git/config.worktree").exists());
16661        assert_eq!(
16662            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16663            "* main"
16664        );
16665    }
16666
16667    #[tokio::test]
16668    async fn preparation_records_creation_intent_before_git_can_fail() {
16669        ask_test_home();
16670        let tmp = tempfile::tempdir().unwrap();
16671        let repo = tmp.path().join("repo");
16672        std::fs::create_dir_all(&repo).unwrap();
16673        init_repo(&repo);
16674        let mut runner = runner_at(RunStatus::Prep);
16675        runner.state.repo = repo.clone();
16676        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16677        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16678        runner.state.config.blind.commit_msg_hook = false;
16679        runner.roles.implementers = vec![spec("one")];
16680        let label = blind::assign_labels(1, runner.state.seed)[0];
16681        let branch = runner.state.branch_for(label);
16682        // A conflicting branch makes Git refuse creation before a candidate
16683        // can be registered. The durable intent must still identify it.
16684        git::git(&repo, &["branch", &branch]).await.unwrap();
16685        assert!(runner.prep().await.is_err());
16686        let saved = RunState::load(&runner.state.id).unwrap();
16687        assert!(saved.candidates.is_empty());
16688        let event = saved
16689            .events
16690            .iter()
16691            .find(|e| e.node == "prep-intent")
16692            .unwrap();
16693        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16694        assert_eq!(intent["branch"], branch);
16695        assert_eq!(intent["start"], runner.state.base_commit);
16696        assert_eq!(
16697            intent["worktree"],
16698            runner
16699                .state
16700                .worktree_root()
16701                .join(format!("cand-{label}"))
16702                .to_string_lossy()
16703                .as_ref()
16704        );
16705        assert_eq!(intent["picks"], serde_json::json!([]));
16706    }
16707
16708    #[tokio::test]
16709    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16710        ask_test_home();
16711        let tmp = tempfile::tempdir().unwrap();
16712        let repo = tmp.path().join("repo");
16713        std::fs::create_dir_all(&repo).unwrap();
16714        init_repo(&repo);
16715        let mut runner = runner_at(RunStatus::Prep);
16716        runner.state.repo = repo.clone();
16717        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16718        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16719        runner.state.sources.pick_commits.push(refs::Input {
16720            token: "missing".into(),
16721            sha: "0".repeat(40),
16722            provenance: refs::Provenance::ExplicitCli,
16723        });
16724        assert!(runner.prep().await.is_err());
16725        assert!(runner.state.candidates.is_empty());
16726        assert!(!runner.state.worktree_root().exists());
16727    }
16728
16729    #[tokio::test]
16730    async fn prose_and_legacy_inference_never_import_into_candidates() {
16731        ask_test_home();
16732        let tmp = tempfile::tempdir().unwrap();
16733        let repo = tmp.path().join("repo");
16734        std::fs::create_dir_all(&repo).unwrap();
16735        init_repo(&repo);
16736        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16737        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16738            .await
16739            .unwrap();
16740        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16741        git::git(&repo, &["add", "."]).await.unwrap();
16742        git::git(&repo, &["commit", "-m", "historical implementation"])
16743            .await
16744            .unwrap();
16745        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16746        git::git(&repo, &["checkout", "main"]).await.unwrap();
16747        for instruction in [
16748            format!("Example: magi/history/A at {source}"),
16749            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16750            format!("Never import magi/history/A or {source}"),
16751            format!("Conversation answer: I mentioned {source} only as background"),
16752        ] {
16753            let mut runner = runner_at(RunStatus::Prep);
16754            runner.state.repo = repo.clone();
16755            runner.state.base_commit = base.clone();
16756            runner.state.instruction = instruction.clone();
16757            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16758            runner.state.config.blind.commit_msg_hook = false;
16759            runner.state.seeds = vec![refs::Seed {
16760                token: "magi/history/A".into(),
16761                sha: source.clone(),
16762                kind: refs::SeedKind::Unmerged,
16763                branch: true,
16764                detail: String::new(),
16765            }];
16766            runner.roles.implementers = vec![spec("one")];
16767            assert_eq!(seeded_instruction(&runner.state), instruction);
16768            // Model an old record with inferred seeds but no structured input field.
16769            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16770            legacy.as_object_mut().unwrap().remove("sources");
16771            runner.state = serde_json::from_value(legacy).unwrap();
16772            assert_eq!(runner.state.sources, refs::Sources::default());
16773            runner.state.save().unwrap();
16774            runner.state = RunState::load(&runner.state.id).unwrap();
16775            runner.prep().await.unwrap();
16776            for candidate in &runner.state.candidates {
16777                assert_eq!(
16778                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16779                    base
16780                );
16781                assert!(!candidate.worktree.join("unwanted").exists());
16782            }
16783        }
16784    }
16785
16786    #[tokio::test]
16787    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16788        ask_test_home();
16789        let tmp = tempfile::tempdir().unwrap();
16790        let repo = tmp.path().join("repo");
16791        std::fs::create_dir_all(&repo).unwrap();
16792        init_repo(&repo);
16793        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16794        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16795        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16796        git::git(&repo, &["add", "."]).await.unwrap();
16797        git::git(&repo, &["commit", "-m", "required seed"])
16798            .await
16799            .unwrap();
16800        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16801        git::git(&repo, &["checkout", "main"]).await.unwrap();
16802        let mut runner = runner_at(RunStatus::Prep);
16803        runner.state.repo = repo.clone();
16804        runner.state.base_commit = base.clone();
16805        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16806        runner.state.config.graph.advise = false;
16807        runner.state.config.blind.commit_msg_hook = false;
16808        runner.state.sources =
16809            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16810                .await
16811                .unwrap();
16812        runner.roles.implementers = vec![spec("one"), spec("two")];
16813        runner.roles.judges = vec![spec("judge")];
16814        let label = blind::assign_labels(2, runner.state.seed)[0];
16815        let branch = runner.state.branch_for(label);
16816        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16817        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16818            .await
16819            .unwrap();
16820        runner.state.candidates.push(Candidate {
16821            index: 0,
16822            label,
16823            agent: "one".into(),
16824            branch,
16825            worktree,
16826            summary: String::new(),
16827            stat: String::new(),
16828            files: 0,
16829            commits: 0,
16830            empty: false,
16831            failed: None,
16832            verified_noop: None,
16833            duration_ms: 0,
16834            folded: false,
16835        });
16836        runner.state.save().unwrap();
16837        // Reload the checkpoint immediately before its first cherry-pick.
16838        runner.state = RunState::load(&runner.state.id).unwrap();
16839        assert_eq!(runner.state.prep_complete, Some(false));
16840        runner.prep().await.unwrap();
16841        assert_eq!(runner.state.prep_complete, Some(true));
16842        assert_eq!(runner.state.candidates.len(), 2);
16843        for candidate in &runner.state.candidates {
16844            assert_eq!(
16845                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16846                git::tree_of(&repo, &seed).await.unwrap()
16847            );
16848            assert_eq!(
16849                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16850                "required commit"
16851            );
16852        }
16853        assert!(runner.state.worktree_root().join("judge-1").exists());
16854        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16855        runner.prep().await.unwrap();
16856        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16857
16858        runner.state.prep_complete = Some(false);
16859        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16860            run: Some(format!(
16861                "test -f '{}'",
16862                tmp.path().join("dependency-ready").display()
16863            )),
16864            ..Default::default()
16865        }];
16866        assert!(runner.prep().await.is_err());
16867        assert!(runner.state.prep_failure.is_some());
16868        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16869        runner.state = RunState::load(&runner.state.id).unwrap();
16870        assert!(
16871            runner.prep().await.is_err(),
16872            "correcting the cause alone must not auto-retry"
16873        );
16874        let failed_at = runner.state.events.last().unwrap().at;
16875        assert!(
16876            runner.retry_preparation(failed_at).is_err(),
16877            "old approvals cannot unlock the hold"
16878        );
16879        let mut task = crate::queue::Task::new(
16880            "retry".into(),
16881            "retry setup".into(),
16882            repo.clone(),
16883            crate::queue::Source::Human,
16884        );
16885        task.start(runner.state.id.clone());
16886        task.hold_machine(Some("setup failed".into()));
16887        task.release_operator("cli", None);
16888        runner
16889            .retry_preparation(task.resumption.as_ref().unwrap().at)
16890            .unwrap();
16891        runner.prep().await.unwrap();
16892        assert!(runner.state.prep_failure.is_none());
16893        assert_eq!(runner.state.prep_complete, Some(true));
16894        assert_eq!(runner.state.candidates.len(), 2);
16895        assert!(runner.state.worktree_root().join("judge-1").exists());
16896        for candidate in &runner.state.candidates {
16897            assert_eq!(
16898                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16899                git::tree_of(&repo, &seed).await.unwrap()
16900            );
16901        }
16902    }
16903
16904    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16905        let mut heads = Vec::new();
16906        for candidate in candidates {
16907            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16908        }
16909        heads
16910    }
16911
16912    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16913        ask_test_home();
16914        let tmp = tempfile::tempdir().unwrap();
16915        let repo = tmp.path().join("repo");
16916        std::fs::create_dir(&repo).unwrap();
16917        init_repo(&repo);
16918        let mut runner = runner_at(RunStatus::Reviewing);
16919        runner.state.repo = repo.clone();
16920        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16921        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16922        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16923            let branch = format!("candidate-{label}");
16924            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16925            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16926                .await
16927                .unwrap();
16928            if label == 'B' {
16929                std::fs::write(worktree.join("change"), "winner").unwrap();
16930                git::rescue_commit(&worktree, "candidate change")
16931                    .await
16932                    .unwrap();
16933            }
16934            runner.state.candidates.push(Candidate {
16935                index,
16936                label,
16937                agent: "alpha".into(),
16938                branch,
16939                worktree,
16940                summary: "completed reply".into(),
16941                stat: String::new(),
16942                files: usize::from(label == 'B'),
16943                commits: usize::from(label == 'B'),
16944                empty: label == 'A',
16945                failed: None,
16946                verified_noop: None,
16947                duration_ms: 1,
16948                folded: false,
16949            });
16950        }
16951        runner.state.judge_skipped = true;
16952        runner.state.tally = Some(Tally {
16953            first_choice: BTreeMap::new(),
16954            borda: BTreeMap::new(),
16955            winner: 'B',
16956            rankings: 0,
16957            unanimous_initial: false,
16958            deliberated: false,
16959            changed_votes: 0,
16960            unanimous_final: false,
16961            tie_break: None,
16962            judges: 0,
16963            present: 0,
16964            quorum: 0,
16965            met_quorum: true,
16966            uncontested: Some("only B produced a change".into()),
16967        });
16968        runner.state.save().unwrap();
16969        (tmp, runner)
16970    }
16971
16972    #[tokio::test]
16973    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16974        let (_tmp, mut runner) = preservation_resume_fixture().await;
16975        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16976        runner.state.config.disk.cache_limit_bytes = 0;
16977        runner.state.config.graph.advise = true;
16978        runner.state.config.graph.advisors = 1;
16979        let advisor = runner.state.worktree_root().join("advisor-1");
16980        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16981            .await
16982            .unwrap();
16983        let home = crate::run::home();
16984        let loser =
16985            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16986        let winner =
16987            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16988        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16989        for target in [&loser, &winner, &advisor] {
16990            std::fs::write(target.join("build-output"), "compiled").unwrap();
16991        }
16992
16993        runner.fold_losers().await.unwrap();
16994
16995        assert!(!loser.join("build-output").exists());
16996        assert!(!advisor.join("build-output").exists());
16997        assert!(winner.join("build-output").is_file());
16998    }
16999
17000    #[tokio::test]
17001    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17002        let (_tmp, mut runner) = preservation_resume_fixture().await;
17003        runner.state.candidates[0].folded = true;
17004        runner.state.config.graph.advise = true;
17005        runner.state.config.graph.advisors = 2;
17006        let repo = runner.state.repo.clone();
17007        let root = runner.state.worktree_root();
17008        let discarded = root.join("advisor-1");
17009        git::worktree_add_detached(&repo, &discarded, "main")
17010            .await
17011            .unwrap();
17012        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17013        let protected = root.join("advisor-2");
17014        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17015            .await
17016            .unwrap();
17017        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17018        runner.state.save().unwrap();
17019
17020        assert!(runner.fold_losers().await.is_err());
17021        assert!(!discarded.exists());
17022        assert!(protected.join("keep").exists());
17023        let saved = RunState::load(&runner.state.id).unwrap();
17024        assert!(saved.events.iter().any(|event| {
17025            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17026        }));
17027    }
17028
17029    #[tokio::test]
17030    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17031        let (tmp, mut runner) = preservation_resume_fixture().await;
17032        let repo = runner.state.repo.clone();
17033        let root = runner.state.worktree_root();
17034        for name in ["advisor-3", "judge-1", "review-2"] {
17035            let path = root.join(name);
17036            git::worktree_add_detached(&repo, &path, "main")
17037                .await
17038                .unwrap();
17039            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17040            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17041            remove_read_seat_worktree(&mut runner.state, &path)
17042                .await
17043                .unwrap();
17044            assert!(!path.exists());
17045        }
17046        let outside = tmp.path().join("advisor-1");
17047        let unknown = root.join("unknown");
17048        let attached = root.join("advisor-4");
17049        git::worktree_add_detached(&repo, &outside, "main")
17050            .await
17051            .unwrap();
17052        git::worktree_add_detached(&repo, &unknown, "main")
17053            .await
17054            .unwrap();
17055        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17056            .await
17057            .unwrap();
17058        let foreign = tmp.path().join("foreign");
17059        std::fs::create_dir(&foreign).unwrap();
17060        init_repo(&foreign);
17061        let wrong_repo = root.join("judge-2");
17062        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17063            .await
17064            .unwrap();
17065        let candidate = runner.state.candidates[0].worktree.clone();
17066        for path in [outside, unknown, attached, wrong_repo, candidate] {
17067            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17068            assert!(
17069                remove_read_seat_worktree(&mut runner.state, &path)
17070                    .await
17071                    .is_err()
17072            );
17073            assert_eq!(
17074                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17075                "keep"
17076            );
17077        }
17078    }
17079
17080    #[tokio::test]
17081    #[cfg(unix)]
17082    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17083        for (solo, failed_checkpoint) in
17084            [(true, false), (false, false), (true, true), (false, true)]
17085        {
17086            let (_tmp, mut runner) = preservation_resume_fixture().await;
17087            if solo {
17088                runner.state.candidates.retain(|c| c.label == 'A');
17089            }
17090            runner.state.candidates[0].empty = false;
17091            runner.state.candidates[0].summary.clear();
17092            runner.state.tally = None;
17093            runner.state.judge_skipped = false;
17094            runner.state.status = RunStatus::Implementing;
17095            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17096            let mut implementer = spec("alpha");
17097            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17098            runner.roles.implementers = vec![implementer];
17099            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17100            if failed_checkpoint {
17101                std::fs::create_dir_all(&patch).unwrap();
17102            }
17103            runner.state.save().unwrap();
17104            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17105            drop(pressure);
17106            runner.state = RunState::load(&runner.state.id).unwrap();
17107            assert_eq!(runner.state.status, RunStatus::Blocked);
17108            assert!(runner.state.interrupted_implementations.contains(&'A'));
17109            assert_eq!(runner.state.candidates[0].commits, 0);
17110            assert!(!runner.state.candidates[0].empty);
17111            assert!(runner.state.candidates[0].failed.is_none());
17112            if failed_checkpoint {
17113                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17114                std::fs::remove_dir(patch).unwrap();
17115            }
17116            runner.state.resource_block = None;
17117            runner.state.config.disk.min_free_bytes = 0;
17118            runner.roles.implementers[0].command = vec![
17119                "sh".into(),
17120                "-c".into(),
17121                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17122            ];
17123            runner.implement().await.unwrap();
17124            assert!(runner.state.interrupted_implementations.is_empty());
17125            assert!(runner.state.candidate_preservation.is_empty());
17126            assert_eq!(runner.state.candidates[0].commits, 1);
17127            assert!(!runner.state.candidates[0].empty);
17128            assert!(
17129                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17130                    .unwrap()
17131                    .contains("retried empty interrupted seat")
17132            );
17133            if !solo {
17134                assert_eq!(runner.state.candidates[1].commits, 1);
17135            }
17136        }
17137    }
17138
17139    #[tokio::test]
17140    #[cfg(unix)]
17141    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17142        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17143            let (_tmp, mut runner) = preservation_resume_fixture().await;
17144            runner.state.candidates.retain(|c| c.label == 'A');
17145            runner.state.candidates[0].empty = false;
17146            runner.state.candidates[0].summary.clear();
17147            runner.state.tally = None;
17148            runner.state.judge_skipped = false;
17149            runner.state.status = RunStatus::Implementing;
17150            // Force only the real post-spawn watchdog, without failing the
17151            // separate admission check. Existing edits predate its measurement.
17152            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17153            let wt = runner.state.candidates[0].worktree.clone();
17154            std::fs::write(
17155                wt.join("interrupted-source"),
17156                "retain implementation work\n",
17157            )
17158            .unwrap();
17159            if committed {
17160                git::rescue_commit(&wt, "implementation checkpoint")
17161                    .await
17162                    .unwrap();
17163            }
17164            let lock = git::git(
17165                &wt,
17166                &[
17167                    "rev-parse",
17168                    "--path-format=absolute",
17169                    "--git-path",
17170                    "index.lock",
17171                ],
17172            )
17173            .await
17174            .unwrap();
17175            if block_rescue {
17176                std::fs::write(&lock, "fixture-owned lock").unwrap();
17177            }
17178            let mut implementer = spec("alpha");
17179            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17180            runner.roles.implementers = vec![implementer];
17181            runner.state.save().unwrap();
17182            let result = runner.implement().await;
17183            drop(pressure);
17184            assert_eq!(result.is_err(), block_rescue);
17185            assert_eq!(
17186                runner.state.resource_block.as_ref().unwrap().kind,
17187                "disk pressure"
17188            );
17189            assert!(
17190                runner
17191                    .state
17192                    .events
17193                    .iter()
17194                    .any(|e| e.message.contains("agent execution interrupted"))
17195            );
17196            assert!(
17197                runner
17198                    .state
17199                    .dir()
17200                    .join("artifacts/candidate-A-recovery/staged.patch")
17201                    .exists()
17202            );
17203            if block_rescue {
17204                let saved = RunState::load(&runner.state.id).unwrap();
17205                assert!(saved.candidate_preservation.contains_key(&'A'));
17206                assert!(!saved.candidates[0].empty);
17207                assert_eq!(
17208                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17209                    "retain implementation work\n"
17210                );
17211                std::fs::remove_file(lock).unwrap();
17212                runner.state = saved;
17213            } else {
17214                assert_eq!(runner.state.status, RunStatus::Blocked);
17215                assert_eq!(runner.state.candidates[0].commits, 1);
17216            }
17217            // Recovery must save the candidate before deciding whether another
17218            // implementation is needed. No implementer is available on retry.
17219            runner.roles.implementers.clear();
17220            runner.state.config.disk.min_free_bytes = 0;
17221            runner.state.resource_block = None;
17222            runner.implement().await.unwrap();
17223            assert!(runner.state.candidate_preservation.is_empty());
17224            assert_eq!(runner.state.candidates[0].commits, 1);
17225            assert!(!runner.state.candidates[0].empty);
17226            assert!(git::is_clean(&wt).await.unwrap());
17227            assert!(
17228                crate::run::read_artifact(&runner.state, "cand-A.patch")
17229                    .unwrap()
17230                    .contains("retain implementation work")
17231            );
17232        }
17233    }
17234
17235    #[tokio::test]
17236    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17237        let (_tmp, mut runner) = preservation_resume_fixture().await;
17238        // Schema 15 already confirmed the unfolded no-change result.
17239        runner.implement().await.unwrap();
17240        assert!(runner.state.candidate_preservation.is_empty());
17241        assert!(
17242            !runner
17243                .state
17244                .dir()
17245                .join("artifacts/candidate-A-recovery")
17246                .exists()
17247        );
17248        runner.fold_losers().await.unwrap();
17249        assert!(!runner.state.candidates[0].worktree.exists());
17250        for schema in [14, crate::run::SCHEMA] {
17251            runner.state.schema = schema;
17252            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17253            runner.state.save().unwrap();
17254            runner.state = RunState::load(&runner.state.id).unwrap();
17255            runner.implement().await.unwrap();
17256            assert!(runner.state.candidate_preservation.is_empty());
17257            assert!(runner.state.candidates[0].folded);
17258            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17259        }
17260    }
17261
17262    #[tokio::test]
17263    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17264        let (_tmp, mut runner) = preservation_resume_fixture().await;
17265        runner.state.candidates.retain(|c| c.label == 'A');
17266        runner.state.tally = None;
17267        runner.state.judge_skipped = false;
17268        let candidate = &mut runner.state.candidates[0];
17269        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17270        candidate.failed = Some("deployment validation unavailable".into());
17271        std::fs::write(
17272            candidate.worktree.join("repair"),
17273            "future launcher policy\n",
17274        )
17275        .unwrap();
17276        runner
17277            .state
17278            .candidate_preservation
17279            .insert('A', "awaiting persistence".into());
17280        runner.persist_candidates().await.unwrap();
17281        let candidate = &runner.state.candidates[0];
17282        assert!(!candidate.empty);
17283        assert_eq!(candidate.commits, 1);
17284        assert_eq!(candidate.files, 1);
17285        assert!(candidate.failed.is_none());
17286        assert!(candidate.summary.contains("EPERM"));
17287        assert!(
17288            crate::run::read_artifact(&runner.state, "cand-A.patch")
17289                .unwrap()
17290                .contains("future launcher policy")
17291        );
17292        assert!(runner.state.candidate_preservation.is_empty());
17293    }
17294
17295    #[tokio::test]
17296    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17297        let (_tmp, mut runner) = preservation_resume_fixture().await;
17298        let wt = runner.state.candidates[0].worktree.clone();
17299        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17300        runner.state.schema = 14;
17301        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17302        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17303        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17304        for _ in 0..2 {
17305            assert!(runner.implement().await.is_err());
17306            assert_eq!(runner.state.status, RunStatus::Blocked);
17307            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17308            assert!(
17309                runner.state.candidates[0].empty,
17310                "old verdict must remain unusable"
17311            );
17312            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17313            assert!(runner.state.judge_skipped);
17314            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17315            assert!(
17316                crate::run::read_artifact(&runner.state, "cand-A.patch")
17317                    .unwrap()
17318                    .contains("owned edits")
17319            );
17320            assert!(wt.exists());
17321            assert_eq!(
17322                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17323                    .await
17324                    .unwrap(),
17325                1
17326            );
17327            runner.state = RunState::load(&runner.state.id).unwrap();
17328        }
17329    }
17330
17331    #[tokio::test]
17332    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17333        let (_tmp, mut runner) = preservation_resume_fixture().await;
17334        let wt = runner.state.candidates[0].worktree.clone();
17335        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17336        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17337        let index_lock = PathBuf::from(
17338            git::git(
17339                &wt,
17340                &[
17341                    "rev-parse",
17342                    "--path-format=absolute",
17343                    "--git-path",
17344                    "index.lock",
17345                ],
17346            )
17347            .await
17348            .unwrap(),
17349        );
17350        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17351        runner.state.schema = 14;
17352        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17353        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17354        assert!(runner.implement().await.is_err());
17355        assert!(runner.after_implement().is_err());
17356        assert!(runner.fold_losers().await.is_err());
17357        assert_eq!(
17358            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17359            "failed seat edits"
17360        );
17361        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17362        runner.state = RunState::load(&runner.state.id).unwrap();
17363        std::fs::remove_file(index_lock).unwrap();
17364        // Recovery finds changes that the old uncontested result never judged.
17365        assert!(runner.implement().await.is_err());
17366        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17367        assert!(runner.state.candidates[0].empty);
17368        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17369        assert!(
17370            crate::run::read_artifact(&runner.state, "cand-A.patch")
17371                .unwrap()
17372                .contains("failed seat edits")
17373        );
17374        assert!(wt.exists());
17375    }
17376
17377    #[tokio::test]
17378    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17379        let (_tmp, mut runner) = preservation_resume_fixture().await;
17380        let repo = runner.state.repo.clone();
17381        let common = git::git(
17382            &repo,
17383            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17384        )
17385        .await
17386        .unwrap();
17387        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17388        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17389        assert!(runner.fold_losers().await.is_err());
17390        assert!(!runner.state.candidates[0].worktree.exists());
17391        assert!(!runner.state.candidates[0].folded);
17392        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17393        runner.state = RunState::load(&runner.state.id).unwrap();
17394        std::fs::remove_file(branch_lock).unwrap();
17395        let judge = runner.state.worktree_root().join("judge-1");
17396        git::worktree_add_detached(&repo, &judge, "main")
17397            .await
17398            .unwrap();
17399        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17400        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17401            .await
17402            .unwrap();
17403        runner.roles.judges = vec![spec("judge")];
17404        assert!(runner.fold_losers().await.is_err());
17405        runner.state = RunState::load(&runner.state.id).unwrap();
17406        assert!(
17407            runner.state.candidates[0].folded,
17408            "candidate progress saved before judge failure"
17409        );
17410        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17411        assert!(judge.join("uncommitted").exists());
17412        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17413            .await
17414            .unwrap();
17415        runner.fold_losers().await.unwrap();
17416        assert!(!judge.exists());
17417        runner.fold_losers().await.unwrap();
17418    }
17419
17420    #[tokio::test]
17421    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17422        let (_tmp, mut runner) = preservation_resume_fixture().await;
17423        runner.state.candidates.retain(|c| c.label == 'B');
17424        runner.state.tally = None;
17425        runner.state.judge_skipped = false;
17426        runner.state.prep_complete = Some(true);
17427        runner.state.config.graph.advise = false;
17428        runner.state.config.graph.selected_implementer = Some("alpha".into());
17429        let wt = runner.state.candidates[0].worktree.clone();
17430        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17431        runner
17432            .state
17433            .candidate_preservation
17434            .insert('B', "awaiting persistence".into());
17435        let index_lock = git::git(
17436            &wt,
17437            &[
17438                "rev-parse",
17439                "--path-format=absolute",
17440                "--git-path",
17441                "index.lock",
17442            ],
17443        )
17444        .await
17445        .unwrap();
17446        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17447        runner.state.save().unwrap();
17448        assert!(runner.execute_graph().await.is_err());
17449        assert_eq!(runner.state.status, RunStatus::Blocked);
17450        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17451        std::fs::remove_file(index_lock).unwrap();
17452        // Park at the next graph boundary: this tests the real selected-seat
17453        // hold guard without dispatching reviewers or publishing anything.
17454        for _ in 0..2 {
17455            runner.state = RunState::load(&runner.state.id).unwrap();
17456            runner.pause.park();
17457            runner.execute_graph().await.unwrap();
17458            assert_eq!(runner.state.status, RunStatus::Implementing);
17459            assert!(runner.state.candidate_preservation.is_empty());
17460            assert_eq!(runner.state.candidates[0].commits, 2);
17461            assert!(runner.state.tally.is_none());
17462        }
17463        runner.implement().await.unwrap();
17464        assert_eq!(runner.state.status, RunStatus::Judging);
17465        // A genuine selected-implementer hold must still require release.
17466        runner.state.status = RunStatus::Blocked;
17467        runner.state.candidates[0].failed = Some("implementation failed".into());
17468        runner.state.save().unwrap();
17469        let error = runner.execute_graph().await.unwrap_err();
17470        assert!(
17471            error
17472                .to_string()
17473                .contains("selected implementation is held")
17474        );
17475    }
17476
17477    #[tokio::test]
17478    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17479        let (_tmp, mut runner) = preservation_resume_fixture().await;
17480        let repo = runner.state.repo.clone();
17481        let candidate = runner.state.candidates[0].clone();
17482        // Remove only the disposable fixture directory, leaving Git's linked
17483        // worktree registration and branch intact, as in a vanished checkout.
17484        let registered = git::worktree_holding(&repo, &candidate.branch)
17485            .await
17486            .unwrap()
17487            .unwrap();
17488        assert_eq!(
17489            registered.canonicalize().unwrap(),
17490            candidate.worktree.canonicalize().unwrap()
17491        );
17492        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17493        assert_eq!(
17494            git::worktree_holding(&repo, &candidate.branch)
17495                .await
17496                .unwrap(),
17497            Some(registered)
17498        );
17499        assert!(
17500            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17501            "the stale registration initially keeps the branch checked out"
17502        );
17503        runner.fold_losers().await.unwrap();
17504        assert!(runner.state.candidates[0].folded);
17505        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17506        assert_eq!(
17507            git::worktree_holding(&repo, &candidate.branch)
17508                .await
17509                .unwrap(),
17510            None
17511        );
17512        runner.state = RunState::load(&runner.state.id).unwrap();
17513        runner.fold_losers().await.unwrap();
17514    }
17515
17516    #[tokio::test]
17517    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17518        let (_tmp, mut runner) = preservation_resume_fixture().await;
17519        let repo = runner.state.repo.clone();
17520        let candidate = runner.state.candidates[0].clone();
17521        let winner = runner.state.candidates[1].clone();
17522        let registered = git::worktree_holding(&repo, &candidate.branch)
17523            .await
17524            .unwrap()
17525            .unwrap();
17526        assert_eq!(
17527            registered.canonicalize().unwrap(),
17528            candidate.worktree.canonicalize().unwrap()
17529        );
17530        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17531        assert_eq!(
17532            git::worktree_holding(&repo, &candidate.branch)
17533                .await
17534                .unwrap(),
17535            Some(registered)
17536        );
17537        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17538
17539        for _ in 0..2 {
17540            fold_run(&mut runner.state, false, &crate::run::home())
17541                .await
17542                .unwrap();
17543            runner.state = RunState::load(&runner.state.id).unwrap();
17544            assert!(runner.state.candidates[0].folded);
17545            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17546            assert_eq!(
17547                git::worktree_holding(&repo, &candidate.branch)
17548                    .await
17549                    .unwrap(),
17550                None
17551            );
17552            assert!(!runner.state.candidates[1].folded);
17553            assert!(winner.worktree.exists());
17554            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17555        }
17556    }
17557    #[tokio::test]
17558    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17559        for sidecar in [false, true] {
17560            let tmp = tempfile::tempdir().unwrap();
17561            let home = tmp.path().join("home");
17562            let repo = tmp.path().join("repo");
17563            std::fs::create_dir(&repo).unwrap();
17564            init_repo(&repo);
17565            let mut state = runner_at(RunStatus::Superseded).state;
17566            state.repo = repo.clone();
17567            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17568            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17569            state.driver_exited = true;
17570            state.reserve_under(&home).unwrap();
17571            git::git(
17572                &repo,
17573                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17574            )
17575            .await
17576            .unwrap();
17577            let wt = state.worktree_root().join("cand-A");
17578            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17579                .await
17580                .unwrap();
17581            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17582            git::commit_all(&wt, "fixture: independent source")
17583                .await
17584                .unwrap();
17585            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17586            state.candidates.push(Candidate {
17587                index: 0,
17588                label: 'A',
17589                agent: "fixture".into(),
17590                branch: "candidate".into(),
17591                worktree: wt.clone(),
17592                summary: String::new(),
17593                stat: String::new(),
17594                files: 0,
17595                commits: 0,
17596                empty: false,
17597                failed: None,
17598                verified_noop: None,
17599                duration_ms: 0,
17600                folded: false,
17601            });
17602            let mut task = crate::queue::Task::new(
17603                "task".into(),
17604                "task".into(),
17605                repo.clone(),
17606                crate::queue::Source::Human,
17607            );
17608            task.runs.push(state.id.clone());
17609            crate::queue::Queue::at(home.join("queue"))
17610                .put(&mut task)
17611                .unwrap();
17612            if sidecar {
17613                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17614            }
17615            state.save_under(&home).unwrap();
17616            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17617            assert!(
17618                fold_run(&mut state, true, &home)
17619                    .await
17620                    .unwrap_err()
17621                    .to_string()
17622                    .contains(&reason)
17623            );
17624            let mut disk = state.config.disk.clone();
17625            disk.fold_grace_secs = 0;
17626            assert_eq!(
17627                crate::clean::fold_due(
17628                    &home.join("runs"),
17629                    &home,
17630                    &state.worktree_root(),
17631                    &disk,
17632                    Timestamp::now() + std::time::Duration::from_secs(10),
17633                )
17634                .await
17635                .unwrap(),
17636                (0, 0)
17637            );
17638            assert!(wt.exists());
17639            state.status = RunStatus::Blocked;
17640            state.save_under(&home).unwrap();
17641            assert!(
17642                fold_run_overriding_recovery_retention(&mut state, true, &home)
17643                    .await
17644                    .is_err()
17645            );
17646            state.status = RunStatus::Superseded;
17647            state.driver_exited = false;
17648            state.driver_claimed = None;
17649            state.save_under(&home).unwrap();
17650            assert!(
17651                fold_run_overriding_recovery_retention(&mut state, true, &home)
17652                    .await
17653                    .is_err()
17654            );
17655            state.driver_pid = Some(std::process::id());
17656            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17657            state.save_under(&home).unwrap();
17658            assert!(
17659                fold_run_overriding_recovery_retention(&mut state, true, &home)
17660                    .await
17661                    .is_err()
17662            );
17663            state.driver_exited = true;
17664            state.driver_pid = None;
17665            state.driver_started_at = None;
17666            state.save_under(&home).unwrap();
17667            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17668            assert!(
17669                fold_run_overriding_recovery_retention(&mut state, true, &home)
17670                    .await
17671                    .is_err()
17672            );
17673            drop(lease);
17674            #[cfg(unix)]
17675            {
17676                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17677                assert!(
17678                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17679                        .await
17680                        .is_err()
17681                );
17682                drop(output);
17683            }
17684            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17685            assert!(
17686                fold_run_overriding_recovery_retention(&mut state, true, &home)
17687                    .await
17688                    .is_err()
17689            );
17690            drop(owner);
17691            let checkpoint = git::git(
17692                &wt,
17693                &[
17694                    "rev-parse",
17695                    "--path-format=absolute",
17696                    "--git-path",
17697                    "CHERRY_PICK_HEAD",
17698                ],
17699            )
17700            .await
17701            .unwrap();
17702            std::fs::write(&checkpoint, &head).unwrap();
17703            assert!(
17704                fold_run_overriding_recovery_retention(&mut state, true, &home)
17705                    .await
17706                    .is_err()
17707            );
17708            std::fs::remove_file(checkpoint).unwrap();
17709            std::fs::write(wt.join("dirty"), "keep").unwrap();
17710            assert!(
17711                fold_run_overriding_recovery_retention(&mut state, true, &home)
17712                    .await
17713                    .is_err()
17714            );
17715            assert!(wt.join("dirty").exists());
17716            std::fs::remove_file(wt.join("dirty")).unwrap();
17717            let evidence = home
17718                .join("runs")
17719                .join(&state.id)
17720                .join("artifacts/fold-evidence");
17721            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17722            std::fs::write(&evidence, "blocked archive").unwrap();
17723            assert!(
17724                fold_run_overriding_recovery_retention(&mut state, true, &home)
17725                    .await
17726                    .is_err()
17727            );
17728            assert!(wt.exists());
17729            assert!(
17730                !RunState::load_under(&state.id, &home)
17731                    .unwrap()
17732                    .events
17733                    .iter()
17734                    .any(|event| event.message.contains("--override-recovery-retention"))
17735            );
17736            std::fs::remove_file(&evidence).unwrap();
17737            fold_run_overriding_recovery_retention(&mut state, true, &home)
17738                .await
17739                .unwrap();
17740            assert!(!wt.exists());
17741            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17742            assert!(
17743                git::worktree_holding(&repo, "candidate")
17744                    .await
17745                    .unwrap()
17746                    .is_none()
17747            );
17748            assert!(
17749                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17750                    .unwrap()
17751                    .contains("retained implementation")
17752            );
17753            assert!(evidence.join(format!("{head}.index")).is_file());
17754            let saved = RunState::load_under(&state.id, &home).unwrap();
17755            assert_eq!(saved.status, RunStatus::Superseded);
17756            assert!(saved.candidates[0].folded);
17757            assert!(saved.events.iter().any(|event| {
17758                event.message.contains("--override-recovery-retention")
17759                    && event.message.contains(&state.id)
17760                    && event.message.contains(&reason)
17761            }));
17762            assert_eq!(
17763                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17764                sidecar
17765            );
17766        }
17767    }
17768
17769    #[tokio::test]
17770    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17771        ask_test_home();
17772        let tmp = tempfile::tempdir().unwrap();
17773        let repo = tmp.path().join("repo");
17774        std::fs::create_dir(&repo).unwrap();
17775        init_repo(&repo);
17776        let mut runner = runner_at(RunStatus::Implementing);
17777        runner.state.repo = repo.clone();
17778        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17779        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17780        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17781            let branch = format!("candidate-{label}");
17782            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17783            git::worktree_add_branch(&repo, &wt, &branch, "main")
17784                .await
17785                .unwrap();
17786            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17787            git::git(&wt, &["add", "README.md"]).await.unwrap();
17788            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17789            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17790            runner.state.candidates.push(Candidate {
17791                index,
17792                label,
17793                agent: "alpha".to_owned(),
17794                branch,
17795                worktree: wt,
17796                summary: "completed implementation".to_owned(),
17797                stat: String::new(),
17798                files: 0,
17799                commits: 0,
17800                empty: false,
17801                failed: None,
17802                verified_noop: None,
17803                duration_ms: 42,
17804                folded: false,
17805            });
17806            runner
17807                .state
17808                .candidate_preservation
17809                .insert(label, "awaiting persistence".to_owned());
17810        }
17811        let wt = runner.state.candidates[0].worktree.clone();
17812        let index_lock = git::git(
17813            &wt,
17814            &[
17815                "rev-parse",
17816                "--path-format=absolute",
17817                "--git-path",
17818                "index.lock",
17819            ],
17820        )
17821        .await
17822        .unwrap();
17823        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17824        runner.state.save().unwrap();
17825        assert!(runner.persist_candidates().await.is_err());
17826        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17827        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17828        assert_eq!(
17829            runner.state.candidates[1].commits, 1,
17830            "other results are still collected"
17831        );
17832        assert!(
17833            !runner.state.candidates[0].empty,
17834            "failed rescue is not no change"
17835        );
17836        assert_eq!(
17837            runner.state.candidates[0].summary,
17838            "completed implementation"
17839        );
17840        assert!(runner.after_implement().is_err());
17841        let home = tmp.path().join("fold-home");
17842        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17843        assert!(wt.join("new-file").exists());
17844        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17845        assert!(recovery.join("staged.patch").exists());
17846        assert!(recovery.join("unstaged.patch").exists());
17847        assert_eq!(
17848            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17849            "untracked edits\n"
17850        );
17851        runner.state.begin_pass();
17852        runner.state.end_pass_parked(ParkCause::Upgrade {
17853            from: "1.0".into(),
17854            to: Some("1.1".into()),
17855        });
17856        runner.state.save().unwrap();
17857        runner.state = RunState::load(&runner.state.id).unwrap();
17858        assert!(matches!(
17859            runner.state.passes.last().unwrap().end,
17860            Some(crate::run::PassEnd::Parked {
17861                cause: ParkCause::Upgrade { .. }
17862            })
17863        ));
17864        std::fs::remove_file(index_lock).unwrap();
17865        // No implementer is configured: a persistence retry cannot dispatch a seat.
17866        runner.implement().await.unwrap();
17867        assert!(runner.state.candidate_preservation.is_empty());
17868        assert!(
17869            runner
17870                .state
17871                .candidates
17872                .iter()
17873                .all(|c| c.commits == 1 && !c.empty)
17874        );
17875        assert!(git::is_clean(&wt).await.unwrap());
17876        assert!(
17877            crate::run::read_artifact(&runner.state, "cand-A.patch")
17878                .unwrap()
17879                .contains("later tracked edits")
17880        );
17881    }
17882
17883    #[tokio::test]
17884    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17885        ask_test_home();
17886        let tmp = tempfile::tempdir().unwrap();
17887        let repo = tmp.path().join("repo");
17888        std::fs::create_dir(&repo).unwrap();
17889        init_repo(&repo);
17890        let wt = tmp.path().join("candidate");
17891        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17892            .await
17893            .unwrap();
17894        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17895        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17896        assert!(wt.join("uncommitted").exists());
17897        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17898        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17899        let mut runner = runner_at(RunStatus::Implementing);
17900        runner.state.repo = repo.clone();
17901        runner.state.base_commit = "missing-base".to_owned();
17902        runner.state.candidates.push(Candidate {
17903            index: 0,
17904            label: 'A',
17905            agent: "alpha".into(),
17906            branch: "candidate".into(),
17907            worktree: wt.clone(),
17908            summary: "completed".into(),
17909            stat: String::new(),
17910            files: 0,
17911            commits: 0,
17912            empty: false,
17913            failed: None,
17914            verified_noop: None,
17915            duration_ms: 1,
17916            folded: false,
17917        });
17918        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17919        assert!(
17920            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17921                .await
17922                .is_err()
17923        );
17924        assert!(!runner.state.candidates[0].folded);
17925        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17926        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17927        runner
17928            .state
17929            .candidate_preservation
17930            .insert('A', "pending".into());
17931        assert!(runner.persist_candidates().await.is_err());
17932        assert!(!runner.state.candidates[0].empty);
17933        assert!(!runner.state.candidates[0].folded);
17934        assert!(wt.exists());
17935        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17936        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17937        std::fs::create_dir_all(&patch_path).unwrap();
17938        assert!(
17939            runner.persist_candidates().await.is_err(),
17940            "artifact failure stays pending"
17941        );
17942        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17943        assert!(!runner.state.candidates[0].empty);
17944        std::fs::remove_dir(patch_path).unwrap();
17945        runner.persist_candidates().await.unwrap();
17946        assert!(
17947            runner.state.candidates[0].empty,
17948            "only successful inspection confirms no change"
17949        );
17950    }
17951
17952    fn init_repo(dir: &Path) {
17953        let run = |args: &[&str]| {
17954            let out = std::process::Command::new("git")
17955                .args(args)
17956                .current_dir(dir)
17957                .quiet()
17958                .output()
17959                .expect("spawn git");
17960            assert!(
17961                out.status.success(),
17962                "git {args:?} failed: {}",
17963                String::from_utf8_lossy(&out.stderr)
17964            );
17965        };
17966        run(&["init", "-b", "main"]);
17967        run(&["config", "user.name", "magi test"]);
17968        run(&["config", "user.email", "magi@example.com"]);
17969        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17970        run(&["add", "-A"]);
17971        run(&["commit", "-m", "init"]);
17972    }
17973
17974    // `settle_questions` is what closes the ghost the phone showed: a run's
17975    // seat asked something, the run then ended, and nothing was left to
17976    // abandon the question it left `open`. `HOME` is a process-wide
17977    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17978    // first time it runs in the binary — every test below still reaches the
17979    // same directory whichever call won, and each gets its own run id from
17980    // `RunState::new`, so they never collide there.
17981    fn ask_test_home() {
17982        crate::run::pin_test_home();
17983    }
17984
17985    #[test]
17986    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17987        ask_test_home();
17988        let mut runner = runner_at(RunStatus::Prep);
17989        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17990        // A blocked temporary output path makes the terminal save fail while
17991        // preserving the already published reservation.
17992        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17993        let error = guard
17994            .finish(
17995                &mut runner.state,
17996                Err(
17997                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17998                        .into(),
17999                ),
18000            )
18001            .unwrap_err();
18002        assert_eq!(
18003            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18004            std::io::ErrorKind::PermissionDenied
18005        );
18006        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18007        let message = format!("{error:#}");
18008        assert!(message.contains("original refusal"));
18009        assert!(!message.contains("could not save terminal"));
18010        assert_eq!(
18011            error.chain().count(),
18012            2,
18013            "only startup attribution wraps the original error"
18014        );
18015        let saved = RunState::load(&runner.state.id).unwrap();
18016        assert_eq!(saved.status, RunStatus::Blocked);
18017        assert!(!saved.startup.unwrap().complete);
18018    }
18019
18020    #[test]
18021    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18022        ask_test_home();
18023        let mut runner = runner_at(RunStatus::Prep);
18024        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18025        let id = runner.state.id.clone();
18026        drop(guard);
18027        let saved = RunState::load(&id).unwrap();
18028        assert_eq!(saved.status, RunStatus::Blocked);
18029        assert!(!saved.startup.as_ref().unwrap().complete);
18030        assert!(
18031            saved
18032                .startup
18033                .unwrap()
18034                .failure
18035                .unwrap()
18036                .contains("interrupted")
18037        );
18038        assert!(Runner::resume(&id).is_err());
18039    }
18040
18041    #[test]
18042    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18043        ask_test_home();
18044        let mut runner = runner_at(RunStatus::Prep);
18045        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18046        let error = guard
18047            .finish(
18048                &mut runner.state,
18049                Err(
18050                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18051                        .into(),
18052                ),
18053            )
18054            .unwrap_err();
18055        assert_eq!(
18056            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18057            std::io::ErrorKind::PermissionDenied
18058        );
18059        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18060        let mut task = crate::queue::Task::new(
18061            "review".into(),
18062            "criteria".into(),
18063            runner.state.repo.clone(),
18064            crate::queue::Source::Human,
18065        );
18066        task.record_startup_failure(failure.clone());
18067        task.record_startup_failure(failure.clone());
18068        assert_eq!(task.startup_failures.len(), 1);
18069        assert!(task.runs.is_empty());
18070        assert_eq!(task.attempts, 0);
18071    }
18072
18073    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18074        ask_test_home();
18075        let tmp = tempfile::tempdir().unwrap();
18076        let repo = tmp.path().join("repo");
18077        std::fs::create_dir(&repo).unwrap();
18078        init_repo(&repo);
18079        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18080        let origin = tmp.path().join("origin.git");
18081        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18082            .await
18083            .unwrap();
18084        git::git(
18085            &repo,
18086            &["remote", "add", "origin", origin.to_str().unwrap()],
18087        )
18088        .await
18089        .unwrap();
18090        git::git(&repo, &["checkout", "-b", "fix/retained"])
18091            .await
18092            .unwrap();
18093        std::fs::write(repo.join("retained"), "retained change").unwrap();
18094        git::git(&repo, &["add", "."]).await.unwrap();
18095        git::git(&repo, &["commit", "-m", "retained implementation"])
18096            .await
18097            .unwrap();
18098        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18099        git::git(&repo, &["checkout", "main"]).await.unwrap();
18100        std::fs::write(repo.join("base-change"), "new base").unwrap();
18101        git::git(&repo, &["add", "."]).await.unwrap();
18102        git::git(&repo, &["commit", "-m", "base moved"])
18103            .await
18104            .unwrap();
18105        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18106        git::git(&repo, &["checkout", "fix/retained"])
18107            .await
18108            .unwrap();
18109        let mut runner = runner_at(RunStatus::Voting);
18110        runner.state.repo = repo.clone();
18111        runner.state.base_commit = base;
18112        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18113        runner.state.config.disk.min_free_bytes = 0;
18114        runner.state.config.graph.review_rounds = 1;
18115        runner.state.config.verify.e2e = vec!["true".into()];
18116        runner.state.config.verify.gate = vec!["true".into()];
18117        runner.state.candidates = vec![Candidate {
18118            index: 0,
18119            label: 'A',
18120            agent: "fixture".into(),
18121            branch: "fix/retained".into(),
18122            worktree: repo.clone(),
18123            summary: String::new(),
18124            stat: String::new(),
18125            files: 1,
18126            commits: 1,
18127            empty: false,
18128            failed: None,
18129            verified_noop: None,
18130            duration_ms: 0,
18131            folded: false,
18132        }];
18133        runner.state.tally = Some(Tally {
18134            first_choice: BTreeMap::new(),
18135            borda: BTreeMap::new(),
18136            winner: 'A',
18137            rankings: 0,
18138            unanimous_initial: true,
18139            deliberated: false,
18140            changed_votes: 0,
18141            unanimous_final: true,
18142            tie_break: None,
18143            judges: 0,
18144            present: 0,
18145            quorum: 0,
18146            met_quorum: true,
18147            uncontested: Some("review-only".into()),
18148        });
18149        let mut task = crate::queue::Task::new(
18150            "fixture".into(),
18151            "fixture".into(),
18152            repo,
18153            crate::queue::Source::Human,
18154        );
18155        task.link_run(&runner.state.id);
18156        crate::queue::Queue::open().put(&mut task).unwrap();
18157        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18158        runner.state.base_sync = Some(BaseSync {
18159            tip: String::new(),
18160            behind: 1,
18161            attempts: BASE_SYNC_ROUNDS,
18162            conflict: None,
18163            already_in: None,
18164        });
18165        runner.sync_to_base().await.unwrap();
18166        assert_eq!(runner.state.status, RunStatus::Blocked);
18167        (tmp, runner, head, task.id)
18168    }
18169
18170    #[tokio::test]
18171    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18172        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18173        runner.state.status = RunStatus::Voting;
18174        runner.state.base_sync = None;
18175        runner.state.base_sync_recovery = Default::default();
18176        let scratch = runner.state.dir().join("base-sync");
18177        std::fs::create_dir_all(&scratch).unwrap();
18178        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18179        runner.sync_to_base().await.unwrap();
18180        assert!(runner.state.resource_block.is_some());
18181        assert!(!runner.state.base_sync_blocked());
18182        assert!(runner.state.base_sync.is_none());
18183        assert_eq!(
18184            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18185            "keep"
18186        );
18187        assert_eq!(runner.state.base_episode_used(), 0);
18188        assert!(runner.state.base_sync_recovery.operations.is_empty());
18189        assert!(runner.state.rebase_fixes.is_empty());
18190        assert_eq!(
18191            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18192            head
18193        );
18194        std::fs::remove_dir_all(&scratch).unwrap();
18195        runner.state.resource_block = None;
18196        runner.sync_to_base().await.unwrap();
18197        assert!(!runner.state.base_sync_blocked());
18198        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18199        assert_eq!(runner.state.base_episode_used(), 1);
18200        assert!(runner.state.base_sync_recovery.operations[0].finished);
18201        assert!(runner.state.rebase_fixes.is_empty());
18202        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18203        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18204    }
18205
18206    #[tokio::test]
18207    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18208        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18209        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18210        runner.state.base_sync_recovery = Default::default();
18211        runner.state.task_instruction = Some("fixture".into());
18212        runner.state.config.agents = vec![spec("fixture")];
18213        runner.state.config.graph.review_rounds = 0;
18214        runner.state.config.merge.mode = MergeMode::None;
18215        runner.state.driver_exited = true;
18216        let sync = runner.state.base_sync.as_mut().unwrap();
18217        sync.conflict = None;
18218        sync.attempts = 0;
18219        runner.state.reserve_base_operation(&head, &tip);
18220        runner.state.finish_base_operation(None);
18221        let detail = format!(
18222            "fix/retained conflicts with origin/main and did not rebase: \
18223             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18224             remaining conflicted path(s): none recorded; git said: \
18225             warning: execution failed: {}",
18226            git::REBASE_EXEC
18227        );
18228        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18229        runner.state.record_base_sync_stop(&head);
18230        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18231            unstarted: false,
18232            agent: "fixture".into(),
18233            paths: Vec::new(),
18234            from: Some(head.clone()),
18235            finished: true,
18236            error: None,
18237            stop: None,
18238            onto: None,
18239            index_outside: None,
18240            launcher: None,
18241            infra: None,
18242            outage: None,
18243        });
18244        runner.state.save().unwrap();
18245        assert_eq!(
18246            crate::resume::validate(&crate::run::home(), &runner.state.id)
18247                .unwrap()
18248                .id,
18249            runner.state.id
18250        );
18251
18252        let dirty = runner.state.repo.join("owner-work");
18253        std::fs::write(&dirty, "keep").unwrap();
18254        runner.sync_to_base().await.unwrap();
18255        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18256        assert!(runner.state.base_sync_recovery.operations[0].finished);
18257        assert!(runner.state.base_sync_blocked());
18258        std::fs::remove_file(dirty).unwrap();
18259
18260        let queue = crate::queue::Queue::open();
18261        let id = runner.state.id.clone();
18262        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18263        let _claim = queue.claim(&owner).unwrap();
18264        let mut task = queue.get(&owner).unwrap();
18265        let config = tmp.path().join("test-config.toml");
18266        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18267        let opts = crate::daemon::Opts {
18268            repo: task.repo.clone(),
18269            config: Some(config),
18270            ..Default::default()
18271        };
18272        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18273        let task = queue.get(&owner).unwrap();
18274        assert_eq!(
18275            task.runs.as_slice(),
18276            std::slice::from_ref(&id),
18277            "{:?}",
18278            task.hold_reason
18279        );
18280        runner.state = RunState::load(&id).unwrap();
18281        assert!(!runner.state.base_sync_blocked());
18282        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18283        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18284        assert!(runner.state.base_sync_recovery.operations[0].finished);
18285        assert_eq!(
18286            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18287            detail
18288        );
18289        assert_eq!(runner.state.rebase_fixes.len(), 1);
18290        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18291    }
18292
18293    #[cfg(unix)]
18294    #[tokio::test]
18295    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18296        for routed in [false, true] {
18297            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18298            let home = crate::run::home();
18299            let queue = crate::queue::Queue::open();
18300            let task = queue.get(&owner).unwrap();
18301            runner.state.task_instruction = Some(task.instruction.clone());
18302            runner.state.driver_exited = true;
18303            runner.state.save().unwrap();
18304            let questions = crate::ask::Questions::at(home.join("questions"));
18305            let mut q = crate::ask::Question::new(
18306                runner.state.id.clone(),
18307                "base-recovery".into(),
18308                "owner".into(),
18309                "Recover bounded base movement?".into(),
18310                String::new(),
18311                vec!["recover".into()],
18312            );
18313            q.actions.insert(
18314                "recover".into(),
18315                crate::ask::ChoiceAction::RecoverBase {
18316                    run: runner.state.id.clone(),
18317                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18318                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18319                },
18320            );
18321            q.routed_task = Some(owner.clone());
18322            q.answer(crate::ask::Answer::Choice("recover".into()))
18323                .unwrap();
18324            questions.put(&mut q).unwrap();
18325            crate::base_recovery_control::recover(
18326                &queue,
18327                &home,
18328                crate::base_recovery_control::Request {
18329                    run: runner.state.id.clone(),
18330                    head: head.clone(),
18331                    actor: "decisions".into(),
18332                    request: q.id.clone(),
18333                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18334                    expected_stop: Some((
18335                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18336                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18337                    )),
18338                },
18339            )
18340            .await
18341            .unwrap();
18342            if routed {
18343                questions
18344                    .update(&q.id, |q| {
18345                        q.routed_task = Some("another-owner".into());
18346                        Ok(())
18347                    })
18348                    .unwrap();
18349            } else {
18350                let mut task = queue.get(&owner).unwrap();
18351                task.hold_manual(Some("new owner decision".into()));
18352                // Keep the generation to exercise the separate owner-decision binding.
18353                task.status = crate::queue::TaskStatus::Queued;
18354                queue.put(&mut task).unwrap();
18355            }
18356            runner.state = RunState::load(&runner.state.id).unwrap();
18357            runner.sync_to_base().await.unwrap();
18358            let approval = runner
18359                .state
18360                .base_sync_recovery
18361                .authorizations
18362                .last()
18363                .unwrap();
18364            assert!(approval.consumed);
18365            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18366                "routing"
18367            } else {
18368                "owner decision"
18369            }));
18370            assert_eq!(
18371                runner.state.base_sync.as_ref().unwrap().attempts,
18372                BASE_SYNC_ROUNDS
18373            );
18374            assert_eq!(
18375                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18376                head
18377            );
18378        }
18379    }
18380
18381    #[cfg(unix)]
18382    #[tokio::test]
18383    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
18384        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
18385        if std::env::var_os(CHILD).is_none() {
18386            let home = tempfile::tempdir().unwrap();
18387            let output = std::process::Command::new(std::env::current_exe().unwrap())
18388                .args([
18389                    "--exact",
18390                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
18391                    "--nocapture",
18392                ])
18393                .env(CHILD, "1")
18394                .env("MAGI_HOME", home.path())
18395                .env("MAGI_WORKER_HOME", home.path())
18396                .env("MAGI_WORKER_ID", "abcdef")
18397                .output()
18398                .unwrap();
18399            assert!(
18400                output.status.success()
18401                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18402                "{}\n{}",
18403                String::from_utf8_lossy(&output.stdout),
18404                String::from_utf8_lossy(&output.stderr)
18405            );
18406            return;
18407        }
18408        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
18409        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18410        let home = crate::run::home();
18411        let queue = crate::queue::Queue::open();
18412        let mut owner = queue.get(&task).unwrap();
18413        owner.release_operator("test-release", None);
18414        owner.start(runner.state.id.clone());
18415        queue.put(&mut owner).unwrap();
18416        runner.state.driver_exited = true;
18417        runner.state.task_instruction = Some(owner.instruction.clone());
18418        runner.state.save().unwrap();
18419        let _claim = queue.claim(&task).unwrap();
18420        let reserve = |id: &str| {
18421            let directory = home.join("workers/jobs").join(id);
18422            std::fs::create_dir_all(&directory).unwrap();
18423            let job = crate::worker::Job {
18424                id: id.into(),
18425                sequence: 1,
18426                kind: "task".into(),
18427                key: format!("task:{task}"),
18428                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
18429                generation: "fixture-generation".into(),
18430                version: None,
18431                status: crate::worker::Status::Running,
18432                result: None,
18433                pid: Some(std::process::id()),
18434                created_at: 0,
18435                finished_at: None,
18436            };
18437            std::fs::write(
18438                directory.join("job.json"),
18439                serde_json::to_vec(&job).unwrap(),
18440            )
18441            .unwrap();
18442            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
18443        };
18444        let _own = reserve("abcdef");
18445        let other = reserve("fedcba");
18446        assert!(
18447            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18448                .await
18449                .is_err()
18450        );
18451        assert!(
18452            RunState::load(&runner.state.id)
18453                .unwrap()
18454                .base_sync_recovery
18455                .authorizations
18456                .is_empty()
18457        );
18458        drop(other);
18459        assert!(crate::daemon::is_working_on(
18460            &home,
18461            &runner.state.id,
18462            Timestamp::now()
18463        ));
18464        assert!(
18465            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
18466        );
18467        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18468            .await
18469            .unwrap();
18470        assert!(
18471            RunState::load(&runner.state.id)
18472                .unwrap()
18473                .base_recovery_pending()
18474        );
18475    }
18476
18477    #[cfg(unix)]
18478    #[tokio::test]
18479    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
18480        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18481        let home = crate::run::home();
18482        runner.state.driver_pid = Some(std::process::id());
18483        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
18484        runner.state.driver_exited = false;
18485        runner.state.begin_pass();
18486        runner.state.save().unwrap();
18487        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
18488        driver.record(&runner.state).unwrap();
18489        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
18490        // Preserve the durable claim as if the process died before Drop saved.
18491        drop(driver);
18492        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
18493        assert_eq!(
18494            runner.state.liveness_under(&home, false),
18495            crate::run::Liveness::Dead
18496        );
18497        let queue = crate::queue::Queue::open();
18498        let _claim = queue.claim(&task).unwrap();
18499        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18500            .await
18501            .unwrap();
18502        let disk = RunState::load(&runner.state.id).unwrap();
18503        assert!(!disk.driver_exited);
18504        assert!(disk.base_recovery_pending());
18505    }
18506
18507    #[cfg(unix)]
18508    #[tokio::test]
18509    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18510        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18511        if std::env::var_os(CHILD).is_none() {
18512            use std::os::unix::fs::PermissionsExt;
18513            let tmp = tempfile::tempdir().unwrap();
18514            let gh = tmp.path().join("gh");
18515            std::fs::write(&gh, r#"#!/bin/sh
18516case "$1 $2" in
18517  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18518  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18519  *) exit 2 ;;
18520esac
18521"#).unwrap();
18522            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18523            let mut paths = vec![tmp.path().to_path_buf()];
18524            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18525            let output = std::process::Command::new(std::env::current_exe().unwrap())
18526                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18527                .env(CHILD, "1")
18528                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18529                .env("PATH", std::env::join_paths(paths).unwrap())
18530                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18531                .output().unwrap();
18532            assert!(
18533                output.status.success()
18534                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18535                "{}\n{}",
18536                String::from_utf8_lossy(&output.stdout),
18537                String::from_utf8_lossy(&output.stderr)
18538            );
18539            return;
18540        }
18541        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18542        let repo = runner.state.repo.clone();
18543        git::git(&repo, &["checkout", "main"]).await.unwrap();
18544        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18545        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18546        git::git(&repo, &["checkout", "fix/retained"])
18547            .await
18548            .unwrap();
18549        runner.state.pr = Some(crate::run::PrRecord {
18550            url: "https://example.test/project/pull/1".into(),
18551            number: 1,
18552            state: "open".into(),
18553            checks: "unknown".into(),
18554            round: 0,
18555            rounds: 1,
18556            red_at_merge: Vec::new(),
18557        });
18558        runner.sync_to_base().await.unwrap();
18559        assert_eq!(runner.state.status, RunStatus::Blocked);
18560        assert_eq!(
18561            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18562            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18563        );
18564        assert!(runner.state.base_sync_closure_pending());
18565        assert!(crate::handover::can_resume(&runner.state));
18566        let queue = crate::queue::Queue::open();
18567        assert!(!crate::base_sync_recovery::held_task(
18568            &queue,
18569            &queue.get(&task).unwrap()
18570        ));
18571        assert!(runner.state.authorize_base_sync(&task).is_err());
18572        // Legacy closure stops have no typed stop but must retain the checkpoint.
18573        runner.state.base_sync_recovery.stop = None;
18574        runner.state.status = RunStatus::Voting;
18575        runner.state.gate_ran = true;
18576        runner.state.config.graph.review_rounds = 0;
18577        runner.state.save().unwrap();
18578        assert!(crate::handover::can_resume(&runner.state));
18579        runner.state = RunState::load(&runner.state.id).unwrap();
18580        runner.execute_graph().await.unwrap();
18581        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18582        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18583        assert_eq!(
18584            runner.state.base_sync.as_ref().unwrap().attempts,
18585            BASE_SYNC_ROUNDS
18586        );
18587        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18588        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18589        assert!(runner.state.reviews.is_empty());
18590        assert!(runner.state.gate.is_empty());
18591    }
18592
18593    #[cfg(unix)]
18594    #[tokio::test]
18595    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18596        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18597        runner.state.driver_exited = true;
18598        runner.state.save().unwrap();
18599        let home = crate::run::home();
18600        let queue = crate::queue::Queue::open();
18601        let _claim = queue.claim(&task).unwrap();
18602        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18603        assert!(
18604            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18605                .await
18606                .is_err()
18607        );
18608        drop(lease);
18609        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18610        assert!(
18611            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18612                .await
18613                .is_err()
18614        );
18615        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18616        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18617            .await
18618            .unwrap();
18619        let disk = RunState::load(&runner.state.id).unwrap();
18620        assert!(disk.base_recovery_pending());
18621        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18622        assert!(
18623            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18624                .await
18625                .is_err()
18626        );
18627        assert_eq!(
18628            RunState::load(&runner.state.id)
18629                .unwrap()
18630                .base_sync_recovery
18631                .authorizations
18632                .len(),
18633            1
18634        );
18635        let mut owner = queue.get(&task).unwrap();
18636        owner.runs.push("20260101-000000-ffff".into());
18637        queue.put(&mut owner).unwrap();
18638        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18639            .await
18640            .unwrap_err();
18641        assert!(error.to_string().contains("run task ownership changed"));
18642    }
18643
18644    #[cfg(unix)]
18645    #[tokio::test]
18646    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18647        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18648        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18649        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18650        legacy["status"] = serde_json::json!("voting");
18651        runner.state = serde_json::from_value(legacy).unwrap();
18652        runner.state.save().unwrap();
18653        for _ in 0..3 {
18654            runner.execute_graph().await.unwrap();
18655            assert_eq!(runner.state.status, RunStatus::Blocked);
18656            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18657            assert!(!crate::handover::can_resume(&runner.state));
18658            assert_eq!(
18659                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18660                head
18661            );
18662            assert!(runner.state.reviews.is_empty());
18663            assert!(!runner.state.gate_ran);
18664        }
18665        let notice = crate::notices::run_ended(&runner.state).unwrap();
18666        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18667        runner.state.begin_pass();
18668        runner.state.status = RunStatus::Voting;
18669        runner.deliberate().await.unwrap();
18670        runner.vote().await.unwrap();
18671        runner.finish_after_tally().await.unwrap();
18672        assert_eq!(runner.state.status, RunStatus::Blocked);
18673        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18674        assert_eq!(
18675            crate::notices::run_ended(&runner.state).unwrap().since,
18676            notice.since
18677        );
18678    }
18679
18680    #[cfg(unix)]
18681    #[tokio::test]
18682    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18683        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18684        for detail in [
18685            "fix/retained conflicts with origin/main and did not rebase: conflict",
18686            "rebased fix/retained locally but origin refused the push",
18687            "unknown failure",
18688        ] {
18689            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18690            runner.state.record_base_sync_stop(&head);
18691            assert!(runner.state.authorize_base_sync(&task).is_err());
18692            runner.state.status = RunStatus::Voting;
18693            runner.execute_graph().await.unwrap();
18694            assert_eq!(runner.state.status, RunStatus::Blocked);
18695            assert!(!crate::handover::can_resume(&runner.state));
18696            assert_eq!(
18697                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18698                head
18699            );
18700        }
18701    }
18702
18703    #[cfg(unix)]
18704    #[tokio::test]
18705    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18706        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18707        runner.state.authorize_base_sync(&task).unwrap();
18708        assert!(runner.state.consume_base_recovery(&head));
18709        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18710        runner.state.reserve_base_operation(&head, &tip);
18711        runner.state.save().unwrap();
18712        runner.state = RunState::load(&runner.state.id).unwrap();
18713        assert!(!runner.state.consume_base_recovery(&head));
18714        runner.sync_to_base().await.unwrap();
18715        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18716        assert_eq!(runner.state.base_episode_used(), 1);
18717        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18718        assert!(
18719            runner
18720                .state
18721                .base_sync_recovery
18722                .operations
18723                .last()
18724                .unwrap()
18725                .finished
18726        );
18727        assert!(!runner.state.base_sync_blocked());
18728        runner.sync_to_base().await.unwrap();
18729        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18730    }
18731
18732    #[cfg(unix)]
18733    #[tokio::test]
18734    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18735        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18736        // Both historical diagnostic spellings retain an exhaustion identity.
18737        let original = runner
18738            .state
18739            .base_sync
18740            .as_ref()
18741            .unwrap()
18742            .conflict
18743            .clone()
18744            .unwrap();
18745        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18746            original
18747                .replace("synchronization(s)", "rebase(s)")
18748                .replace("synchronizing", "rebasing"),
18749        );
18750        runner.state.base_sync_recovery = Default::default();
18751        runner.state.record_base_sync_stop(&head);
18752        assert_eq!(
18753            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18754            crate::base_sync_recovery::StopKind::Exhausted
18755        );
18756        runner.state.authorize_base_sync(&task).unwrap();
18757        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18758        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18759            .as_object_mut()
18760            .unwrap();
18761        auth.remove("interval");
18762        auth.remove("scope");
18763        runner.state = serde_json::from_value(legacy).unwrap();
18764        assert!(runner.state.consume_base_recovery(&head));
18765        assert_eq!(runner.state.base_episode_used(), 3);
18766        runner.sync_to_base().await.unwrap();
18767        assert_eq!(runner.state.base_episode_used(), 4);
18768        runner.state.resource_block = Some(crate::run::ResourceBlock {
18769            node: "gate".into(),
18770            kind: "cache".into(),
18771            detail: "legacy wait".into(),
18772            at: Timestamp::now(),
18773            cause: crate::run::ResourceBlockCause::Unrecorded,
18774        });
18775        runner.state.save().unwrap();
18776        assert!(
18777            runner
18778                .state
18779                .base_sync_recovery
18780                .episodes
18781                .last()
18782                .unwrap()
18783                .boundary
18784                .is_none()
18785        );
18786        runner.state.resource_block = None;
18787        advance_base_fixture(&runner).await;
18788        runner.sync_to_base().await.unwrap();
18789        assert!(runner.state.base_sync_blocked());
18790        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18791    }
18792
18793    #[cfg(unix)]
18794    async fn advance_base_fixture(runner: &Runner) {
18795        let repo = &runner.state.repo;
18796        for args in [
18797            vec!["checkout", "main"],
18798            vec!["commit", "--allow-empty", "-m", "base advanced"],
18799            vec!["push", "origin", "main"],
18800            vec!["checkout", "fix/retained"],
18801        ] {
18802            git::git(repo, &args).await.unwrap();
18803        }
18804    }
18805
18806    #[cfg(unix)]
18807    fn fresh_base_interval_fixture(runner: &mut Runner) {
18808        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18809        runner.state.base_sync.as_mut().unwrap().conflict = None;
18810        runner.state.base_sync_recovery = Default::default();
18811        runner.state.status = RunStatus::Voting;
18812    }
18813
18814    #[cfg(unix)]
18815    #[tokio::test]
18816    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18817        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18818        fresh_base_interval_fixture(&mut runner);
18819        runner.state.begin_pass();
18820        runner.sync_to_base().await.unwrap();
18821        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18822        runner.state.resource_block = Some(crate::run::ResourceBlock {
18823            node: "gate".into(),
18824            kind: "build cache".into(),
18825            detail: "busy".into(),
18826            at: Timestamp::now(),
18827            cause: crate::run::ResourceBlockCause::Timeout {
18828                waited_secs: 1,
18829                limit_secs: 1,
18830            },
18831        });
18832        runner.state.save().unwrap();
18833        let queue = crate::queue::Queue::open();
18834        let mut owner = queue.get(&task).unwrap();
18835        runner.state.task_instruction = Some(owner.instruction.clone());
18836        owner.release_operator("fixture-owner", None);
18837        queue.put(&mut owner).unwrap();
18838        let approval = owner.resumption.clone().unwrap();
18839        runner.state.resource_block = None;
18840        runner.state.save().unwrap();
18841        runner.state = RunState::load(&runner.state.id).unwrap();
18842        advance_base_fixture(&runner).await;
18843        runner.sync_to_base().await.unwrap();
18844        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18845        assert_eq!(runner.state.base_episode_used(), 1);
18846        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18847        assert!(
18848            runner.state.base_sync_recovery.episodes[0]
18849                .boundary
18850                .as_ref()
18851                .unwrap()
18852                .consumed
18853        );
18854        assert!(
18855            !runner
18856                .state
18857                .renew_base_episode(&task, &approval, &head, "base")
18858        );
18859        for _ in 0..3 {
18860            owner.release_operator("fixture-owner", None);
18861            queue.put(&mut owner).unwrap();
18862            runner.state = RunState::load(&runner.state.id).unwrap();
18863            runner.state.begin_pass();
18864            runner.sync_to_base().await.unwrap();
18865            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18866            assert_eq!(runner.state.base_episode_used(), 1);
18867        }
18868        runner.state.resource_block = Some(crate::run::ResourceBlock {
18869            node: "gate".into(),
18870            kind: "disk pressure".into(),
18871            detail: "free space required".into(),
18872            at: Timestamp::now(),
18873            cause: crate::run::ResourceBlockCause::Other,
18874        });
18875        runner.state.end_pass_parked(ParkCause::Interrupt {
18876            reason: "disk pressure".into(),
18877        });
18878        runner.state.save().unwrap();
18879        owner.release_operator("fixture-owner-after-disk", None);
18880        queue.put(&mut owner).unwrap();
18881        runner.state.resource_block = None;
18882        advance_base_fixture(&runner).await;
18883        runner.sync_to_base().await.unwrap();
18884        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18885        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18886        assert_eq!(runner.state.base_episode_used(), 1);
18887        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18888    }
18889
18890    #[cfg(unix)]
18891    #[tokio::test]
18892    async fn base_recovery_continuous_advancement_stops_at_four() {
18893        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18894        fresh_base_interval_fixture(&mut runner);
18895        for spent in 1..=BASE_SYNC_ROUNDS {
18896            runner.sync_to_base().await.unwrap();
18897            assert!(!runner.state.base_sync_blocked());
18898            assert_eq!(runner.state.base_episode_used(), spent);
18899            advance_base_fixture(&runner).await;
18900        }
18901        runner.sync_to_base().await.unwrap();
18902        assert_eq!(
18903            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18904            crate::base_sync_recovery::StopKind::Exhausted
18905        );
18906        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18907        assert!(stop.unverified_sync);
18908        let action = runner.state.base_sync_next_action();
18909        assert!(action.contains("never reached its gate"));
18910        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18911        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18912        runner.state = RunState::load(&runner.state.id).unwrap();
18913        runner.sync_to_base().await.unwrap();
18914        assert_eq!(runner.state.base_episode_used(), 4);
18915        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18916    }
18917
18918    #[cfg(unix)]
18919    #[tokio::test]
18920    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18921        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18922        runner.state.ensure_base_episode();
18923        // Verification progress alone is not evidence of a successful sync.
18924        runner.state.record_base_progress(&head);
18925        runner.state.base_sync_recovery.stop = None;
18926        runner.state.record_base_sync_stop(&head);
18927        assert!(
18928            !runner
18929                .state
18930                .base_sync_recovery
18931                .stop
18932                .as_ref()
18933                .unwrap()
18934                .unverified_sync
18935        );
18936
18937        runner.state.finish_base_operation(Some(&head));
18938        // A gate for another head cannot verify this synchronization.
18939        runner.state.gate_ran = true;
18940        runner.state.gate_head = Some("older-head".into());
18941        runner.state.base_sync_recovery.stop = None;
18942        runner.state.record_base_sync_stop(&head);
18943        runner.state.save().unwrap();
18944        runner.state = RunState::load(&runner.state.id).unwrap();
18945        assert!(
18946            runner
18947                .state
18948                .base_sync_recovery
18949                .stop
18950                .as_ref()
18951                .unwrap()
18952                .unverified_sync
18953        );
18954
18955        runner.state.gate_head = Some(head.clone());
18956        runner.state.base_sync_recovery.stop = None;
18957        runner.state.record_base_sync_stop(&head);
18958        assert!(
18959            !runner
18960                .state
18961                .base_sync_recovery
18962                .stop
18963                .as_ref()
18964                .unwrap()
18965                .unverified_sync
18966        );
18967        assert!(
18968            !runner
18969                .state
18970                .base_sync_next_action()
18971                .contains("never reached its gate")
18972        );
18973
18974        // Historical records cannot establish the missing synchronization evidence.
18975        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18976        legacy["base_sync_recovery"]["stop"]
18977            .as_object_mut()
18978            .unwrap()
18979            .remove("unverified_sync");
18980        legacy["base_sync_recovery"]["episodes"][0]
18981            .as_object_mut()
18982            .unwrap()
18983            .remove("last_sync_head");
18984        runner.state = serde_json::from_value(legacy).unwrap();
18985        assert!(
18986            !runner
18987                .state
18988                .base_sync_recovery
18989                .stop
18990                .as_ref()
18991                .unwrap()
18992                .unverified_sync
18993        );
18994        assert!(
18995            runner.state.base_sync_recovery.episodes[0]
18996                .last_sync_head
18997                .is_none()
18998        );
18999    }
19000
19001    #[cfg(unix)]
19002    #[tokio::test]
19003    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19004        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19005        runner.state.authorize_base_sync(&task).unwrap();
19006        assert!(
19007            runner
19008                .state
19009                .base_sync_next_action()
19010                .contains("Approval recorded")
19011        );
19012        assert!(
19013            runner
19014                .state
19015                .base_sync_next_action()
19016                .contains("4/4 in episode 0, 4 lifetime")
19017        );
19018        assert!(runner.state.consume_base_recovery(&head));
19019        assert!(
19020            runner
19021                .state
19022                .base_sync_next_action()
19023                .contains("0/4 in episode 1, 4 lifetime")
19024        );
19025    }
19026
19027    #[cfg(unix)]
19028    #[tokio::test]
19029    async fn base_recovery_changed_head_invalidates_without_spending() {
19030        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19031        runner.state.authorize_base_sync(&task).unwrap();
19032        git::git(
19033            &runner.state.repo,
19034            &["commit", "--allow-empty", "-m", "external head change"],
19035        )
19036        .await
19037        .unwrap();
19038        runner.sync_to_base().await.unwrap();
19039        let a = runner
19040            .state
19041            .base_sync_recovery
19042            .authorizations
19043            .last()
19044            .unwrap();
19045        assert!(a.consumed);
19046        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19047        runner.state = RunState::load(&runner.state.id).unwrap();
19048        assert!(
19049            runner
19050                .state
19051                .base_sync_next_action()
19052                .contains("Approval invalidated")
19053        );
19054        assert!(!runner.state.base_recovery_pending());
19055        assert!(runner.state.base_sync_blocked());
19056        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19057    }
19058
19059    #[cfg(unix)]
19060    #[tokio::test]
19061    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19062        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19063        runner.state.driver_exited = true;
19064        runner.state.save().unwrap();
19065        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19066            .await
19067            .unwrap();
19068        runner.state = RunState::load(&runner.state.id).unwrap();
19069        advance_base_fixture(&runner).await;
19070        runner.sync_to_base().await.unwrap();
19071        let a = runner
19072            .state
19073            .base_sync_recovery
19074            .authorizations
19075            .last()
19076            .unwrap();
19077        assert!(
19078            a.consumed
19079                && a.invalidated
19080                    .as_deref()
19081                    .unwrap()
19082                    .contains("fetched base changed")
19083        );
19084        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19085        assert_eq!(
19086            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19087            head
19088        );
19089        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19090            .await
19091            .unwrap();
19092        runner.state = RunState::load(&runner.state.id).unwrap();
19093        runner.sync_to_base().await.unwrap();
19094        assert!(!runner.state.base_sync_blocked());
19095        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19096    }
19097
19098    #[cfg(unix)]
19099    #[tokio::test]
19100    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19101        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19102        runner.state.authorize_base_sync(&task).unwrap();
19103        assert!(runner.state.consume_base_recovery(&head));
19104        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19105        runner.state.reserve_base_operation(&head, &tip);
19106        runner.state.save().unwrap();
19107        let scratch = runner.state.dir().join("base-sync");
19108        assert_eq!(
19109            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19110                .await
19111                .unwrap(),
19112            crate::rebase::Rebased::Applied
19113        );
19114        runner.state = RunState::load(&runner.state.id).unwrap();
19115        runner.sync_to_base().await.unwrap();
19116        assert!(
19117            runner
19118                .state
19119                .base_sync_recovery
19120                .operations
19121                .last()
19122                .unwrap()
19123                .finished
19124        );
19125        assert_eq!(runner.state.base_episode_used(), 1);
19126        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19127        assert!(!runner.state.base_sync_blocked());
19128    }
19129
19130    #[cfg(unix)]
19131    #[tokio::test]
19132    async fn base_recovery_crash_preserves_untracked_files() {
19133        for ignored in [false, true] {
19134            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19135            runner.state.authorize_base_sync(&task).unwrap();
19136            assert!(runner.state.consume_base_recovery(&head));
19137            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19138            runner.state.reserve_base_operation(&head, &tip);
19139            runner.state.save().unwrap();
19140            let scratch = runner.state.dir().join("base-sync");
19141            assert_eq!(
19142                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19143                    .await
19144                    .unwrap(),
19145                crate::rebase::Rebased::Applied
19146            );
19147            let repo = &runner.state.repo;
19148            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19149            assert_ne!(result, head);
19150            if ignored {
19151                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19152                    .await
19153                    .unwrap();
19154                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19155            }
19156            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19157            assert!(
19158                git::git_raw(repo, &["diff", "--quiet", &head])
19159                    .await
19160                    .unwrap()
19161                    .ok()
19162            );
19163            // Resume after the branch moved, before its checkout was reset.
19164            runner.state = RunState::load(&runner.state.id).unwrap();
19165            runner.sync_to_base().await.unwrap();
19166            assert!(runner.state.base_sync_blocked());
19167            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19168            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19169            assert_eq!(
19170                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19171                result
19172            );
19173            assert_eq!(
19174                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19175                "retained work\n"
19176            );
19177            assert!(
19178                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19179                    .await
19180                    .unwrap()
19181                    .ok()
19182            );
19183        }
19184    }
19185
19186    #[cfg(unix)]
19187    #[tokio::test]
19188    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19189        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19190        runner.state.authorize_base_sync(&task).unwrap();
19191        assert!(runner.state.consume_base_recovery(&head));
19192        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19193        runner.state.reserve_base_operation(&head, &tip);
19194        runner.state.save().unwrap();
19195        let scratch = runner.state.dir().join("base-sync");
19196        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19197            .await
19198            .unwrap();
19199        git::sync_to_head(&runner.state.repo).await.unwrap();
19200        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19201        git::git(&runner.state.repo, &["add", "foreign"])
19202            .await
19203            .unwrap();
19204        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19205            .await
19206            .unwrap();
19207        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19208        runner.state = RunState::load(&runner.state.id).unwrap();
19209        runner.sync_to_base().await.unwrap();
19210        assert!(runner.state.base_sync_blocked());
19211        assert!(
19212            !runner
19213                .state
19214                .base_sync_recovery
19215                .operations
19216                .last()
19217                .unwrap()
19218                .finished
19219        );
19220        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19221        assert_eq!(
19222            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19223            foreign_head
19224        );
19225    }
19226
19227    #[cfg(unix)]
19228    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19229    {
19230        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19231        fresh_base_interval_fixture(&mut runner);
19232        let repo = &runner.state.repo;
19233        git::git(repo, &["checkout", "main"]).await.unwrap();
19234        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19235        git::git(repo, &["add", "retained"]).await.unwrap();
19236        git::git(repo, &["commit", "-m", "upstream retained change"])
19237            .await
19238            .unwrap();
19239        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19240        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19241        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19242        let scratch = runner.state.dir().join("base-sync");
19243        assert!(matches!(
19244            git::rebase_start(repo, &scratch, "fix/retained", &tip)
19245                .await
19246                .unwrap(),
19247            git::RebaseStart::Conflicted(_)
19248        ));
19249        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
19250            unstarted: false,
19251            agent: "fixture".into(),
19252            paths: vec!["retained".into()],
19253            from: Some(head.clone()),
19254            onto: None,
19255            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
19256            index_outside: None,
19257            finished: false,
19258            error: None,
19259            launcher: None,
19260            infra: None,
19261            outage: None,
19262        });
19263        (tmp, runner, head, tip, scratch)
19264    }
19265
19266    #[cfg(unix)]
19267    #[tokio::test]
19268    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
19269        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19270        // A resource stop from before reservations existed, with resolved
19271        // contents left for the launcher's ordinary staging continuation.
19272        std::fs::write(
19273            scratch.join("retained"),
19274            "upstream and retained resolution\n",
19275        )
19276        .unwrap();
19277        runner.state.resource_block = Some(crate::run::ResourceBlock {
19278            node: "rebase".into(),
19279            kind: "repository coordination".into(),
19280            detail: "busy".into(),
19281            at: Timestamp::now(),
19282            cause: crate::run::ResourceBlockCause::Other,
19283        });
19284        runner.state.save().unwrap();
19285        // Advance the remote without moving either checkout participating
19286        // in the standing rebase.
19287        let newer = git::git(
19288            &runner.state.repo,
19289            &[
19290                "commit-tree",
19291                "main^{tree}",
19292                "-p",
19293                "main",
19294                "-m",
19295                "base advanced during wait",
19296            ],
19297        )
19298        .await
19299        .unwrap();
19300        git::git(
19301            &runner.state.repo,
19302            &[
19303                "push",
19304                "origin",
19305                &format!("{}:refs/heads/main", newer.trim()),
19306            ],
19307        )
19308        .await
19309        .unwrap();
19310        runner.state = RunState::load(&runner.state.id).unwrap();
19311        runner.state.resource_block = None;
19312        runner.sync_to_base().await.unwrap();
19313        assert!(!runner.state.base_sync_blocked());
19314        let op = &runner.state.base_sync_recovery.operations[0];
19315        assert_eq!(op.head, head);
19316        assert_eq!(op.tip, tip);
19317        assert!(op.finished);
19318        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19319        assert_eq!(runner.state.rebase_fixes.len(), 1);
19320        let latest = git::rev_parse(&runner.state.repo, "origin/main")
19321            .await
19322            .unwrap();
19323        assert_ne!(latest, tip);
19324        runner.state = RunState::load(&runner.state.id).unwrap();
19325        runner.sync_to_base().await.unwrap();
19326        assert!(!runner.state.base_sync_blocked());
19327        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
19328        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
19329        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19330    }
19331
19332    #[cfg(unix)]
19333    #[tokio::test]
19334    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
19335        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19336        runner.state.reserve_base_operation(&head, &tip);
19337        runner.state.save().unwrap();
19338        std::fs::write(
19339            scratch.join("retained"),
19340            "upstream and retained resolution\n",
19341        )
19342        .unwrap();
19343        git::git(&scratch, &["add", "retained"]).await.unwrap();
19344        git::git(
19345            &scratch,
19346            &["-c", "core.editor=true", "rebase", "--continue"],
19347        )
19348        .await
19349        .unwrap();
19350        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19351        assert!(
19352            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19353                .await
19354                .unwrap()
19355                .is_empty()
19356        );
19357        assert_eq!(
19358            crate::rebase::finish(
19359                &mut runner.state,
19360                &scratch,
19361                "fix/retained",
19362                &head,
19363                &tip,
19364                &["retained".into()],
19365                ""
19366            )
19367            .await
19368            .unwrap(),
19369            crate::rebase::Rebased::Applied
19370        );
19371        assert!(!scratch.exists());
19372        // Simulate losing the caller before finish_base_operation/save.
19373        runner.state = RunState::load(&runner.state.id).unwrap();
19374        let op = &runner.state.base_sync_recovery.operations[0];
19375        assert!(!op.finished);
19376        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
19377        runner.sync_to_base().await.unwrap();
19378        assert!(!runner.state.base_sync_blocked());
19379        assert!(runner.state.base_sync_recovery.operations[0].finished);
19380        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19381        assert_eq!(runner.state.rebase_fixes.len(), 1);
19382        let winner = runner.state.winner().unwrap().clone();
19383        let wait = runner.repository_wait();
19384        assert!(
19385            verify_current_head(&mut runner.state, &winner, &wait)
19386                .await
19387                .unwrap()
19388        );
19389        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19390    }
19391
19392    #[cfg(unix)]
19393    #[tokio::test]
19394    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
19395        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
19396            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19397            runner.state.reserve_base_operation(&head, &tip);
19398            runner.state.save().unwrap();
19399            std::fs::write(
19400                scratch.join("retained"),
19401                "upstream and retained resolution\n",
19402            )
19403            .unwrap();
19404            git::git(&scratch, &["add", "retained"]).await.unwrap();
19405            git::git(
19406                &scratch,
19407                &["-c", "core.editor=true", "rebase", "--continue"],
19408            )
19409            .await
19410            .unwrap();
19411            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19412            assert!(!git::rebase_in_progress(&scratch).await);
19413            assert!(
19414                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19415                    .await
19416                    .unwrap()
19417                    .is_empty()
19418            );
19419            match damage {
19420                Some("record") => {
19421                    let path =
19422                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
19423                            .await
19424                            .unwrap();
19425                    std::fs::write(scratch.join(path), "").unwrap();
19426                }
19427                Some("foreign") => {
19428                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
19429                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
19430                    git::git(&scratch, &["commit", "-m", "foreign work"])
19431                        .await
19432                        .unwrap();
19433                }
19434                Some("dirty") => {
19435                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
19436                }
19437                _ => {}
19438            }
19439            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19440            // Crash immediately after Git continuation, before finish runs.
19441            runner.state = RunState::load(&runner.state.id).unwrap();
19442            assert!(
19443                runner.state.base_sync_recovery.operations[0]
19444                    .validated_head
19445                    .is_none()
19446            );
19447            runner.sync_to_base().await.unwrap();
19448            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19449            assert_eq!(runner.state.base_episode_used(), 1);
19450            assert_eq!(runner.state.rebase_fixes.len(), 1);
19451            assert_eq!(
19452                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19453                retained_head
19454            );
19455            if damage.is_some() {
19456                assert!(runner.state.base_sync_blocked());
19457                assert!(scratch.exists());
19458                assert!(!runner.state.base_sync_recovery.operations[0].finished);
19459                assert!(
19460                    runner.state.base_sync_recovery.operations[0]
19461                        .validated_head
19462                        .is_none()
19463                );
19464            } else {
19465                assert!(!runner.state.base_sync_blocked());
19466                assert!(!scratch.exists());
19467                assert!(runner.state.base_sync_recovery.operations[0].finished);
19468                assert_eq!(
19469                    runner.state.base_sync_recovery.operations[0]
19470                        .validated_head
19471                        .as_deref(),
19472                    Some(result.as_str())
19473                );
19474                let winner = runner.state.winner().unwrap().clone();
19475                let wait = runner.repository_wait();
19476                assert!(
19477                    verify_current_head(&mut runner.state, &winner, &wait)
19478                        .await
19479                        .unwrap()
19480                );
19481                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19482                runner.state = RunState::load(&runner.state.id).unwrap();
19483                runner.sync_to_base().await.unwrap();
19484                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19485            }
19486        }
19487    }
19488
19489    #[cfg(unix)]
19490    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
19491        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19492        // This is an ordinary gate stop, not an authorized base-budget recovery.
19493        runner.state.prep_complete = Some(true);
19494        runner.state.base_sync = None;
19495        runner.state.base_sync_recovery = Default::default();
19496        runner.state.config.graph.gate_fix_rounds = 1;
19497        let mut review = review_round(true, 0, 1, 1, false, true);
19498        review.head = head.clone();
19499        review.verified_head = Some(head.clone());
19500        runner.state.reviews = vec![review];
19501        runner.state.gate = vec![CommandOutcome {
19502            command: "old gate".into(),
19503            code: Some(1),
19504            output_tail: "old failure".into(),
19505            duration_ms: 0,
19506            resource_blocked: false,
19507            ..Default::default()
19508        }];
19509        runner.state.gate_head = Some(head.clone());
19510        runner.state.gate_ran = true;
19511        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
19512            agent: "fixture".into(),
19513            failed: runner.state.gate.clone(),
19514            notes: "spent".into(),
19515            committed: false,
19516            error: None,
19517        }];
19518        runner.state.land_approval = Some(crate::run::LandApproval {
19519            question: "old approval".into(),
19520            head: head.clone(),
19521        });
19522        runner.state.status = RunStatus::Blocked;
19523        (tmp, runner, head)
19524    }
19525
19526    #[cfg(unix)]
19527    #[tokio::test]
19528    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
19529        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
19530        runner.sync_to_base().await.unwrap();
19531        let winner = runner.state.winner().unwrap().clone();
19532        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
19533        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
19534        assert_ne!(head, base);
19535        runner.state.config.verify.e2e = vec![format!(
19536            "git update-ref refs/remotes/origin/main {head} && false"
19537        )];
19538        let wait = repository_wait(&runner.state, None);
19539        assert!(
19540            !verify_current_head(&mut runner.state, &winner, &wait)
19541                .await
19542                .unwrap()
19543        );
19544        assert_eq!(
19545            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
19546                .await
19547                .unwrap(),
19548            head
19549        );
19550        assert_eq!(
19551            runner
19552                .state
19553                .head_e2e
19554                .as_ref()
19555                .unwrap()
19556                .base_commit
19557                .as_deref(),
19558            Some(base.as_str())
19559        );
19560    }
19561
19562    #[cfg(unix)]
19563    #[tokio::test]
19564    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19565        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19566            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19567            let phases = tmp.path().join("phases");
19568            runner.state.config.verify.e2e = vec![format!(
19569                "echo e2e >> '{}'; {}",
19570                phases.display(),
19571                if e2e_ok {
19572                    "true"
19573                } else {
19574                    "echo new-e2e-failure; false"
19575                }
19576            )];
19577            runner.state.config.verify.gate = vec![format!(
19578                "echo gate >> '{}'; {}",
19579                phases.display(),
19580                if gate_ok {
19581                    "true"
19582                } else {
19583                    "echo new-gate-failure; false"
19584                }
19585            )];
19586            runner.state.save().unwrap();
19587            runner.state = RunState::load(&runner.state.id).unwrap();
19588            runner.sync_to_base().await.unwrap();
19589            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19590            assert_ne!(head, old);
19591            // Reentry after Git updated but before verification was invalidated.
19592            runner.state = RunState::load(&runner.state.id).unwrap();
19593            runner.execute_graph().await.unwrap();
19594            assert_eq!(runner.state.gate_fixes.len(), 1);
19595            assert_eq!(runner.state.reviews.len(), 1);
19596            assert_eq!(runner.state.reviews[0].head, old);
19597            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19598            assert_eq!(runner.state.verification_history.len(), 1);
19599            let history = &runner.state.verification_history[0];
19600            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19601            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19602            assert!(history.archived_at.is_some());
19603            assert_eq!(history.fixes_spent, Some(1));
19604            assert_eq!(history.gate[0].output_tail, "old failure");
19605            let archive_events: Vec<_> = runner
19606                .state
19607                .events
19608                .iter()
19609                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19610                .collect();
19611            assert_eq!(archive_events.len(), 1);
19612            assert!(archive_events[0].message.contains(&short(&old)));
19613            assert!(archive_events[0].message.contains(&short(&head)));
19614            assert!(
19615                archive_events[0]
19616                    .message
19617                    .contains("1 gate-fix round(s) already spent stay spent")
19618            );
19619            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19620            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19621            if e2e_ok {
19622                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19623                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19624            } else {
19625                assert!(!runner.state.gate_ran);
19626            }
19627            assert_eq!(
19628                runner.state.status,
19629                if e2e_ok && gate_ok {
19630                    RunStatus::Ready
19631                } else {
19632                    RunStatus::Blocked
19633                }
19634            );
19635            if !e2e_ok || !gate_ok {
19636                let cause = runner.state.verification_blocking_cause().unwrap();
19637                assert!(cause.contains(&head));
19638                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19639                // A later successful progress event must not become the cause.
19640                runner.state.event("land", "rebased successfully");
19641                let notice = crate::notices::run_ended(&runner.state).unwrap();
19642                assert!(!format!("{notice:?}").contains("rebased successfully"));
19643                assert!(runner.state.merge.is_none());
19644            }
19645            let before = std::fs::read_to_string(&phases).unwrap();
19646            runner.state.save().unwrap();
19647            runner.state = RunState::load(&runner.state.id).unwrap();
19648            runner.review_loop().await.unwrap();
19649            runner.gate().await.unwrap();
19650            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19651            assert_eq!(runner.state.verification_history.len(), 1);
19652            let history = &runner.state.verification_history[0];
19653            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19654            assert!(history.archived_at.is_some());
19655            assert_eq!(history.fixes_spent, Some(1));
19656        }
19657    }
19658
19659    #[cfg(unix)]
19660    #[tokio::test]
19661    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19662        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19663        let marker = tmp.path().join("gate-ran");
19664        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19665        runner.review_loop().await.unwrap();
19666        runner.gate().await.unwrap();
19667        assert_eq!(runner.state.status, RunStatus::Blocked);
19668        assert!(!marker.exists());
19669        assert!(runner.state.verification_history.is_empty());
19670        runner.state.gate_head = None;
19671        runner.gate().await.unwrap();
19672        assert!(marker.exists());
19673        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19674        assert_eq!(runner.state.verification_history.len(), 1);
19675        assert_eq!(runner.state.gate_fixes.len(), 1);
19676    }
19677
19678    #[cfg(unix)]
19679    #[tokio::test]
19680    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19681        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19682        runner.sync_to_base().await.unwrap();
19683        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19684        runner.state.reconcile_verification_head(&head);
19685        // Both crash-before-command and resource wait are unresolved evidence.
19686        for outcomes in [
19687            Vec::new(),
19688            vec![CommandOutcome {
19689                command: "true".into(),
19690                code: None,
19691                output_tail: "cache unavailable".into(),
19692                duration_ms: 0,
19693                resource_blocked: true,
19694                ..Default::default()
19695            }],
19696        ] {
19697            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19698                head.clone(),
19699                false,
19700                outcomes,
19701            ));
19702            runner.state.gate_ran = false;
19703            runner.state.gate.clear();
19704            runner.state.save().unwrap();
19705            runner.state = RunState::load(&runner.state.id).unwrap();
19706            runner.merge().await.unwrap();
19707            assert!(runner.state.merge.is_none());
19708            runner.review_loop().await.unwrap();
19709            runner.gate().await.unwrap();
19710            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19711            assert!(runner.state.gate_allows_progress());
19712            assert_eq!(runner.state.gate_fixes.len(), 1);
19713            assert!(runner.state.merge.is_none());
19714        }
19715        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19716        git::git(
19717            &runner.state.repo,
19718            &["commit", "--allow-empty", "-m", "external update"],
19719        )
19720        .await
19721        .unwrap();
19722        runner.merge().await.unwrap();
19723        assert!(runner.state.merge.is_none());
19724        assert_eq!(runner.state.status, RunStatus::Blocked);
19725    }
19726
19727    #[cfg(unix)]
19728    #[tokio::test]
19729    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19730        for waiting_on_gate in [false, true] {
19731            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19732            runner.sync_to_base().await.unwrap();
19733            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19734            runner.state.reconcile_verification_head(&head);
19735            if waiting_on_gate {
19736                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19737                    head.clone(),
19738                    true,
19739                    Vec::new(),
19740                ));
19741            }
19742            let cache = tmp.path().join("cache");
19743            runner.state.config.verify.e2e =
19744                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19745            runner.state.config.verify.gate = vec!["true".into()];
19746            runner.state.config.graph.timeout_resource_wait = 1;
19747            let owner =
19748                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19749            let guard =
19750                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19751                    crate::cache::AcquireOutcome::Acquired(g) => g,
19752                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19753                };
19754            runner.review_loop().await.unwrap();
19755            runner.gate().await.unwrap();
19756            assert!(!runner.state.gate_ran);
19757            assert_eq!(runner.state.gate_fixes.len(), 1);
19758            assert!(runner.state.resource_block.is_some());
19759            runner.merge().await.unwrap();
19760            assert!(runner.state.merge.is_none());
19761            drop(guard);
19762            runner.state = RunState::load(&runner.state.id).unwrap();
19763            // The driver clears the previous pass's resource stop on resume.
19764            runner.state.resource_block = None;
19765            runner.review_loop().await.unwrap();
19766            runner.gate().await.unwrap();
19767            assert!(runner.state.gate_allows_progress());
19768            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19769            assert_eq!(runner.state.gate_fixes.len(), 1);
19770        }
19771    }
19772
19773    #[cfg(unix)]
19774    #[tokio::test]
19775    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19776        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19777        runner.sync_to_base().await.unwrap();
19778        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19779        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19780        // Verification passes before pre_gate and fails on the mechanically changed head.
19781        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19782        runner.review_loop().await.unwrap();
19783        runner.gate().await.unwrap();
19784        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19785        assert_ne!(before, after);
19786        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19787        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19788        assert!(!runner.state.gate_allows_progress());
19789        runner.merge().await.unwrap();
19790        assert!(runner.state.merge.is_none());
19791        assert!(
19792            runner
19793                .state
19794                .verification_history
19795                .iter()
19796                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19797        );
19798
19799        // An incomplete review is still an independent hold on a changed head.
19800        runner.state.reviews[0].clean = false;
19801        runner.state.reviews[0].answered = 0;
19802        runner.state.config.verify.e2e = vec!["true".into()];
19803        runner.review_loop().await.unwrap();
19804        runner.gate().await.unwrap();
19805        runner.merge().await.unwrap();
19806        assert_eq!(runner.state.status, RunStatus::Blocked);
19807        assert!(runner.state.merge.is_none());
19808        assert!(
19809            runner
19810                .state
19811                .verification_blocking_cause()
19812                .unwrap()
19813                .contains("review blocked")
19814        );
19815    }
19816
19817    #[cfg(unix)]
19818    #[tokio::test]
19819    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19820        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19821        runner.state.gate_head = None;
19822        runner.state.config.verify.gate =
19823            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19824        runner.review_loop().await.unwrap();
19825        runner.gate().await.unwrap();
19826        assert_ne!(
19827            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19828            old
19829        );
19830        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19831        assert!(!runner.state.gate_allows_progress());
19832        assert_eq!(runner.state.status, RunStatus::Blocked);
19833        runner.merge().await.unwrap();
19834        assert!(runner.state.merge.is_none());
19835    }
19836
19837    #[cfg(unix)]
19838    #[tokio::test]
19839    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19840        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19841        let mut old_review = review_round(true, 0, 1, 1, false, true);
19842        old_review.head = head.clone();
19843        old_review.verified_head = Some(head.clone());
19844        runner.state.reviews = vec![old_review];
19845        runner.state.gate = vec![CommandOutcome {
19846            command: "old gate".into(),
19847            code: None,
19848            output_tail: "timed out after 2400s".into(),
19849            duration_ms: 2_400_000,
19850            resource_blocked: false,
19851            ..Default::default()
19852        }];
19853        runner.state.gate_ran = true;
19854        runner.state.gate_head = Some(head.clone());
19855        runner.state.land_approval = Some(crate::run::LandApproval {
19856            question: "old-head-approval".into(),
19857            head: head.clone(),
19858        });
19859        runner.state.authorize_base_sync(&task).unwrap();
19860        runner.sync_to_base().await.unwrap();
19861        assert!(!runner.state.base_sync_blocked());
19862        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19863        assert_ne!(head, fresh);
19864        assert_eq!(runner.state.reviews.len(), 1);
19865        assert!(!runner.state.gate_ran);
19866        let saved = &runner.state.base_sync_recovery.authorizations[0];
19867        assert_eq!(saved.reviews[0].head, head);
19868        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19869        assert!(saved.gate_ran);
19870        assert!(!saved.gate[0].ok());
19871        runner.review_loop().await.unwrap();
19872        runner.gate().await.unwrap();
19873        assert_eq!(runner.state.reviews[0].head, head);
19874        assert_eq!(
19875            runner.state.reviews[0].verified_head.as_deref(),
19876            Some(head.as_str())
19877        );
19878        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19879        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19880        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19881        assert!(runner.state.gate_ran);
19882        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19883        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19884        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19885        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19886        assert_eq!(
19887            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19888            "retained change"
19889        );
19890    }
19891
19892    #[cfg(unix)]
19893    #[tokio::test]
19894    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19895        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19896        let queue = crate::queue::Queue::open();
19897        let mut owner = queue.get(&task).unwrap();
19898        owner.release_operator("test-resume", None);
19899        queue.put(&mut owner).unwrap();
19900        let generation = owner.resumption.as_ref().unwrap().generation;
19901        runner.state.task_instruction = Some(owner.instruction.clone());
19902        runner.state.driver_exited = true;
19903        runner.state.save().unwrap();
19904        let home = crate::run::home();
19905        let _claim = queue.claim(&task).unwrap();
19906        owner.resumption.as_mut().unwrap().at =
19907            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19908        queue.put(&mut owner).unwrap();
19909        assert!(
19910            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19911                .await
19912                .is_err(),
19913            "an approval from before the stop grants nothing"
19914        );
19915        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19916        queue.put(&mut owner).unwrap();
19917        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19918            .await
19919            .unwrap();
19920        assert!(
19921            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19922                .await
19923                .is_err()
19924        );
19925        runner.state = RunState::load(&runner.state.id).unwrap();
19926        assert_eq!(
19927            runner.state.base_sync_recovery.authorizations[0].generation,
19928            Some(generation)
19929        );
19930        runner.sync_to_base().await.unwrap();
19931        let repo = runner.state.repo.clone();
19932        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19933        git::git(&repo, &["checkout", "main"]).await.unwrap();
19934        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19935        git::git(&repo, &["add", "."]).await.unwrap();
19936        git::git(&repo, &["commit", "-m", "move base again"])
19937            .await
19938            .unwrap();
19939        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19940        git::git(&repo, &["checkout", "fix/retained"])
19941            .await
19942            .unwrap();
19943        runner.sync_to_base().await.unwrap();
19944        assert!(!runner.state.base_sync_blocked());
19945        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19946        assert_eq!(runner.state.base_episode_used(), 2);
19947        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19948        assert_ne!(fresh, head);
19949        assert!(!runner.state.base_recovery_pending());
19950        // Even replaying the generation with a later timestamp grants nothing.
19951        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19952        queue.put(&mut owner).unwrap();
19953        assert!(
19954            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19955                .await
19956                .is_err()
19957        );
19958        runner.state = RunState::load(&runner.state.id).unwrap();
19959        runner.sync_to_base().await.unwrap();
19960        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19961        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19962        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19963    }
19964
19965    #[cfg(unix)]
19966    #[tokio::test]
19967    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19968        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19969        runner.state.base_sync = None;
19970        runner.state.status = RunStatus::Blocked;
19971        let mut second = runner.state.candidates[0].clone();
19972        second.label = 'B';
19973        runner.state.candidates.push(second);
19974        assert!(runner.state.votes.is_empty());
19975        assert!(runner.state.deliberation.is_empty());
19976        runner.deliberate().await.unwrap();
19977        runner.vote().await.unwrap();
19978        assert_eq!(runner.state.status, RunStatus::Blocked);
19979        assert!(runner.state.votes.is_empty());
19980        assert!(runner.state.deliberation.is_empty());
19981    }
19982
19983    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19984    /// reads nothing else off it.
19985    fn runner_at(status: RunStatus) -> Runner {
19986        let mut state = RunState::new(
19987            PathBuf::from("/nonexistent/repo"),
19988            "main".to_owned(),
19989            "deadbeef".to_owned(),
19990            "task".to_owned(),
19991            Config::default(),
19992        );
19993        // These fixtures test execution flow, independent of host disk capacity.
19994        state.config.disk.min_free_bytes = 0;
19995        // These fixtures share one home and save concurrently. Short clock
19996        // IDs can collide, making an ownership test read another test's run.
19997        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19998        state.id = format!(
19999            "20000101-000000-{:04x}",
20000            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20001        );
20002        state.status = status;
20003        Runner {
20004            state,
20005            roles: ResolvedRoles {
20006                implementers: Vec::new(),
20007                judges: Vec::new(),
20008                reviewers: Vec::new(),
20009                fixer: None,
20010                conductor: conductor(),
20011                implementer_roster: Vec::new(),
20012                judge_roster: Vec::new(),
20013                reviewer_roster: Vec::new(),
20014            },
20015            sem: Arc::new(Semaphore::new(1)),
20016            pause: Pause::new(),
20017            interrupt: Pause::new(),
20018        }
20019    }
20020
20021    #[tokio::test]
20022    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20023        crate::run::pin_test_home();
20024        let home = crate::run::home();
20025        let mut runner = runner_at(RunStatus::Ready);
20026        runner.state.driver_exited = true;
20027        runner.state.save().unwrap();
20028        let id = runner.state.id.clone();
20029        let path = runner.state.dir().join("run.json");
20030        let ids = ["R1-1-1".into()];
20031        let lease = crate::driver::maintenance(&home, &id).unwrap();
20032        for (guard, expected) in [
20033            (Some(lease), "currently being worked on"),
20034            (None, "ownership is being updated"),
20035        ] {
20036            let owner = if guard.is_none() {
20037                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20038            } else {
20039                None
20040            };
20041            let before = std::fs::read(&path).unwrap();
20042            let err = runner
20043                .fix_selected(&ids, "ownership conflict", false)
20044                .await
20045                .unwrap_err();
20046            assert!(format!("{err:#}").contains(expected), "{err:#}");
20047            assert_eq!(std::fs::read(&path).unwrap(), before);
20048            assert!(!runner.state.dir().join("fix.lock").exists());
20049            drop(owner);
20050            drop(guard);
20051        }
20052        let mut disk = RunState::load(&id).unwrap();
20053        disk.driver_exited = false;
20054        disk.driver_pid = Some(std::process::id());
20055        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20056        disk.save().unwrap();
20057        assert_eq!(
20058            disk.liveness_under(&home, false),
20059            crate::run::Liveness::Live
20060        );
20061        let before = std::fs::read(&path).unwrap();
20062        let err = runner
20063            .fix_selected(&ids, "live driver", false)
20064            .await
20065            .unwrap_err();
20066        assert!(
20067            err.to_string().contains("currently being worked on"),
20068            "{err:#}"
20069        );
20070        assert_eq!(std::fs::read(&path).unwrap(), before);
20071        assert!(!runner.state.dir().join("fix.lock").exists());
20072        disk.driver_exited = true;
20073        disk.driver_pid = None;
20074        disk.driver_started_at = None;
20075        disk.status = RunStatus::Reviewing;
20076        disk.save().unwrap();
20077        let before = std::fs::read(&path).unwrap();
20078        let err = runner
20079            .fix_selected(&ids, "stale state", false)
20080            .await
20081            .unwrap_err();
20082        assert!(
20083            err.to_string().contains("run changed since it was loaded"),
20084            "{err:#}"
20085        );
20086        assert_eq!(std::fs::read(&path).unwrap(), before);
20087        assert!(!runner.state.dir().join("fix.lock").exists());
20088        assert!(runner.state.operator_fixes.is_empty());
20089    }
20090
20091    #[tokio::test]
20092    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20093        use std::future::Future;
20094        use std::task::Poll;
20095
20096        crate::run::pin_test_home();
20097        let home = crate::run::home();
20098        let repo = tempfile::tempdir().unwrap();
20099        let mut runner = runner_at(RunStatus::Ready);
20100        runner.state.repo = repo.path().to_path_buf();
20101        runner.state.driver_exited = true;
20102        runner.state.candidates.push(Candidate {
20103            index: 0,
20104            label: 'A',
20105            agent: "mock".into(),
20106            branch: "magi/test/A".into(),
20107            worktree: repo.path().join("wt"),
20108            summary: String::new(),
20109            stat: String::new(),
20110            files: 0,
20111            commits: 0,
20112            empty: false,
20113            failed: None,
20114            verified_noop: None,
20115            duration_ms: 0,
20116            folded: false,
20117        });
20118        runner.state.tally = Some(Tally {
20119            first_choice: BTreeMap::from([('A', 1)]),
20120            borda: BTreeMap::new(),
20121            winner: 'A',
20122            rankings: 1,
20123            unanimous_initial: true,
20124            deliberated: false,
20125            changed_votes: 0,
20126            unanimous_final: true,
20127            tie_break: None,
20128            judges: 1,
20129            present: 1,
20130            quorum: 1,
20131            met_quorum: true,
20132            uncontested: None,
20133        });
20134        runner.state.save().unwrap();
20135        let id = runner.state.id.clone();
20136        let dir = runner.state.dir();
20137        let before = std::fs::read(dir.join("run.json")).unwrap();
20138        let ids = ["R1-1-1".into()];
20139        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20140        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20141            Poll::Pending => Poll::Ready(()),
20142            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20143        })
20144        .await;
20145        assert!(FixClaim::acquire(&dir).is_err());
20146        assert!(crate::driver::maintenance(&home, &id).is_err());
20147        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20148        drop(fix);
20149        assert!(FixClaim::acquire(&dir).is_ok());
20150        assert!(crate::driver::maintenance(&home, &id).is_ok());
20151        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20152    }
20153
20154    #[tokio::test]
20155    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20156        crate::run::pin_test_home();
20157        let temp = tempfile::tempdir().unwrap();
20158        let root = temp.path().canonicalize().unwrap();
20159        let repo = root.join("repo");
20160        std::fs::create_dir(&repo).unwrap();
20161        init_repo(&repo);
20162        git::git(&repo, &["config", "core.autocrlf", "false"])
20163            .await
20164            .unwrap();
20165        let mut runner = runner_at(RunStatus::Blocked);
20166        runner.state.repo = repo.clone();
20167        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20168        runner.state.config.agents = vec![conductor()];
20169        runner.state.config.graph.selected_implementer = Some("conductor".into());
20170        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20171        let (shell, command, setup_output) = if cfg!(windows) {
20172            (
20173                vec!["cmd".into(), "/C".into()],
20174                "echo ready>seat-ready",
20175                "ready\r\n",
20176            )
20177        } else {
20178            (
20179                vec!["sh".into(), "-c".into()],
20180                "printf ready > seat-ready",
20181                "ready",
20182            )
20183        };
20184        runner.state.config.verify.shell = Some(shell);
20185        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20186            run: Some(command.into()),
20187            ..Default::default()
20188        }];
20189        runner.state.save().unwrap();
20190        let path = runner.state.worktree_root().join("judge-1");
20191        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20192            .await
20193            .unwrap();
20194        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20195        git::git(&path, &["add", "."]).await.unwrap();
20196        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20197        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20198            .await
20199            .unwrap();
20200        git::git(&path, &["checkout", "--detach", &head])
20201            .await
20202            .unwrap();
20203        let evidence = crate::fold_evidence::snapshot(
20204            &runner.state,
20205            &crate::run::home().canonicalize().unwrap(),
20206            &head,
20207            64 * 1024 * 1024,
20208        )
20209        .await
20210        .unwrap();
20211        let mut contents = BTreeMap::new();
20212        contents.insert(
20213            repo.join("logs/HEAD"),
20214            format!("{head} {head} fixture\n").into_bytes(),
20215        );
20216        let record = serde_json::json!({
20217            "version":1, "run":runner.state.id, "source":path, "head":head,
20218            "evidence":evidence, "admin":{}, "admin_contents":contents,
20219            "history":{head.clone():evidence}, "phase":"evicted"
20220        });
20221        std::fs::write(
20222            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20223            serde_json::to_vec(&record).unwrap(),
20224        )
20225        .unwrap();
20226        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20227        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20228            .await
20229            .unwrap();
20230        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20231        assert!(
20232            !git::git_raw(&repo, &["cat-file", "-e", &head])
20233                .await
20234                .unwrap()
20235                .ok()
20236        );
20237        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20238        let error = resumed.execute().await.unwrap_err();
20239        assert!(
20240            error
20241                .to_string()
20242                .contains("selected implementation is held"),
20243            "{error:#}"
20244        );
20245        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
20246        assert_eq!(
20247            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
20248            setup_output
20249        );
20250        assert_eq!(
20251            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
20252            "unrelated seat"
20253        );
20254        let error = resumed.execute().await.unwrap_err();
20255        assert!(
20256            error
20257                .to_string()
20258                .contains("selected implementation is held"),
20259            "{error:#}"
20260        );
20261        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
20262        git::git(&path, &["add", "."]).await.unwrap();
20263        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
20264        let next = git::git(
20265            &path,
20266            &[
20267                "commit-tree",
20268                &next_tree,
20269                "-p",
20270                &head,
20271                "-m",
20272                "next review checkpoint",
20273            ],
20274        )
20275        .await
20276        .unwrap();
20277        git::git(&path, &["checkout", "--detach", &next])
20278            .await
20279            .unwrap();
20280        resumed.state.reviews.push(
20281            serde_json::from_value(serde_json::json!({
20282                "round":1, "head":next, "reviews":[]
20283            }))
20284            .unwrap(),
20285        );
20286        resumed.state.save().unwrap();
20287        let error = resumed.execute().await.unwrap_err();
20288        assert!(
20289            error
20290                .to_string()
20291                .contains("selected implementation is held"),
20292            "{error:#}"
20293        );
20294        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
20295    }
20296
20297    #[tokio::test]
20298    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
20299        crate::run::pin_test_home();
20300        let mut runner = runner_at(RunStatus::Gating);
20301        runner.state.save().unwrap();
20302        let id = runner.state.id.clone();
20303        let passes = runner.state.passes.len();
20304        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20305        let mut claiming = Box::pin(runner.claim_driver(None));
20306        std::future::poll_fn(|cx| {
20307            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
20308            std::task::Poll::Ready(())
20309        })
20310        .await;
20311        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
20312        drop(owner);
20313        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
20314            .await
20315            .unwrap()
20316            .unwrap();
20317        assert_eq!(execution.runner.state.passes.len(), passes + 1);
20318        assert!(execution.runner.state.resource_block.is_none());
20319        assert_eq!(
20320            execution.runner.state.liveness(false),
20321            crate::run::Liveness::Live
20322        );
20323        drop(execution);
20324        assert!(RunState::load(&id).unwrap().driver_exited);
20325    }
20326
20327    #[tokio::test]
20328    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
20329        crate::run::pin_test_home();
20330        let mut runner = runner_at(RunStatus::Gating);
20331        runner.state.save().unwrap();
20332        // run.json can commit, but the subsequent lease metadata write fails.
20333        // Cleanup must run after releasing the short ownership lock.
20334        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
20335        assert!(runner.claim_driver(None).await.is_err());
20336        assert!(runner.state.driver_exited);
20337        assert_eq!(runner.state.driver_pid, None);
20338        let disk = RunState::load(&runner.state.id).unwrap();
20339        assert!(disk.driver_exited);
20340        assert_eq!(disk.driver_pid, None);
20341        assert_eq!(disk.status, RunStatus::Gating);
20342    }
20343
20344    #[tokio::test]
20345    async fn an_early_graph_error_releases_its_driver() {
20346        crate::run::pin_test_home();
20347        let mut runner = runner_at(RunStatus::Blocked);
20348        runner.state.config.graph.selected_implementer = Some("selected".into());
20349        runner.state.save().unwrap();
20350        assert!(runner.execute().await.is_err());
20351        let disk = RunState::load(&runner.state.id).unwrap();
20352        assert!(disk.driver_exited);
20353        assert_eq!(disk.driver_pid, None);
20354        assert_eq!(disk.status, RunStatus::Blocked);
20355    }
20356
20357    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
20358        crate::run::MergeRepair {
20359            question: "repair-question".into(),
20360            head: "old-head".into(),
20361            pr: "https://github.com/o/r/pull/42".into(),
20362            reviews: vec![review_round(false, 1, 1, 1, false, true)],
20363            gate: vec![outcome(Some(0), false)],
20364            gate_head: Some("old-head".into()),
20365            gate_fixes: Vec::new(),
20366            pre_gate: Vec::new(),
20367            phase,
20368            failure: None,
20369        }
20370    }
20371
20372    #[tokio::test]
20373    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
20374        crate::run::pin_test_home();
20375        let mut runner = runner_at(RunStatus::Landing);
20376        runner.state.merge_repairs.push(merge_repair_request(
20377            crate::run::MergeRepairPhase::Requested,
20378        ));
20379        runner.state.save().unwrap();
20380        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
20381        assert!(
20382            runner
20383                .execute()
20384                .await
20385                .unwrap_err()
20386                .to_string()
20387                .contains("already running")
20388        );
20389        assert_eq!(
20390            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20391            crate::run::MergeRepairPhase::Requested
20392        );
20393        drop(claim);
20394        let mut disk = runner.state.clone();
20395        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
20396        disk.save().unwrap();
20397        assert!(
20398            runner
20399                .execute()
20400                .await
20401                .unwrap_err()
20402                .to_string()
20403                .contains("decision changed")
20404        );
20405        assert_eq!(
20406            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20407            crate::run::MergeRepairPhase::Complete
20408        );
20409    }
20410
20411    #[test]
20412    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
20413        crate::run::pin_test_home();
20414        let mut runner = runner_at(RunStatus::Landing);
20415        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
20416        runner.state.reviews = request.reviews.clone();
20417        runner.state.gate = request.gate.clone();
20418        runner.state.gate_ran = true;
20419        runner.state.land_approval = Some(crate::run::LandApproval {
20420            question: "old".into(),
20421            head: "old-head".into(),
20422        });
20423        runner.state.merge_repairs.push(request);
20424        runner.begin_merge_repair_review(0).unwrap();
20425        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
20426        assert!(!runner.state.gate_status().ok());
20427        assert!(runner.state.land_approval.is_none());
20428        let disk = RunState::load(&runner.state.id).unwrap();
20429        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
20430        assert!(disk.merge_repairs[0].gate[0].ok());
20431        assert_eq!(
20432            disk.merge_repairs[0].phase,
20433            crate::run::MergeRepairPhase::Reviewing
20434        );
20435        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
20436        assert!(disk.reviews.is_empty());
20437    }
20438
20439    #[tokio::test]
20440    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
20441        crate::run::pin_test_home();
20442        for phase in [
20443            crate::run::MergeRepairPhase::Fixing,
20444            crate::run::MergeRepairPhase::Requested,
20445        ] {
20446            let mut runner = runner_at(RunStatus::Landing);
20447            runner.state.config.graph.land_rounds = 0;
20448            runner.state.merge_repairs.push(merge_repair_request(phase));
20449            runner.state.save().unwrap();
20450            assert!(!runner.repair_merge_review().await.unwrap());
20451            assert_eq!(runner.state.status, RunStatus::Blocked);
20452            assert_eq!(
20453                runner.state.merge_repairs[0].phase,
20454                crate::run::MergeRepairPhase::Failed
20455            );
20456            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
20457            assert!(
20458                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
20459                    "interrupted"
20460                } else {
20461                    "budget exhausted"
20462                })
20463            );
20464            assert!(runner.state.merge.is_none());
20465        }
20466    }
20467
20468    /// `park_here` folding in the reason `Pause::park_because` recorded -
20469    /// this is what lets an operator reading a run's events tell an
20470    /// interrupt-driven park from an ordinary shutdown park.
20471    #[test]
20472    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
20473        crate::run::pin_test_home();
20474        let mut runner = runner_at(RunStatus::Implementing);
20475        let interrupt = Pause::new();
20476        runner.watch_interrupt(interrupt.clone());
20477
20478        interrupt.park_because("task a1b2 asked to run first");
20479
20480        assert!(runner.park_here().expect("park_here"));
20481        assert!(runner.state.parked);
20482        let last = runner.state.events.last().expect("a park event");
20483        assert_eq!(last.node, "park");
20484        assert!(
20485            last.message.contains("task a1b2 asked to run first"),
20486            "expected the interrupt reason in {:?}",
20487            last.message
20488        );
20489    }
20490
20491    /// The cause is stored on the pass when it parks, and the first cause a
20492    /// shared pause was given is the one that stays.
20493    #[test]
20494    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
20495        crate::run::pin_test_home();
20496        let mut runner = runner_at(RunStatus::Implementing);
20497        runner.state.begin_pass();
20498        let shutdown = Pause::new();
20499        runner.on_pause(shutdown.clone());
20500        let upgrade = ParkCause::Upgrade {
20501            from: "0.121.0".to_owned(),
20502            to: Some("0.121.1".to_owned()),
20503        };
20504        shutdown.park_for(upgrade.clone());
20505        shutdown.park_for(ParkCause::Operator);
20506
20507        assert!(runner.park_here().expect("park_here"));
20508        assert_eq!(
20509            runner.state.passes[0].end,
20510            Some(crate::run::PassEnd::Parked { cause: upgrade })
20511        );
20512        let last = runner.state.events.last().expect("a park event");
20513        assert!(last.message.contains("0.121.0"), "{}", last.message);
20514    }
20515
20516    #[tokio::test]
20517    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
20518        crate::run::pin_test_home();
20519        let mut runner = runner_at(RunStatus::Reviewing);
20520        runner.state.save().unwrap();
20521        let mut execution = runner.claim_driver(None).await.expect("first execution");
20522        assert_eq!(execution.runner.state.passes.len(), 1);
20523        execution
20524            .driver
20525            .finish(&mut execution.runner.state)
20526            .await
20527            .unwrap();
20528    }
20529
20530    #[tokio::test]
20531    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
20532        crate::run::pin_test_home();
20533        let mut runner = runner_at(RunStatus::Reviewing);
20534        runner.state.config.agents = vec![conductor()];
20535        runner.state.config.graph.timeout_resource_wait = 0;
20536        runner.state.save().unwrap();
20537        let id = runner.state.id.clone();
20538        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20539        assert!(runner.claim_driver(None).await.is_err());
20540        drop(owner);
20541        drop(runner);
20542        let mut resumed = Runner::resume(&id).unwrap();
20543        assert_eq!(resumed.state.driver_claimed, Some(false));
20544        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
20545        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
20546        let mut execution = resumed
20547            .claim_driver(None)
20548            .await
20549            .expect("retry initial claim after reload");
20550        assert_eq!(execution.runner.state.driver_claimed, Some(true));
20551        assert_eq!(execution.runner.state.passes.len(), 1);
20552        execution
20553            .driver
20554            .finish(&mut execution.runner.state)
20555            .await
20556            .unwrap();
20557    }
20558
20559    #[tokio::test]
20560    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
20561        crate::run::pin_test_home();
20562        let mut runner = runner_at(RunStatus::Reviewing);
20563        runner.state.config.agents = vec![conductor()];
20564        runner.state.save().unwrap();
20565        let id = runner.state.id.clone();
20566        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20567        let mut resumed = Runner::resume(&id).unwrap();
20568        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20569        assert!(resumed.claim_driver(None).await.is_err());
20570        assert!(RunState::load(&id).unwrap().passes.is_empty());
20571        drop(lease);
20572        let mut execution = resumed.claim_driver(None).await.unwrap();
20573        execution
20574            .driver
20575            .finish(&mut execution.runner.state)
20576            .await
20577            .unwrap();
20578    }
20579
20580    #[tokio::test]
20581    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20582        crate::run::pin_test_home();
20583        let mut runner = runner_at(RunStatus::Reviewing);
20584        let state = &mut runner.state;
20585        state.config.agents = vec![conductor()];
20586        state.driver_claimed = None;
20587        state.driver_pid = Some(std::process::id());
20588        state.driver_started_at = None;
20589        state.begin_pass();
20590        state.save().unwrap();
20591        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20592        std::fs::write(
20593            state.dir().join("driver.json"),
20594            serde_json::to_vec(&serde_json::json!({
20595                "pid": state.driver_pid, "started_at": null,
20596                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20597            }))
20598            .unwrap(),
20599        )
20600        .unwrap();
20601        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20602        drop(lease);
20603        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20604        let mut resumed = Runner::resume(&state.id).unwrap();
20605        assert!(!resumed.state.driver_exited);
20606        let mut execution = resumed
20607            .claim_driver(None)
20608            .await
20609            .expect("lease proves previous execution ended");
20610        assert_eq!(execution.runner.state.passes.len(), 2);
20611        execution
20612            .driver
20613            .finish(&mut execution.runner.state)
20614            .await
20615            .unwrap();
20616    }
20617
20618    #[tokio::test]
20619    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20620        crate::run::pin_test_home();
20621        let mut runner = runner_at(RunStatus::Reviewing);
20622        let mut json = serde_json::to_value(&runner.state).unwrap();
20623        json.as_object_mut().unwrap().remove("driver_claimed");
20624        runner.state = serde_json::from_value(json).unwrap();
20625        assert_eq!(runner.state.driver_claimed, None);
20626        runner.state.save().unwrap();
20627        let mut execution = runner
20628            .claim_driver(None)
20629            .await
20630            .expect("the execution lease, not a missing marker, excludes a second driver");
20631        assert_eq!(execution.runner.state.passes.len(), 1);
20632        execution
20633            .driver
20634            .finish(&mut execution.runner.state)
20635            .await
20636            .unwrap();
20637    }
20638
20639    #[tokio::test]
20640    async fn driver_admission_refuses_a_proven_live_driver() {
20641        crate::run::pin_test_home();
20642        let mut runner = runner_at(RunStatus::Reviewing);
20643        let pid = std::process::id();
20644        runner.state.driver_pid = Some(pid);
20645        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20646        assert!(runner.state.driver_started_at.is_some());
20647        runner.state.save().unwrap();
20648        let error = runner
20649            .claim_driver(None)
20650            .await
20651            .err()
20652            .expect("a live driver must refuse");
20653        assert!(error.to_string().contains("live driver"), "{error:#}");
20654        let saved = RunState::load(&runner.state.id).unwrap();
20655        assert_eq!(saved.driver_pid, Some(pid));
20656        assert_eq!(saved.status, RunStatus::Reviewing);
20657        assert!(saved.passes.is_empty());
20658    }
20659
20660    #[test]
20661    fn parking_resource_halt_persists_the_pass_once() {
20662        crate::run::pin_test_home();
20663        let mut runner = runner_at(RunStatus::Reviewing);
20664        runner.state.begin_pass();
20665        runner.state.resource_block = Some(crate::run::ResourceBlock {
20666            node: "fix".into(),
20667            kind: "shared build cache".into(),
20668            detail: "cancelled".into(),
20669            at: Timestamp::now(),
20670            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20671        });
20672        let cause = ParkCause::Upgrade {
20673            from: "old".into(),
20674            to: Some("new".into()),
20675        };
20676        runner.pause.park_for(cause.clone());
20677        // Both direct fixer exits and graph resource boundaries must complete
20678        // parking, rather than returning a stale Reviewing record.
20679        runner.stop_for_resource().unwrap();
20680        assert!(runner.resource_halt().unwrap());
20681        assert!(runner.park_here().unwrap());
20682        let saved = RunState::load(&runner.state.id).unwrap();
20683        assert!(saved.parked);
20684        assert_eq!(saved.status, RunStatus::Reviewing);
20685        assert!(saved.passes[0].ended_at.is_some());
20686        assert_eq!(
20687            saved.passes[0].end,
20688            Some(crate::run::PassEnd::Parked {
20689                cause: cause.clone()
20690            })
20691        );
20692        assert_eq!(
20693            saved.resource_block.unwrap().cause,
20694            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20695        );
20696        assert_eq!(
20697            saved
20698                .events
20699                .iter()
20700                .filter(|event| event.node == "park")
20701                .count(),
20702            1
20703        );
20704    }
20705
20706    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20707    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20708    /// cleared) must not make a *different* run - one only watching its own,
20709    /// unshared interrupt `Pause` - see itself as parked. If a future change
20710    /// ever collapsed these back into one handle, the interrupt scheduler
20711    /// would park every run for the rest of the daemon's life, not just the
20712    /// one it meant to interrupt.
20713    #[test]
20714    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20715        crate::run::pin_test_home();
20716        let mut runner = runner_at(RunStatus::Implementing);
20717        let shutdown = Pause::new();
20718        runner.on_pause(shutdown.clone());
20719        let interrupt = Pause::new();
20720        runner.watch_interrupt(interrupt.clone());
20721
20722        // Nobody has asked for anything yet.
20723        assert!(!runner.park_here().expect("park_here"));
20724        assert!(!runner.state.parked);
20725
20726        // Only the interrupt handle fires; the shutdown handle stays clear.
20727        interrupt.park_because("test");
20728        assert!(!shutdown.parked());
20729        assert!(runner.park_here().expect("park_here"));
20730    }
20731
20732    /// The property every prior attempt at this feature failed to pin down:
20733    /// asking a run to park while one of its nodes has a real, in-flight
20734    /// async operation running (an agent call, in production) must not cut
20735    /// that operation short. `park_here` is only ever consulted *between*
20736    /// `execute`'s node calls - see its own doc - so nothing inside a node
20737    /// can observe a park request until the node itself returns. This proves
20738    /// that structurally, with real `tokio` concurrency and a channel
20739    /// handshake (never a sleep, which would only prove "usually", not
20740    /// "cannot"): the "node" below reports that it has genuinely started,
20741    /// and only then is the park requested; the node still has to be told to
20742    /// finish before `park_here` is ever called, exactly mirroring every
20743    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20744    /// in `execute`.
20745    #[tokio::test]
20746    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20747        crate::run::pin_test_home();
20748        let mut runner = runner_at(RunStatus::Implementing);
20749        let interrupt = Pause::new();
20750        runner.watch_interrupt(interrupt.clone());
20751
20752        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20753        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20754
20755        // Stands in for one node's in-flight agent call: it proves it has
20756        // genuinely started, then blocks - exactly as a spawned CLI process
20757        // does - until told to finish.
20758        let node = async move {
20759            started_tx.send(()).expect("send started");
20760            finish_rx.await.expect("recv finish");
20761            "node finished"
20762        };
20763
20764        let interrupter = async move {
20765            started_rx.await.expect("recv started");
20766            // The call is now genuinely in flight. Ask it to park.
20767            interrupt.park_because("higher-priority task waiting");
20768            // Nothing the node does can observe this yet - there is no
20769            // check inside it, by construction - so let the executor run
20770            // anything pending and then let the node finish on its own.
20771            tokio::task::yield_now().await;
20772            finish_tx.send(()).expect("send finish");
20773        };
20774
20775        let (node_result, ()) = tokio::join!(node, interrupter);
20776        assert_eq!(
20777            node_result, "node finished",
20778            "the in-flight call ran to completion"
20779        );
20780
20781        // Only now, at the boundary the real `execute` would check right
20782        // after this node, does the park take effect.
20783        assert!(runner.park_here().expect("park_here"));
20784        assert!(runner.state.parked);
20785    }
20786
20787    /// A run parked mid-competition carries every field it had accumulated
20788    /// through the exact same disk round-trip an ordinary resume uses -
20789    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20790    /// Nothing about parking for an interrupt is a special case of that path;
20791    /// this is what proves it rather than assuming it.
20792    #[test]
20793    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20794        crate::run::pin_test_home();
20795        let mut runner = runner_at(RunStatus::Judging);
20796        // `Runner::resume` re-resolves roles from the saved config, which
20797        // refuses an empty roster - give it the same minimal one `conductor`
20798        // itself uses.
20799        runner.state.config.agents = vec![conductor()];
20800        runner.state.candidates = vec![Candidate {
20801            index: 0,
20802            label: 'A',
20803            agent: "alpha".to_owned(),
20804            branch: "magi/x/A".to_owned(),
20805            worktree: PathBuf::from("/nonexistent/worktree"),
20806            summary: "did the thing".to_owned(),
20807            stat: "1 file changed".to_owned(),
20808            files: 1,
20809            commits: 1,
20810            empty: false,
20811            failed: None,
20812            verified_noop: None,
20813            duration_ms: 1234,
20814            folded: false,
20815        }];
20816        let run_id = runner.state.id.clone();
20817
20818        let interrupt = Pause::new();
20819        runner.watch_interrupt(interrupt.clone());
20820        interrupt.park_because("task c3d4 asked to run first");
20821        assert!(runner.park_here().expect("park_here"));
20822
20823        let resumed = Runner::resume(&run_id).expect("resume");
20824        assert_eq!(resumed.state.candidates.len(), 1);
20825        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20826        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20827        assert_eq!(resumed.state.status, runner.state.status);
20828        assert!(
20829            resumed.state.parked,
20830            "still parked until `execute` actually walks the graph again"
20831        );
20832        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20833    }
20834
20835    /// A fresh open question on `run`, stored and handed back for assertions.
20836    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20837        let mut q = ask::Question::new(
20838            run.to_owned(),
20839            "implement".to_owned(),
20840            "impl-A".to_owned(),
20841            "Which storage backend should the cache use?".to_owned(),
20842            String::new(),
20843            vec!["SQLite".to_owned(), "Redis".to_owned()],
20844        );
20845        store.put(&mut q).unwrap();
20846        q
20847    }
20848
20849    #[test]
20850    fn a_failed_runs_open_question_is_abandoned() {
20851        ask_test_home();
20852        let store = ask::Questions::open();
20853        let mut runner = runner_at(RunStatus::Failed);
20854        let run = runner.state.id.clone();
20855        let q = ask_open_question(&store, &run);
20856
20857        runner.settle_questions();
20858
20859        let back = store.get(&q.id).unwrap();
20860        assert!(
20861            !back.status.open(),
20862            "the seat that asked died with the run; nobody is left to read an answer"
20863        );
20864        assert!(
20865            back.detail.contains(&run) && back.detail.contains("failed"),
20866            "the reason names what the run became, not just that it is gone: {}",
20867            back.detail
20868        );
20869    }
20870
20871    #[test]
20872    fn a_merged_runs_open_question_is_abandoned_too() {
20873        ask_test_home();
20874        let store = ask::Questions::open();
20875        // A run that finishes cleanly still leaves nobody to read an answer -
20876        // this is not only a failure-path cleanup.
20877        for status in [RunStatus::Merged, RunStatus::Ready] {
20878            let mut runner = runner_at(status);
20879            let run = runner.state.id.clone();
20880            let q = ask_open_question(&store, &run);
20881
20882            runner.settle_questions();
20883
20884            let back = store.get(&q.id).unwrap();
20885            assert!(
20886                !back.status.open(),
20887                "{status:?} run's question must not outlive the run"
20888            );
20889        }
20890    }
20891
20892    #[test]
20893    fn a_still_resumable_runs_open_question_is_left_alone() {
20894        ask_test_home();
20895        let store = ask::Questions::open();
20896        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20897        // review round and the seat sessions are all still on disk — so a
20898        // question asked mid-round may yet get a real answer from a real
20899        // resume. Sweeping it here would be exactly the failure mode this
20900        // whole feature exists to avoid on the other side.
20901        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20902            let mut runner = runner_at(status);
20903            let run = runner.state.id.clone();
20904            let q = ask_open_question(&store, &run);
20905
20906            runner.settle_questions();
20907
20908            let back = store.get(&q.id).unwrap();
20909            assert!(
20910                back.status.open(),
20911                "{status:?} is still alive; the question must still be waiting"
20912            );
20913        }
20914    }
20915
20916    #[test]
20917    fn settle_questions_never_touches_an_already_answered_question() {
20918        ask_test_home();
20919        let store = ask::Questions::open();
20920        let mut runner = runner_at(RunStatus::Failed);
20921        let run = runner.state.id.clone();
20922        let mut q = ask_open_question(&store, &run);
20923        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20924            .unwrap();
20925        store.put(&mut q).unwrap();
20926
20927        // Called twice, the way a crash-recovered daemon reclaim and the
20928        // graph's own cleanup both can for the same run — `abandon_for_run`
20929        // only ever touches what is still open, so this must be inert both
20930        // times, not merely the second.
20931        runner.settle_questions();
20932        runner.settle_questions();
20933
20934        let back = store.get(&q.id).unwrap();
20935        assert_eq!(
20936            back.status,
20937            ask::QuestionStatus::Answered,
20938            "a real answer is a decision on record, never overwritten by a sweep"
20939        );
20940    }
20941
20942    #[tokio::test]
20943    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20944        let tmp = tempfile::tempdir().unwrap();
20945        let home = tmp.path().join("home");
20946        let repo = tmp.path().join("repo");
20947        std::fs::create_dir(&home).unwrap();
20948        std::fs::create_dir(&repo).unwrap();
20949        init_repo(&repo);
20950
20951        let mut config = Config::default();
20952        config.graph.worktree_root = Some(tmp.path().join("wt"));
20953        config.verify.build_cache = crate::config::BuildCache::Isolated;
20954        let mut state = RunState::new(
20955            repo.clone(),
20956            "main".into(),
20957            "base".into(),
20958            "fold fixture".into(),
20959            config,
20960        );
20961        let root = state.worktree_root();
20962        let mut outputs = Vec::new();
20963        for name in ["idle", "busy"] {
20964            let checkout = root.join(name);
20965            git::worktree_add_detached(&repo, &checkout, "main")
20966                .await
20967                .unwrap();
20968            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20969            let output = target.join("generated");
20970            std::fs::write(&output, name).unwrap();
20971            outputs.push((target, output));
20972        }
20973        let unknown = crate::build_target::root(&home)
20974            .join("00000000-0000-0000-0000-000000000000")
20975            .join("target");
20976        std::fs::create_dir_all(&unknown).unwrap();
20977        let unowned = unknown.join("generated");
20978        std::fs::write(&unowned, "keep").unwrap();
20979        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20980        let crate::cache::AcquireOutcome::Acquired(_lease) =
20981            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20982        else {
20983            panic!("fixture target must be free");
20984        };
20985
20986        fold_run(&mut state, true, &home).await.unwrap();
20987        assert!(!root.exists());
20988        assert!(!outputs[0].1.exists());
20989        assert!(outputs[1].1.is_file());
20990        assert!(unowned.is_file());
20991    }
20992
20993    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20994    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20995    /// without merging, whose winner is still the operator's answer to read.
20996    /// Nothing previously called `fold_run` itself with a real `tally`, so
20997    /// this is the first test to pin down the one distinction the whole
20998    /// automatic-fold feature depends on: the winner's worktree and branch
20999    /// must survive, everything else sharing the run's worktree bay - a
21000    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21001    /// second sweep treats every non-winner directory under the bay alike -
21002    /// must not.
21003    #[tokio::test]
21004    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21005        crate::run::pin_test_home();
21006        let tmp = tempfile::tempdir().expect("tempdir");
21007        let repo = tmp.path().join("repo");
21008        std::fs::create_dir_all(&repo).unwrap();
21009        init_repo(&repo);
21010
21011        let mut config = Config::default();
21012        config.graph.worktree_root = Some(tmp.path().join("wt"));
21013
21014        let mut state = RunState::new(
21015            repo.clone(),
21016            "main".to_owned(),
21017            "deadbeef".to_owned(),
21018            "task".to_owned(),
21019            config,
21020        );
21021        let root = state.worktree_root();
21022        let wt_a = root.join("cand-A");
21023        let wt_b = root.join("cand-B");
21024        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21025            .await
21026            .expect("worktree A");
21027        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21028            .await
21029            .expect("worktree B");
21030
21031        state.candidates = vec![
21032            Candidate {
21033                index: 0,
21034                label: 'A',
21035                agent: "alpha".to_owned(),
21036                branch: "magi/x/A".to_owned(),
21037                worktree: wt_a.clone(),
21038                summary: String::new(),
21039                stat: String::new(),
21040                files: 0,
21041                commits: 0,
21042                empty: false,
21043                failed: None,
21044                verified_noop: None,
21045                duration_ms: 0,
21046                folded: false,
21047            },
21048            Candidate {
21049                index: 1,
21050                label: 'B',
21051                agent: "beta".to_owned(),
21052                branch: "magi/x/B".to_owned(),
21053                worktree: wt_b.clone(),
21054                summary: String::new(),
21055                stat: String::new(),
21056                files: 0,
21057                commits: 0,
21058                empty: false,
21059                failed: None,
21060                verified_noop: None,
21061                duration_ms: 0,
21062                folded: false,
21063            },
21064        ];
21065        state.tally = Some(Tally {
21066            first_choice: BTreeMap::from([('A', 1)]),
21067            borda: BTreeMap::new(),
21068            winner: 'A',
21069            rankings: 1,
21070            unanimous_initial: true,
21071            deliberated: false,
21072            changed_votes: 0,
21073            unanimous_final: true,
21074            tie_break: None,
21075            judges: 1,
21076            present: 1,
21077            quorum: 1,
21078            met_quorum: true,
21079            uncontested: None,
21080        });
21081        state.status = RunStatus::Ready;
21082
21083        fold_run(&mut state, false, &crate::run::home())
21084            .await
21085            .expect("fold_run");
21086
21087        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21088        assert!(
21089            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21090            "the unmerged winner's branch survives"
21091        );
21092        assert!(
21093            !state.candidates[0].folded,
21094            "the winner is not marked folded"
21095        );
21096
21097        assert!(!wt_b.exists(), "the loser's worktree is removed");
21098        assert!(
21099            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21100            "the loser's branch is removed"
21101        );
21102        assert!(state.candidates[1].folded, "the loser is marked folded");
21103    }
21104
21105    #[tokio::test]
21106    #[cfg(unix)]
21107    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21108        use std::os::fd::AsRawFd as _;
21109        use std::time::Duration;
21110
21111        let tmp = tempfile::tempdir().unwrap();
21112        let repo = tmp.path().join("repo");
21113        std::fs::create_dir_all(&repo).unwrap();
21114        init_repo(&repo);
21115        let common = repo.join(".git");
21116        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21117        let home = tmp.path().join("home");
21118        let mut config = Config::default();
21119        config.coordination = crate::config::test_coordination();
21120        config.graph.worktree_root = Some(tmp.path().join("wt"));
21121        config.graph.timeout_resource_wait = 1;
21122        let mut state = RunState::new(
21123            repo.clone(),
21124            "main".into(),
21125            "deadbeef".into(),
21126            "task".into(),
21127            config,
21128        );
21129        let root = state.worktree_root();
21130        let candidate = root.join("cand-A");
21131        let reviewer = root.join("review-1");
21132        let branch = state.branch_for('A');
21133        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21134            .await
21135            .unwrap();
21136        git::worktree_add_detached(&repo, &reviewer, "main")
21137            .await
21138            .unwrap();
21139        git::acquire_worktree_config(&repo).await.unwrap();
21140        state.enabled_worktree_config = true;
21141        state.status = RunStatus::Ready;
21142        state.candidates.push(Candidate {
21143            index: 0,
21144            label: 'A',
21145            agent: "implement".into(),
21146            branch: branch.clone(),
21147            worktree: candidate.clone(),
21148            summary: String::new(),
21149            stat: String::new(),
21150            files: 0,
21151            commits: 0,
21152            empty: false,
21153            failed: None,
21154            verified_noop: None,
21155            duration_ms: 0,
21156            folded: false,
21157        });
21158        state.save_under(&home).unwrap();
21159        let config_before = std::fs::read(common.join("config")).unwrap();
21160        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21161            .await
21162            .unwrap();
21163        // A separate OS handle bypasses the launcher's local gate, exactly as
21164        // an external updater does, and must still prevent all folding work.
21165        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21166        assert_eq!(
21167            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21168            0
21169        );
21170        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21171        assert!(
21172            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21173                .await
21174                .is_err()
21175        );
21176        assert!(candidate.exists());
21177        assert!(reviewer.exists());
21178        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21179        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21180        assert_eq!(
21181            git::git(&repo, &["worktree", "list", "--porcelain"])
21182                .await
21183                .unwrap(),
21184            worktrees_before
21185        );
21186        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21187            .await
21188            .unwrap()
21189            .unwrap_err();
21190        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
21191        drop(fold);
21192        assert!(candidate.exists() && reviewer.exists());
21193        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
21194        assert_eq!(
21195            state.resource_block.as_ref().unwrap().kind,
21196            "repository coordination"
21197        );
21198        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21199        drop(external);
21200        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21201        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
21202            .await
21203            .unwrap()
21204            .unwrap();
21205        drop(fold);
21206        assert!(removed.contains(&branch));
21207        assert!(!root.exists());
21208        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
21209        assert!(state.candidates[0].folded);
21210        assert!(!state.enabled_worktree_config);
21211        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
21212        let enabled = git::git_raw(
21213            &repo,
21214            &["config", "--local", "--get", "extensions.worktreeConfig"],
21215        )
21216        .await
21217        .unwrap();
21218        assert!(!enabled.ok(), "the last config reference was released");
21219    }
21220
21221    /// A branch handed to a later run is that run's (and its pull request's):
21222    /// folding the run that released it must not delete it.
21223    #[tokio::test]
21224    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
21225        let tmp = tempfile::tempdir().expect("tempdir");
21226        let repo = tmp.path().join("repo");
21227        std::fs::create_dir_all(&repo).unwrap();
21228        init_repo(&repo);
21229        let home = tmp.path().join("home");
21230
21231        let mut config = Config::default();
21232        config.graph.worktree_root = Some(tmp.path().join("wt"));
21233        let mut state = RunState::new(
21234            repo.clone(),
21235            "main".to_owned(),
21236            "deadbeef".to_owned(),
21237            "task".to_owned(),
21238            config,
21239        );
21240        // The worktree is already gone (released); the branch survives.
21241        git::git(&repo, &["branch", "magi/x/A", "main"])
21242            .await
21243            .expect("branch");
21244        state.candidates = vec![Candidate {
21245            index: 0,
21246            label: 'A',
21247            agent: "alpha".to_owned(),
21248            branch: "magi/x/A".to_owned(),
21249            worktree: state.worktree_root().join("cand-A"),
21250            summary: String::new(),
21251            stat: String::new(),
21252            files: 0,
21253            commits: 0,
21254            empty: false,
21255            failed: None,
21256            verified_noop: None,
21257            duration_ms: 0,
21258            folded: true,
21259        }];
21260        state.released_to = Some("20260901-000000-new1".to_owned());
21261        state.released_branches = vec!["magi/x/A".to_owned()];
21262
21263        fold_run(&mut state, true, &home).await.expect("fold_run");
21264        state.status = RunStatus::Merged;
21265        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
21266        state.merge = Some(crate::run::MergeOutcome {
21267            mode: MergeMode::Pr,
21268            ok: true,
21269            detail: "confirmed merged".into(),
21270            empty: false,
21271        });
21272        fold_run(&mut state, true, &home)
21273            .await
21274            .expect("merged fold");
21275
21276        assert!(
21277            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21278            "the handed-over branch survives a fold"
21279        );
21280    }
21281
21282    /// A winner with nothing ahead of the base is caught before `gh` is ever
21283    /// asked for a pull request, and the message carries what the task's
21284    /// references resolved to.
21285    #[tokio::test]
21286    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
21287        let tmp = tempfile::tempdir().expect("tempdir");
21288        let repo = tmp.path().join("repo");
21289        std::fs::create_dir_all(&repo).unwrap();
21290        init_repo(&repo);
21291        let run = |args: &[&str]| {
21292            let out = std::process::Command::new("git")
21293                .quiet()
21294                .args(args)
21295                .current_dir(&repo)
21296                .output()
21297                .expect("spawn git");
21298            assert!(out.status.success(), "git {args:?}");
21299        };
21300        run(&["branch", "magi/x/A"]);
21301        run(&["checkout", "-q", "-b", "magi/x/B"]);
21302        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
21303        run(&["add", "-A"]);
21304        run(&["commit", "-q", "-m", "work"]);
21305        run(&["checkout", "-q", "main"]);
21306
21307        // A pull request is compared against the remote's base, so the
21308        // fixture needs one. Before it exists nothing can be read, and the
21309        // answer must be "not empty".
21310        let probe = RunState::new(
21311            repo.clone(),
21312            "main".to_owned(),
21313            "deadbeef".to_owned(),
21314            "task".to_owned(),
21315            Config::default(),
21316        );
21317        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
21318        let bare = tmp.path().join("origin.git");
21319        let out = std::process::Command::new("git")
21320            .quiet()
21321            .args(["init", "-q", "--bare"])
21322            .arg(&bare)
21323            .output()
21324            .expect("spawn git");
21325        assert!(out.status.success(), "git init --bare");
21326        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
21327        run(&["push", "-q", "origin", "main"]);
21328
21329        let mut state = RunState::new(
21330            repo.clone(),
21331            "main".to_owned(),
21332            "deadbeef".to_owned(),
21333            "task".to_owned(),
21334            Config::default(),
21335        );
21336        state.seeds = vec![refs::Seed {
21337            token: "magi/27b2/A".to_owned(),
21338            kind: refs::SeedKind::Unresolved,
21339            sha: String::new(),
21340            branch: true,
21341            detail: "no branch or commit named magi/27b2/A".to_owned(),
21342        }];
21343
21344        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
21345        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
21346        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
21347        let detail = empty_candidate_detail(&state, "main");
21348        assert!(detail.starts_with("empty candidate"), "{detail}");
21349        assert!(!detail.contains("magi/27b2/A"), "{detail}");
21350        assert!(detail.contains("--start-from"), "{detail}");
21351    }
21352
21353    /// `status == Ready` used to be read as "this is the harmless
21354    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
21355    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
21356    /// run's PR was closed without merging — and reentering `merge` with
21357    /// `mode` still `Pr` does not know the difference, so it pushed and
21358    /// opened a second pull request. `mode == Local` reproduces the same
21359    /// blind spot without a network call: reentry must not attempt another
21360    /// git merge once this node has already recorded an outcome.
21361    #[tokio::test]
21362    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
21363        let tmp = tempfile::tempdir().expect("tempdir");
21364        let repo = tmp.path().join("repo");
21365        std::fs::create_dir_all(&repo).unwrap();
21366        init_repo(&repo);
21367
21368        let mut config = Config::default();
21369        config.merge.mode = MergeMode::Local;
21370
21371        let mut state = RunState::new(
21372            repo.clone(),
21373            "main".to_owned(),
21374            "deadbeef".to_owned(),
21375            "task".to_owned(),
21376            config,
21377        );
21378        state.candidates = vec![Candidate {
21379            index: 0,
21380            label: 'A',
21381            agent: "alpha".to_owned(),
21382            branch: "does-not-exist".to_owned(),
21383            worktree: repo.clone(),
21384            summary: String::new(),
21385            stat: String::new(),
21386            files: 0,
21387            commits: 0,
21388            empty: false,
21389            failed: None,
21390            verified_noop: None,
21391            duration_ms: 0,
21392            folded: false,
21393        }];
21394        state.tally = Some(Tally {
21395            first_choice: BTreeMap::from([('A', 1)]),
21396            borda: BTreeMap::new(),
21397            winner: 'A',
21398            rankings: 1,
21399            unanimous_initial: true,
21400            deliberated: false,
21401            changed_votes: 0,
21402            unanimous_final: true,
21403            tie_break: None,
21404            judges: 0,
21405            present: 0,
21406            quorum: 0,
21407            met_quorum: true,
21408            uncontested: Some("only candidate A produced a change".to_owned()),
21409        });
21410        state.reviews = vec![ReviewRound {
21411            round: 1,
21412            head: "deadbeef".to_owned(),
21413            verified_head: None,
21414            verified_at: None,
21415            reviews: Vec::new(),
21416            e2e: Vec::new(),
21417            fix: None,
21418            blocking: 0,
21419            answered: 0,
21420            expected: 0,
21421            clean: true,
21422            verify_retried: false,
21423            e2e_deferred: false,
21424            e2e_defer_reason: None,
21425            progressed: false,
21426            vote_split: false,
21427            reconsideration: Vec::new(),
21428            verdict: None,
21429        }];
21430        state.gate = vec![CommandOutcome {
21431            command: "test".to_owned(),
21432            code: Some(0),
21433            output_tail: String::new(),
21434            duration_ms: 0,
21435            resource_blocked: false,
21436            ..Default::default()
21437        }];
21438        state.gate_ran = true;
21439        // Reached its conclusion already — e.g. `land` closing the PR without
21440        // merging it, which (like the honest `MergeMode::None` path) leaves
21441        // `status` at `Ready`. The recorded outcome is what actually marks
21442        // this node done.
21443        state.status = RunStatus::Ready;
21444        state.merge = Some(MergeOutcome {
21445            mode: MergeMode::Local,
21446            ok: false,
21447            detail: "already concluded".to_owned(),
21448            empty: false,
21449        });
21450
21451        let mut runner = Runner {
21452            state,
21453            roles: ResolvedRoles {
21454                implementers: Vec::new(),
21455                judges: Vec::new(),
21456                reviewers: Vec::new(),
21457                fixer: None,
21458                conductor: conductor(),
21459                implementer_roster: Vec::new(),
21460                judge_roster: Vec::new(),
21461                reviewer_roster: Vec::new(),
21462            },
21463            sem: Arc::new(Semaphore::new(1)),
21464            pause: Pause::new(),
21465            interrupt: Pause::new(),
21466        };
21467
21468        runner.merge().await.expect("merge");
21469
21470        assert_eq!(
21471            runner.state.status,
21472            RunStatus::Ready,
21473            "a concluded run's status must not change on reentry"
21474        );
21475        assert_eq!(
21476            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
21477            Some("already concluded"),
21478            "merge must not run again once the node already recorded an outcome"
21479        );
21480    }
21481
21482    /// `gate` leaves `state.gate_ran` false both before it has ever run and
21483    /// when its last attempt was resource-blocked (the shared build cache
21484    /// could not be acquired or confirmed fresh in time - see
21485    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
21486    /// `Vec` this also leaves behind used to read as "nothing failed" and let
21487    /// a run merge a tree the gate never actually checked - exactly the case
21488    /// a contended cache produces on every retry until it clears. `merge`
21489    /// must refuse until `gate` has actually recorded an attempt.
21490    #[tokio::test]
21491    async fn merge_refuses_a_gate_that_has_not_actually_run() {
21492        let tmp = tempfile::tempdir().expect("tempdir");
21493        let repo = tmp.path().join("repo");
21494        std::fs::create_dir_all(&repo).unwrap();
21495        init_repo(&repo);
21496
21497        let mut config = Config::default();
21498        config.merge.mode = MergeMode::Local;
21499
21500        let mut state = RunState::new(
21501            repo.clone(),
21502            "main".to_owned(),
21503            "deadbeef".to_owned(),
21504            "task".to_owned(),
21505            config,
21506        );
21507        state.candidates = vec![Candidate {
21508            index: 0,
21509            label: 'A',
21510            agent: "alpha".to_owned(),
21511            branch: "does-not-exist".to_owned(),
21512            worktree: repo.clone(),
21513            summary: String::new(),
21514            stat: String::new(),
21515            files: 0,
21516            commits: 0,
21517            empty: false,
21518            failed: None,
21519            verified_noop: None,
21520            duration_ms: 0,
21521            folded: false,
21522        }];
21523        state.tally = Some(Tally {
21524            first_choice: BTreeMap::from([('A', 1)]),
21525            borda: BTreeMap::new(),
21526            winner: 'A',
21527            rankings: 1,
21528            unanimous_initial: true,
21529            deliberated: false,
21530            changed_votes: 0,
21531            unanimous_final: true,
21532            tie_break: None,
21533            judges: 0,
21534            present: 0,
21535            quorum: 0,
21536            met_quorum: true,
21537            uncontested: Some("only candidate A produced a change".to_owned()),
21538        });
21539        state.reviews = vec![ReviewRound {
21540            round: 1,
21541            head: "deadbeef".to_owned(),
21542            verified_head: None,
21543            verified_at: None,
21544            reviews: Vec::new(),
21545            e2e: Vec::new(),
21546            fix: None,
21547            blocking: 0,
21548            answered: 0,
21549            expected: 0,
21550            clean: true,
21551            verify_retried: false,
21552            e2e_deferred: false,
21553            e2e_defer_reason: None,
21554            progressed: false,
21555            vote_split: false,
21556            reconsideration: Vec::new(),
21557            verdict: None,
21558        }];
21559        // The point: `gate` has not recorded anything yet.
21560        state.gate = Vec::new();
21561        state.gate_ran = false;
21562        state.status = RunStatus::Gating;
21563
21564        let mut runner = Runner {
21565            state,
21566            roles: ResolvedRoles {
21567                implementers: Vec::new(),
21568                judges: Vec::new(),
21569                reviewers: Vec::new(),
21570                fixer: None,
21571                conductor: conductor(),
21572                implementer_roster: Vec::new(),
21573                judge_roster: Vec::new(),
21574                reviewer_roster: Vec::new(),
21575            },
21576            sem: Arc::new(Semaphore::new(1)),
21577            pause: Pause::new(),
21578            interrupt: Pause::new(),
21579        };
21580
21581        runner.merge().await.expect("merge");
21582
21583        assert!(
21584            runner.state.merge.is_none(),
21585            "an empty gate must never be read as a passing one: {:?}",
21586            runner.state.merge
21587        );
21588    }
21589
21590    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21591    /// commands configured and `merge.mode` is `none` (a review-only run).
21592    /// `gate` must still record a real attempt — zero commands, vacuously
21593    /// passed — rather than leaving `state.gate` empty in a way `merge`
21594    /// cannot tell apart from "never ran"; otherwise the run reaches
21595    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21596    #[tokio::test]
21597    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21598        let tmp = tempfile::tempdir().expect("tempdir");
21599        let repo = tmp.path().join("repo");
21600        std::fs::create_dir_all(&repo).unwrap();
21601        init_repo(&repo);
21602
21603        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21604        let config = Config::default();
21605
21606        let mut state = RunState::new(
21607            repo.clone(),
21608            "main".to_owned(),
21609            "deadbeef".to_owned(),
21610            "task".to_owned(),
21611            config,
21612        );
21613        state.candidates = vec![Candidate {
21614            index: 0,
21615            label: 'A',
21616            agent: "alpha".to_owned(),
21617            branch: "does-not-exist".to_owned(),
21618            worktree: repo.clone(),
21619            summary: String::new(),
21620            stat: String::new(),
21621            files: 0,
21622            commits: 0,
21623            empty: false,
21624            failed: None,
21625            verified_noop: None,
21626            duration_ms: 0,
21627            folded: false,
21628        }];
21629        state.tally = Some(Tally {
21630            first_choice: BTreeMap::from([('A', 1)]),
21631            borda: BTreeMap::new(),
21632            winner: 'A',
21633            rankings: 1,
21634            unanimous_initial: true,
21635            deliberated: false,
21636            changed_votes: 0,
21637            unanimous_final: true,
21638            tie_break: None,
21639            judges: 0,
21640            present: 0,
21641            quorum: 0,
21642            met_quorum: true,
21643            uncontested: Some("only candidate A produced a change".to_owned()),
21644        });
21645        state.reviews = vec![ReviewRound {
21646            round: 1,
21647            head: "deadbeef".to_owned(),
21648            verified_head: None,
21649            verified_at: None,
21650            reviews: Vec::new(),
21651            e2e: Vec::new(),
21652            fix: None,
21653            blocking: 0,
21654            answered: 0,
21655            expected: 0,
21656            clean: true,
21657            verify_retried: false,
21658            e2e_deferred: false,
21659            e2e_defer_reason: None,
21660            progressed: false,
21661            vote_split: false,
21662            reconsideration: Vec::new(),
21663            verdict: None,
21664        }];
21665
21666        let mut runner = Runner {
21667            state,
21668            roles: ResolvedRoles {
21669                implementers: Vec::new(),
21670                judges: Vec::new(),
21671                reviewers: Vec::new(),
21672                fixer: None,
21673                conductor: conductor(),
21674                implementer_roster: Vec::new(),
21675                judge_roster: Vec::new(),
21676                reviewer_roster: Vec::new(),
21677            },
21678            sem: Arc::new(Semaphore::new(1)),
21679            pause: Pause::new(),
21680            interrupt: Pause::new(),
21681        };
21682
21683        runner.gate().await.expect("gate");
21684        assert!(
21685            runner.state.gate_ran,
21686            "zero configured commands is still a real attempt, not an unrun gate"
21687        );
21688        assert!(runner.state.gate.is_empty());
21689        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21690        assert_ne!(
21691            runner.state.status,
21692            RunStatus::Blocked,
21693            "a gate with nothing to check must not read as failed"
21694        );
21695
21696        runner.merge().await.expect("merge");
21697        assert_eq!(
21698            runner.state.status,
21699            RunStatus::Ready,
21700            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21701        );
21702    }
21703
21704    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21705    /// `verify.gate` (so the e2e leg and the final gate never build against
21706    /// different directories). With zero `verify.gate` commands but a
21707    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21708    /// that lease before discovering it had nothing to run - so a repo with
21709    /// no gate commands could come back `resource_blocked` (and therefore
21710    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21711    /// cache, exactly the contention this run's own zero commands could
21712    /// never have touched. `gate` must recognise there is nothing to check
21713    /// before it ever asks for the lease.
21714    #[tokio::test]
21715    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21716        crate::run::pin_test_home();
21717        let home = crate::run::home();
21718
21719        let tmp = tempfile::tempdir().expect("tempdir");
21720        let repo = tmp.path().join("repo");
21721        std::fs::create_dir_all(&repo).unwrap();
21722        init_repo(&repo);
21723        // Unique to this test, so holding its lease cannot collide with
21724        // another test sharing the same process-wide `home`.
21725        let cache_dir = tmp.path().join("target");
21726
21727        let mut config = Config::default();
21728        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21729        // `verify.gate` stays empty (the default). Any accidental cache
21730        // acquisition must report contention immediately, regardless of how
21731        // long unrelated Git subprocesses take under parallel test load.
21732        config.graph.timeout_verify = Some(2);
21733        config.graph.timeout_resource_wait = 0;
21734
21735        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21736        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21737            .expect("no io error acquiring directly")
21738        {
21739            crate::cache::AcquireOutcome::Acquired(g) => g,
21740            crate::cache::AcquireOutcome::Busy(b) => {
21741                panic!("expected the direct acquire to win the lease first: {b:?}")
21742            }
21743        };
21744
21745        let mut state = RunState::new(
21746            repo.clone(),
21747            "main".to_owned(),
21748            "deadbeef".to_owned(),
21749            "task".to_owned(),
21750            config,
21751        );
21752        state.candidates = vec![Candidate {
21753            index: 0,
21754            label: 'A',
21755            agent: "alpha".to_owned(),
21756            branch: "does-not-exist".to_owned(),
21757            worktree: repo.clone(),
21758            summary: String::new(),
21759            stat: String::new(),
21760            files: 0,
21761            commits: 0,
21762            empty: false,
21763            failed: None,
21764            verified_noop: None,
21765            duration_ms: 0,
21766            folded: false,
21767        }];
21768        state.tally = Some(Tally {
21769            first_choice: BTreeMap::from([('A', 1)]),
21770            borda: BTreeMap::new(),
21771            winner: 'A',
21772            rankings: 1,
21773            unanimous_initial: true,
21774            deliberated: false,
21775            changed_votes: 0,
21776            unanimous_final: true,
21777            tie_break: None,
21778            judges: 0,
21779            present: 0,
21780            quorum: 0,
21781            met_quorum: true,
21782            uncontested: Some("only candidate A produced a change".to_owned()),
21783        });
21784        state.reviews = vec![ReviewRound {
21785            round: 1,
21786            head: "deadbeef".to_owned(),
21787            verified_head: None,
21788            verified_at: None,
21789            reviews: Vec::new(),
21790            e2e: Vec::new(),
21791            fix: None,
21792            blocking: 0,
21793            answered: 0,
21794            expected: 0,
21795            clean: true,
21796            verify_retried: false,
21797            e2e_deferred: false,
21798            e2e_defer_reason: None,
21799            progressed: false,
21800            vote_split: false,
21801            reconsideration: Vec::new(),
21802            verdict: None,
21803        }];
21804
21805        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21806        state.reviews[0].e2e = vec![CommandOutcome {
21807            command: state.config.verify.e2e[0].clone(),
21808            code: Some(0),
21809            output_tail: String::new(),
21810            duration_ms: 0,
21811            resource_blocked: false,
21812            ..Default::default()
21813        }];
21814        let mut runner = Runner {
21815            state,
21816            roles: ResolvedRoles {
21817                implementers: Vec::new(),
21818                judges: Vec::new(),
21819                reviewers: Vec::new(),
21820                fixer: None,
21821                conductor: conductor(),
21822                implementer_roster: Vec::new(),
21823                judge_roster: Vec::new(),
21824                reviewer_roster: Vec::new(),
21825            },
21826            sem: Arc::new(Semaphore::new(1)),
21827            pause: Pause::new(),
21828            interrupt: Pause::new(),
21829        };
21830
21831        runner.gate().await.expect("gate");
21832        assert!(runner.state.resource_block.is_none());
21833        assert!(
21834            !runner
21835                .state
21836                .events
21837                .iter()
21838                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21839            "a gate with nothing to run must never request the held cache lease"
21840        );
21841        assert!(
21842            runner.state.gate_ran,
21843            "zero commands is still a real, immediate attempt"
21844        );
21845        assert!(runner.state.gate.is_empty());
21846        assert_ne!(
21847            runner.state.status,
21848            RunStatus::Blocked,
21849            "must not read as resource-blocked on a lease it never asked for"
21850        );
21851    }
21852
21853    /// A separate process carries a live worker's environment throughout all
21854    /// verification entry points; the parallel harness never changes its env.
21855    #[cfg(unix)]
21856    #[tokio::test]
21857    async fn verification_is_standalone_inside_a_live_worker() {
21858        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21859        if std::env::var_os(CHILD).is_none() {
21860            let home = tempfile::tempdir().unwrap();
21861            let generation = crate::worker::pin_current(home.path()).unwrap();
21862            let output = std::process::Command::new(std::env::current_exe().unwrap())
21863                .args([
21864                    "--exact",
21865                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21866                    "--nocapture",
21867                ])
21868                .env(CHILD, "1")
21869                .env("MAGI_HOME", home.path())
21870                .env("MAGI_WORKER_HOME", home.path())
21871                .env("MAGI_WORKER_ID", "abcdef")
21872                .env("MAGI_WORKER_GENERATION", &generation.id)
21873                .env("MAGI_WORKER_EXE", &generation.executable)
21874                .env("MAGI_RUN", "verification-parent")
21875                .env("MAGI_NODE", "gate")
21876                .env("MAGI_SEAT", "worker-fixture")
21877                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21878                .env("MAGI_NO_AUTOUPDATE", "0")
21879                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21880                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21881                .env(
21882                    "VERIFY_EXPECT_TOOLCHAIN",
21883                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21884                )
21885                .env(
21886                    "VERIFY_EXPECT_CACHE",
21887                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21888                )
21889                .output()
21890                .unwrap();
21891            assert!(
21892                output.status.success()
21893                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21894                "{}\n{}",
21895                String::from_utf8_lossy(&output.stdout),
21896                String::from_utf8_lossy(&output.stderr)
21897            );
21898            return;
21899        }
21900        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21901        let home = crate::run::home();
21902        let directory = home.join("workers/jobs/abcdef");
21903        std::fs::create_dir_all(&directory).unwrap();
21904        let job = crate::worker::Job {
21905            id: "abcdef".into(),
21906            sequence: 1,
21907            kind: "task".into(),
21908            key: "task:verification".into(),
21909            payload: serde_json::json!({}),
21910            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21911            version: Some(env!("CARGO_PKG_VERSION").into()),
21912            status: crate::worker::Status::Running,
21913            result: None,
21914            pid: Some(std::process::id()),
21915            created_at: 0,
21916            finished_at: None,
21917        };
21918        std::fs::write(
21919            directory.join("job.json"),
21920            serde_json::to_vec(&job).unwrap(),
21921        )
21922        .unwrap();
21923        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21924        let assert_worker = || {
21925            assert_eq!(
21926                crate::worker::current_job(&home).unwrap().unwrap().id,
21927                job.id
21928            );
21929            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21930            assert_eq!(
21931                crate::worker::helper_executable(&home).unwrap(),
21932                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21933            );
21934            assert!(
21935                crate::updater::Checker::new(&crate::config::Update {
21936                    mode: crate::config::UpdateMode::Notify,
21937                    interval: None,
21938                    auto_restart: false,
21939                })
21940                .is_none(),
21941                "the driver remains pinned, even while tests are standalone"
21942            );
21943        };
21944        assert_worker();
21945        let repo = home.join("repo");
21946        std::fs::create_dir_all(&repo).unwrap();
21947        init_repo(&repo);
21948        // Keep storage, seat/control context, containment and tool lookup.
21949        // No inherited values (or credentials) are printed on success.
21950        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21951            test -z "${MAGI_WORKER_GENERATION+x}" &&
21952            test -z "${MAGI_WORKER_HOME+x}" &&
21953            test -z "${MAGI_WORKER_EXE+x}" &&
21954            test "$MAGI_HOME/repo" -ef . &&
21955            test "$MAGI_RUN" = verification-parent &&
21956            test "$MAGI_NODE" = gate &&
21957            test "$MAGI_SEAT" = worker-fixture &&
21958            test -n "$MAGI_PROCESS_OWNER" &&
21959            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21960            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21961            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21962            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21963        // Negative control: an ordinary child inherits the contamination.
21964        assert!(
21965            !std::process::Command::new("sh")
21966                .args(["-c", probe])
21967                .current_dir(&repo)
21968                .status()
21969                .unwrap()
21970                .success()
21971        );
21972        let unrelated_home = tempfile::tempdir().unwrap();
21973        assert!(
21974            crate::worker::current_job(unrelated_home.path()).is_err(),
21975            "an inherited worker id cannot be resolved in a unit fixture's home"
21976        );
21977        let mut runner = runner_at(RunStatus::Gating);
21978        runner.state.repo = repo.clone();
21979        runner.state.config.disk.min_free_bytes = 0;
21980        runner.state.config.coordination = crate::config::test_coordination();
21981        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21982        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21983        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21984        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21985        let winner = Candidate {
21986            index: 0,
21987            label: 'A',
21988            agent: "fixture".into(),
21989            branch: "main".into(),
21990            worktree: repo.clone(),
21991            summary: String::new(),
21992            stat: String::new(),
21993            files: 0,
21994            commits: 0,
21995            empty: false,
21996            failed: None,
21997            verified_noop: None,
21998            duration_ms: 0,
21999            folded: false,
22000        };
22001        let (e2e, retried, pids) = run_e2e_with_retry(
22002            &mut runner.state,
22003            &["sh".into(), "-c".into()],
22004            &[format!("{probe} && printf initial")],
22005            &repo,
22006            Duration::from_secs(10),
22007            "initial",
22008            None,
22009        )
22010        .await;
22011        assert!(!retried && pids.is_empty());
22012        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22013        assert_eq!(e2e[0].output_tail, "initial");
22014        let gate = runner.run_gate(&winner).await.unwrap();
22015        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22016        // An interrupted repair must recheck e2e from saved state. Landing
22017        // reuses that state and must run both pre-gate and gate again.
22018        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22019            git::rev_parse(&repo, "HEAD").await.unwrap(),
22020            false,
22021            Vec::new(),
22022        ));
22023        runner.state.save().unwrap();
22024        let mut resumed = RunState::load(&runner.state.id).unwrap();
22025        let wait = crate::repo_lock::WaitPolicy::default();
22026        assert!(matches!(
22027            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22028                .await
22029                .unwrap(),
22030            GateFix::Retry
22031        ));
22032        let saved = RunState::load(&resumed.id).unwrap();
22033        let repair = saved.gate_repair_e2e.unwrap();
22034        assert!(repair.passed);
22035        assert_eq!(repair.outcomes.len(), 1);
22036        assert!(repair.outcomes[0].ok());
22037        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22038            .await
22039            .unwrap();
22040        assert_eq!(landing.len(), 1);
22041        assert!(landing[0].ok(), "{landing:?}");
22042        assert_eq!(
22043            std::fs::read_to_string(repo.join("phases")).unwrap(),
22044            "pre\ngate\ne2e\npre\ngate\n"
22045        );
22046        assert_worker();
22047    }
22048
22049    #[cfg(unix)]
22050    #[tokio::test]
22051    async fn verification_keeps_the_panic_and_the_full_output() {
22052        crate::run::pin_test_home();
22053        let tmp = tempfile::tempdir().unwrap();
22054        let mut config = Config::default();
22055        config.disk.min_free_bytes = 0;
22056        let mut state = RunState::new(
22057            tmp.path().to_owned(),
22058            "main".into(),
22059            "base".into(),
22060            "verification evidence".into(),
22061            config,
22062        );
22063        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22064                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22065                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22066        let mut names = Vec::new();
22067        for _ in 0..2 {
22068            let (outcomes, _) = run_commands(
22069                &mut state,
22070                "gate",
22071                "gate",
22072                0,
22073                &["sh".into(), "-c".into()],
22074                &[script.into()],
22075                tmp.path(),
22076                Duration::from_secs(60),
22077            )
22078            .await;
22079            let tail = &outcomes[0].output_tail;
22080            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
22081            assert!(tail.contains("boom assertion"));
22082            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
22083            let line = tail.lines().next().unwrap();
22084            names.push(line.to_owned());
22085        }
22086        assert_ne!(names[0], names[1], "the second run must not overwrite");
22087        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
22088        assert!(full.len() > 500_000 && full.contains("boom assertion"));
22089        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
22090
22091        // Storage failures are evidence too; preserve the command's verdict.
22092        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
22093        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
22094        let (outcomes, _) = run_commands(
22095            &mut state,
22096            "gate",
22097            "gate",
22098            0,
22099            &["sh".into(), "-c".into()],
22100            &["echo failure-output; exit 7".into()],
22101            tmp.path(),
22102            Duration::from_secs(10),
22103        )
22104        .await;
22105        assert_eq!(outcomes[0].code, Some(7));
22106        assert!(state.events.iter().any(|e| {
22107            e.node == "gate" && e.message.contains("could not save the full gate output:")
22108        }));
22109    }
22110
22111    #[cfg(unix)]
22112    #[tokio::test]
22113    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
22114        crate::run::pin_test_home();
22115        let tmp = tempfile::tempdir().unwrap();
22116        let mut config = Config::default();
22117        config.disk.min_free_bytes = 0;
22118        let mut state = RunState::new(
22119            tmp.path().to_owned(),
22120            "main".into(),
22121            "base".into(),
22122            "verification evidence".into(),
22123            config,
22124        );
22125        let (outcomes, pids) = run_commands(
22126            &mut state,
22127            "gate",
22128            "gate",
22129            1,
22130            &["sh".into(), "-c".into()],
22131            &[
22132                "printf before-timeout; exec sleep 30".into(),
22133                "kill -TERM $$".into(),
22134                "exit 7".into(),
22135                "printf success".into(),
22136            ],
22137            tmp.path(),
22138            Duration::from_secs(1),
22139        )
22140        .await;
22141        wait_for_timed_out_children_to_die(&pids).await;
22142        assert_eq!(
22143            pids.len(),
22144            1,
22145            "unleased timeout retains its death-check PID"
22146        );
22147        assert_eq!(outcomes.len(), 4);
22148        assert_eq!(outcomes[0].code, None);
22149        assert!(outcomes[0].output_tail.contains("before-timeout"));
22150        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
22151        assert_eq!(outcomes[1].code, None);
22152        assert!(outcomes[1].output_tail.contains("command terminated:"));
22153        assert!(!outcomes[1].output_tail.contains("timed out"));
22154        assert_eq!(outcomes[2].code, Some(7));
22155        assert!(!outcomes[2].output_tail.contains("timed out"));
22156        assert_eq!(outcomes[3].code, Some(0));
22157        assert_eq!(outcomes[3].output_tail, "success");
22158        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
22159    }
22160
22161    /// The addendum's second gap: a `verify.gate` command running for real
22162    /// wall-clock time had nothing at all to show for it in `active` before
22163    /// `run_commands` learned to record it — a run could sit in `Gating` for
22164    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
22165    /// what was actually happening. Proven with a genuinely still-running
22166    /// command, not just a before/after check on the final state: a poller
22167    /// task reads the same `run.json` `gate()` is writing, the same way the
22168    /// phone or `magi show` would, while the shell command is still blocked
22169    /// on its own release marker.
22170    #[tokio::test]
22171    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
22172        crate::run::pin_test_home();
22173
22174        let tmp = tempfile::tempdir().expect("tempdir");
22175        let repo = tmp.path().join("repo");
22176        std::fs::create_dir_all(&repo).unwrap();
22177        init_repo(&repo);
22178
22179        let mut config = Config::default();
22180        config.disk.min_free_bytes = 0;
22181        config.verify.gate = vec![
22182            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
22183             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
22184                .to_owned(),
22185        ];
22186
22187        let mut state = RunState::new(
22188            repo.clone(),
22189            "main".to_owned(),
22190            "deadbeef".to_owned(),
22191            "task".to_owned(),
22192            config,
22193        );
22194        let run_id = state.id.clone();
22195        state.candidates = vec![Candidate {
22196            index: 0,
22197            label: 'A',
22198            agent: "alpha".to_owned(),
22199            branch: "does-not-exist".to_owned(),
22200            worktree: repo.clone(),
22201            summary: String::new(),
22202            stat: String::new(),
22203            files: 0,
22204            commits: 0,
22205            empty: false,
22206            failed: None,
22207            verified_noop: None,
22208            duration_ms: 0,
22209            folded: false,
22210        }];
22211        state.tally = Some(Tally {
22212            first_choice: BTreeMap::from([('A', 1)]),
22213            borda: BTreeMap::new(),
22214            winner: 'A',
22215            rankings: 1,
22216            unanimous_initial: true,
22217            deliberated: false,
22218            changed_votes: 0,
22219            unanimous_final: true,
22220            tie_break: None,
22221            judges: 0,
22222            present: 0,
22223            quorum: 0,
22224            met_quorum: true,
22225            uncontested: Some("only candidate A produced a change".to_owned()),
22226        });
22227        state.reviews = vec![ReviewRound {
22228            round: 1,
22229            head: "deadbeef".to_owned(),
22230            verified_head: None,
22231            verified_at: None,
22232            reviews: Vec::new(),
22233            e2e: Vec::new(),
22234            fix: None,
22235            blocking: 0,
22236            answered: 0,
22237            expected: 0,
22238            clean: true,
22239            verify_retried: false,
22240            e2e_deferred: false,
22241            e2e_defer_reason: None,
22242            progressed: false,
22243            vote_split: false,
22244            reconsideration: Vec::new(),
22245            verdict: None,
22246        }];
22247
22248        let mut runner = Runner {
22249            state,
22250            roles: ResolvedRoles {
22251                implementers: Vec::new(),
22252                judges: Vec::new(),
22253                reviewers: Vec::new(),
22254                fixer: None,
22255                conductor: conductor(),
22256                implementer_roster: Vec::new(),
22257                judge_roster: Vec::new(),
22258                reviewer_roster: Vec::new(),
22259            },
22260            sem: Arc::new(Semaphore::new(1)),
22261            pause: Pause::new(),
22262            interrupt: Pause::new(),
22263        };
22264
22265        let started_marker = repo.join("started.marker");
22266        let release_marker = repo.join("release.marker");
22267        let observe = async {
22268            loop {
22269                if started_marker.exists()
22270                    && let Ok(s) = crate::run::RunState::load(&run_id)
22271                    && let Some(a) = s.active.get("gate")
22272                {
22273                    std::fs::write(&release_marker, b"go").expect("release marker");
22274                    break a.clone();
22275                }
22276                tokio::time::sleep(Duration::from_millis(50)).await;
22277            }
22278        };
22279        let captured = {
22280            let gate = runner.gate();
22281            tokio::pin!(gate);
22282            let captured = tokio::select! {
22283                observed = observe => observed,
22284                result = &mut gate => panic!(
22285                    "gate exited before its in-flight entry was observed: {result:?}"
22286                ),
22287            };
22288            gate.await.expect("gate");
22289            captured
22290        };
22291
22292        assert_eq!(captured.task.as_deref(), Some("gate"));
22293        assert_eq!(captured.node, "gate");
22294        assert_eq!(captured.index, Some(1));
22295        assert_eq!(captured.total, Some(1));
22296        assert!(
22297            captured
22298                .command
22299                .as_deref()
22300                .is_some_and(|c| c.contains("started.marker")),
22301            "{captured:?}"
22302        );
22303
22304        assert!(
22305            runner.state.active.is_empty(),
22306            "the entry must be cleared once the command actually finished: {:?}",
22307            runner.state.active
22308        );
22309        assert!(runner.state.gate_ran);
22310        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
22311    }
22312
22313    /// The hand-off over a blocking finding a reviewer rejected on leaves a
22314    /// record for `land`; one with only a Minor, or no reject, leaves none.
22315    #[tokio::test]
22316    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
22317        use crate::verdict::{Finding, ReviewVote, Severity};
22318        crate::run::pin_test_home();
22319        let tmp = tempfile::tempdir().expect("tempdir");
22320        let repo = tmp.path().join("repo");
22321        std::fs::create_dir_all(&repo).unwrap();
22322        init_repo(&repo);
22323
22324        for (severity, vote, expect) in [
22325            (Severity::Major, ReviewVote::Reject, true),
22326            (Severity::Minor, ReviewVote::Reject, false),
22327            (Severity::Major, ReviewVote::Approve, false),
22328        ] {
22329            let mut round = review_round(false, 1, 1, 1, false, true);
22330            round.reviews = vec![ReviewRecord {
22331                reviewer: 1,
22332                agent: "alpha".to_owned(),
22333                summary: String::new(),
22334                findings: vec![Finding {
22335                    id: "R1-1-1".to_owned(),
22336                    severity,
22337                    file: None,
22338                    line: None,
22339                    title: "t".to_owned(),
22340                    detail: String::new(),
22341                }],
22342                vote: Some(vote),
22343                failed: None,
22344                duration_ms: 0,
22345                attempts: 0,
22346            }];
22347            let mut state = RunState::new(
22348                repo.clone(),
22349                "main".to_owned(),
22350                "deadbeef".to_owned(),
22351                "task".to_owned(),
22352                Config::default(),
22353            );
22354            state.reviews = vec![round];
22355            let mut runner = Runner {
22356                state,
22357                roles: ResolvedRoles {
22358                    implementers: Vec::new(),
22359                    judges: Vec::new(),
22360                    reviewers: Vec::new(),
22361                    fixer: None,
22362                    conductor: conductor(),
22363                    implementer_roster: Vec::new(),
22364                    judge_roster: Vec::new(),
22365                    reviewer_roster: Vec::new(),
22366                },
22367                sem: Arc::new(Semaphore::new(1)),
22368                pause: Pause::new(),
22369                interrupt: Pause::new(),
22370            };
22371            let shell = runner.state.config.shell();
22372            runner
22373                .stop_reviewing("round budget spent", &shell, &repo)
22374                .await
22375                .expect("stop_reviewing");
22376            assert_eq!(runner.state.status, RunStatus::Gating);
22377            assert_eq!(
22378                runner.state.contested_handoff.is_some(),
22379                expect,
22380                "{severity:?} + {vote:?}"
22381            );
22382        }
22383    }
22384
22385    /// The shape the incident this whole fix responds to actually had: the
22386    /// round budget spent, the last round's own e2e blocked on the shared
22387    /// build cache (held here by a live pid — this test process — exactly
22388    /// `cache`'s own unit tests' pattern for "another owner, still alive"
22389    /// without forking a process). `stop_reviewing` must retry it — not
22390    /// silently leave the round looking untouched (the catch-up-only half of
22391    /// the bug), and not read the contention as a red `e2e` and block the
22392    /// run on it (the other half). Called directly, the same way
22393    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
22394    /// above exercises `gate`, so this never needs a real cargo build to
22395    /// reach: the lease is never released, so `with_cache_lease` never gets
22396    /// past acquiring it into anything that would need a real workspace.
22397    #[tokio::test]
22398    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
22399        crate::run::pin_test_home();
22400        let home = crate::run::home();
22401
22402        let tmp = tempfile::tempdir().expect("tempdir");
22403        let repo = tmp.path().join("repo");
22404        std::fs::create_dir_all(&repo).unwrap();
22405        init_repo(&repo);
22406        let head = crate::git::rev_parse(&repo, "HEAD")
22407            .await
22408            .expect("rev-parse");
22409        // Unique to this test, so holding its lease cannot collide with
22410        // another test sharing the same process-wide `home`.
22411        let cache_dir = tmp.path().join("target");
22412
22413        let mut config = Config::default();
22414        config.verify.e2e = vec![format!(
22415            "CARGO_TARGET_DIR='{}' test -f README.md",
22416            cache_dir.display()
22417        )];
22418        config.graph.review_rounds = 1;
22419        // Bounded so a regression that does start waiting fails the test in
22420        // seconds, not hangs it.
22421        config.graph.timeout_verify = Some(2);
22422        config.graph.timeout_resource_wait = 2;
22423
22424        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22425        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22426            .expect("no io error acquiring directly")
22427        {
22428            crate::cache::AcquireOutcome::Acquired(g) => g,
22429            crate::cache::AcquireOutcome::Busy(b) => {
22430                panic!("expected the direct acquire to win the lease first: {b:?}")
22431            }
22432        };
22433
22434        let mut state = RunState::new(
22435            repo.clone(),
22436            "main".to_owned(),
22437            head.clone(),
22438            "task".to_owned(),
22439            config,
22440        );
22441        state.candidates = vec![Candidate {
22442            index: 0,
22443            label: 'A',
22444            agent: "alpha".to_owned(),
22445            branch: "does-not-exist".to_owned(),
22446            worktree: repo.clone(),
22447            summary: String::new(),
22448            stat: String::new(),
22449            files: 0,
22450            commits: 0,
22451            empty: false,
22452            failed: None,
22453            verified_noop: None,
22454            duration_ms: 0,
22455            folded: false,
22456        }];
22457        state.tally = Some(Tally {
22458            first_choice: BTreeMap::from([('A', 1)]),
22459            borda: BTreeMap::new(),
22460            winner: 'A',
22461            rankings: 1,
22462            unanimous_initial: true,
22463            deliberated: false,
22464            changed_votes: 0,
22465            unanimous_final: true,
22466            tie_break: None,
22467            judges: 0,
22468            present: 0,
22469            quorum: 0,
22470            met_quorum: true,
22471            uncontested: Some("only candidate A produced a change".to_owned()),
22472        });
22473        // The round budget's last round, deferred: `needs_catchup_run`'s
22474        // other trigger. `stop_reviewing`'s retry machinery must treat this
22475        // exactly like a resource-blocked attempt once it actually runs.
22476        state.reviews = vec![ReviewRound {
22477            round: 1,
22478            head: head.clone(),
22479            verified_head: None,
22480            verified_at: None,
22481            reviews: Vec::new(),
22482            e2e: Vec::new(),
22483            fix: None,
22484            blocking: 1,
22485            answered: 1,
22486            expected: 1,
22487            clean: false,
22488            verify_retried: false,
22489            e2e_deferred: true,
22490            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
22491            progressed: false,
22492            vote_split: false,
22493            reconsideration: Vec::new(),
22494            verdict: None,
22495        }];
22496
22497        let mut runner = Runner {
22498            state,
22499            roles: ResolvedRoles {
22500                implementers: Vec::new(),
22501                judges: Vec::new(),
22502                reviewers: Vec::new(),
22503                fixer: None,
22504                conductor: conductor(),
22505                implementer_roster: Vec::new(),
22506                judge_roster: Vec::new(),
22507                reviewer_roster: Vec::new(),
22508            },
22509            sem: Arc::new(Semaphore::new(1)),
22510            pause: Pause::new(),
22511            interrupt: Pause::new(),
22512        };
22513
22514        let shell = runner.state.config.shell();
22515        runner
22516            .stop_reviewing("round budget spent", &shell, &repo)
22517            .await
22518            .expect("stop_reviewing");
22519
22520        let last = runner.state.reviews.last().expect("round record");
22521        assert_eq!(
22522            last.e2e_status(),
22523            E2eStatus::ResourceBlocked,
22524            "the shared cache is still held; the attempt must read as blocked, not deferred or \
22525             failed: {last:?}"
22526        );
22527        assert_eq!(
22528            last.verified_head.as_deref(),
22529            Some(head.as_str()),
22530            "which commit this attempt targeted is known even though nothing finished checking \
22531             it"
22532        );
22533        let first_attempt_at = last
22534            .verified_at
22535            .expect("when this attempt ran is known too");
22536        assert_ne!(
22537            runner.state.status,
22538            RunStatus::Blocked,
22539            "contention is evidence about the machine, not the patch — it must not settle the \
22540             run as blocked: {:?}",
22541            runner.state.status
22542        );
22543        assert!(
22544            !runner
22545                .state
22546                .events
22547                .iter()
22548                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
22549            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
22550            runner.state.events
22551        );
22552
22553        // The cache is still held: a later reentry must retry the same
22554        // round's verification again — not leave it looking exactly as
22555        // untouched as the first blocked attempt, which is indistinguishable
22556        // from never having tried again at all.
22557        runner
22558            .stop_reviewing("round budget spent", &shell, &repo)
22559            .await
22560            .expect("stop_reviewing retry");
22561        assert_eq!(
22562            runner.state.reviews.len(),
22563            1,
22564            "no new round was started: {:?}",
22565            runner.state.reviews
22566        );
22567        let last = runner.state.reviews.last().expect("round record");
22568        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22569        assert!(
22570            last.verified_at.expect("still known") > first_attempt_at,
22571            "a second reentry must be a fresh attempt, not a stale copy of the first"
22572        );
22573        assert_ne!(runner.state.status, RunStatus::Blocked);
22574
22575        held.release();
22576    }
22577
22578    #[cfg(unix)]
22579    #[tokio::test]
22580    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22581        ask_test_home();
22582        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22583            let tmp = tempfile::tempdir().unwrap();
22584            let repo = tmp.path().join("repo");
22585            std::fs::create_dir(&repo).unwrap();
22586            init_repo(&repo);
22587            let run_git = |args: &[&str]| {
22588                let out = std::process::Command::new("git")
22589                    .args(args)
22590                    .current_dir(&repo)
22591                    .output()
22592                    .unwrap();
22593                assert!(
22594                    out.status.success(),
22595                    "{args:?}: {}",
22596                    String::from_utf8_lossy(&out.stderr)
22597                );
22598            };
22599            let origin = tmp.path().join("origin.git");
22600            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22601            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22602            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22603            run_git(&["add", "spec.rs"]);
22604            run_git(&["commit", "-m", "initial spec"]);
22605            run_git(&["push", "origin", "main"]);
22606            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22607            run_git(&["checkout", "-b", "fix/review"]);
22608            std::fs::write(
22609                repo.join("check.rs"),
22610                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22611            )
22612            .unwrap();
22613            run_git(&["add", "check.rs"]);
22614            run_git(&["commit", "-m", "use spec"]);
22615            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22616            run_git(&["checkout", "main"]);
22617            std::fs::write(
22618                repo.join("spec.rs"),
22619                "struct AgentSpec { max_turn_secs: u64 }\n",
22620            )
22621            .unwrap();
22622            run_git(&["add", "spec.rs"]);
22623            run_git(&["commit", "-m", "extend spec"]);
22624            run_git(&["push", "origin", "main"]);
22625            run_git(&["checkout", "fix/review"]);
22626
22627            let mut runner = runner_at(RunStatus::Reviewing);
22628            runner.state.repo = repo.clone();
22629            runner.state.base_commit = base;
22630            runner.state.pr_head = Some("fix/review".into());
22631            runner.state.config.graph.review_rounds = max_rounds;
22632            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22633            runner.state.config.graph.sessions = false;
22634            runner.state.config.disk.min_free_bytes = 0;
22635            runner.state.config.verify.e2e =
22636                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22637            runner.state.candidates = vec![Candidate {
22638                index: 0,
22639                label: 'A',
22640                agent: "fixture".into(),
22641                branch: "fix/review".into(),
22642                worktree: repo.clone(),
22643                summary: String::new(),
22644                stat: String::new(),
22645                files: 1,
22646                commits: 1,
22647                empty: false,
22648                failed: None,
22649                verified_noop: None,
22650                duration_ms: 0,
22651                folded: false,
22652            }];
22653            runner.state.tally = Some(Tally {
22654                first_choice: BTreeMap::new(),
22655                borda: BTreeMap::new(),
22656                winner: 'A',
22657                rankings: 0,
22658                unanimous_initial: true,
22659                deliberated: false,
22660                changed_votes: 0,
22661                unanimous_final: true,
22662                tie_break: None,
22663                judges: 0,
22664                present: 0,
22665                quorum: 0,
22666                met_quorum: true,
22667                uncontested: Some("review-only".into()),
22668            });
22669            let mut last = review_round(false, 0, 1, 1, false, false);
22670            last.head = reviewed.clone();
22671            last.e2e_deferred = true;
22672            last.e2e[0].resource_blocked = true;
22673            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22674            if max_rounds == 1 {
22675                last.e2e.clear();
22676            }
22677            runner.state.reviews = vec![last];
22678            let calls = tmp.path().join("fix-calls");
22679            let mut fixer = spec("repair");
22680            fixer
22681                .env
22682                .insert("FIX_CALLS".into(), calls.display().to_string());
22683            fixer.command = vec!["sh".into(), "-c".into(), r#"
22684                echo fix >> "$FIX_CALLS"
22685                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22686                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22687                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22688                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22689            "#.into()];
22690            let mut reviewer = spec("reviewer");
22691            reviewer.command = vec![
22692                "sh".into(),
22693                "-c".into(),
22694                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22695                    .into(),
22696            ];
22697            runner.roles.fixer = Some(vec![fixer]);
22698            runner.roles.reviewers = vec![reviewer];
22699
22700            runner.sync_to_base().await.unwrap();
22701            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22702            assert_ne!(rebased, reviewed);
22703            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22704            if reentry {
22705                // Simulate a crash after catch-up evidence was saved but before
22706                // dispatching the fixer. No dedicated pending-repair field exists.
22707                let shell = runner.state.config.shell();
22708                runner
22709                    .stop_unresolved_review("deferred verification", &shell, &repo)
22710                    .await
22711                    .unwrap();
22712                assert!(runner.catchup_repairable());
22713                assert!(!calls.exists());
22714                runner.state = RunState::load(&runner.state.id).unwrap();
22715                assert!(runner.catchup_repairable());
22716            }
22717            runner.review_loop().await.unwrap();
22718            let first = &runner.state.reviews[0];
22719            assert_eq!(first.head, reviewed);
22720            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22721            assert!(
22722                first.verify_retried,
22723                "a reproduced build failure gets exactly one retry: {:?}",
22724                first.e2e
22725            );
22726            assert!(first.e2e[0].output_tail.contains("E0063"));
22727            assert!(!runner.catchup_repairable());
22728            if max_rounds == 2 {
22729                assert_eq!(
22730                    runner.state.status,
22731                    RunStatus::Gating,
22732                    "{}",
22733                    crate::report::run(&runner.state)
22734                );
22735                assert_eq!(runner.state.reviews.len(), 2);
22736                assert!(first.fix.as_ref().unwrap().committed);
22737                assert!(runner.state.reviews[1].clean);
22738                assert_eq!(
22739                    runner
22740                        .state
22741                        .reviews
22742                        .iter()
22743                        .filter(|r| r.fix.is_some())
22744                        .count(),
22745                    1
22746                );
22747                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22748                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22749            } else {
22750                assert_eq!(runner.state.status, RunStatus::Blocked);
22751                assert!(first.fix.is_none());
22752                assert!(!calls.exists());
22753                let recovery = crate::recovery::assess(
22754                    "prior",
22755                    Some(&runner.state),
22756                    &runner.landing_base(),
22757                    crate::recovery::Relation::Diverged,
22758                );
22759                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22760                let reasons = recovery.reasons.join("\n");
22761                assert!(
22762                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22763                    "{reasons}"
22764                );
22765                assert!(
22766                    reasons.contains("base sync to")
22767                        && reasons.contains("additional review is required"),
22768                    "{reasons}"
22769                );
22770            }
22771        }
22772    }
22773
22774    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22775    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22776    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22777    /// own top-of-function fast path (`review_conclusion`) correctly reads
22778    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22779    /// own `for` range is empty once the round budget is spent, so
22780    /// `review_loop` must retry the check itself rather than silently doing
22781    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22782    /// above exercises directly, but through `review_loop`'s own entry point
22783    /// this time, proving the wiring between the two rather than just the
22784    /// retry logic in isolation.
22785    #[tokio::test]
22786    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22787        crate::run::pin_test_home();
22788        let home = crate::run::home();
22789
22790        let tmp = tempfile::tempdir().expect("tempdir");
22791        let repo = tmp.path().join("repo");
22792        std::fs::create_dir_all(&repo).unwrap();
22793        init_repo(&repo);
22794        let head = crate::git::rev_parse(&repo, "HEAD")
22795            .await
22796            .expect("rev-parse");
22797        let cache_dir = tmp.path().join("target");
22798
22799        let mut config = Config::default();
22800        config.verify.e2e = vec![format!(
22801            "CARGO_TARGET_DIR='{}' test -f README.md",
22802            cache_dir.display()
22803        )];
22804        config.graph.review_rounds = 1;
22805        config.graph.timeout_verify = Some(2);
22806        config.graph.timeout_resource_wait = 2;
22807
22808        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22809        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22810            .expect("no io error acquiring directly")
22811        {
22812            crate::cache::AcquireOutcome::Acquired(g) => g,
22813            crate::cache::AcquireOutcome::Busy(b) => {
22814                panic!("expected the direct acquire to win the lease first: {b:?}")
22815            }
22816        };
22817
22818        let mut state = RunState::new(
22819            repo.clone(),
22820            "main".to_owned(),
22821            head.clone(),
22822            "task".to_owned(),
22823            config,
22824        );
22825        state.candidates = vec![Candidate {
22826            index: 0,
22827            label: 'A',
22828            agent: "alpha".to_owned(),
22829            branch: "does-not-exist".to_owned(),
22830            worktree: repo.clone(),
22831            summary: String::new(),
22832            stat: String::new(),
22833            files: 0,
22834            commits: 0,
22835            empty: false,
22836            failed: None,
22837            verified_noop: None,
22838            duration_ms: 0,
22839            folded: false,
22840        }];
22841        state.tally = Some(Tally {
22842            first_choice: BTreeMap::from([('A', 1)]),
22843            borda: BTreeMap::new(),
22844            winner: 'A',
22845            rankings: 1,
22846            unanimous_initial: true,
22847            deliberated: false,
22848            changed_votes: 0,
22849            unanimous_final: true,
22850            tie_break: None,
22851            judges: 0,
22852            present: 0,
22853            quorum: 0,
22854            met_quorum: true,
22855            uncontested: Some("only candidate A produced a change".to_owned()),
22856        });
22857        // The exact shape a prior process's `stop_reviewing` would have left
22858        // on disk: the round budget's last round, a real attempt already
22859        // made and already resource-blocked.
22860        state.reviews = vec![ReviewRound {
22861            round: 1,
22862            head: head.clone(),
22863            verified_head: Some(head.clone()),
22864            verified_at: Some(jiff::Timestamp::now()),
22865            reviews: Vec::new(),
22866            e2e: vec![CommandOutcome {
22867                command: format!(
22868                    "CARGO_TARGET_DIR='{}' test -f README.md",
22869                    cache_dir.display()
22870                ),
22871                code: None,
22872                output_tail: "waiting for the shared build cache".to_owned(),
22873                duration_ms: 0,
22874                resource_blocked: true,
22875                ..Default::default()
22876            }],
22877            fix: None,
22878            blocking: 1,
22879            answered: 1,
22880            expected: 1,
22881            clean: false,
22882            verify_retried: false,
22883            e2e_deferred: false,
22884            e2e_defer_reason: None,
22885            progressed: false,
22886            vote_split: false,
22887            reconsideration: Vec::new(),
22888            verdict: None,
22889        }];
22890
22891        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22892        let mut runner = Runner {
22893            state,
22894            roles: ResolvedRoles {
22895                implementers: Vec::new(),
22896                judges: Vec::new(),
22897                reviewers: Vec::new(),
22898                fixer: None,
22899                conductor: conductor(),
22900                implementer_roster: Vec::new(),
22901                judge_roster: Vec::new(),
22902                reviewer_roster: Vec::new(),
22903            },
22904            sem: Arc::new(Semaphore::new(1)),
22905            pause: Pause::new(),
22906            interrupt: Pause::new(),
22907        };
22908
22909        // The lease is still held throughout, so this reentry's own retry is
22910        // also contended — proving `review_loop` actually tried again (not
22911        // that it happened to succeed) is what the timestamp comparison
22912        // below is for.
22913        runner.review_loop().await.expect("review_loop");
22914
22915        assert_eq!(
22916            runner.state.reviews.len(),
22917            1,
22918            "no new round was started on top of the unresolved one: {:?}",
22919            runner.state.reviews
22920        );
22921        let last = &runner.state.reviews[0];
22922        assert_eq!(
22923            last.e2e_status(),
22924            E2eStatus::ResourceBlocked,
22925            "still contended: {last:?}"
22926        );
22927        assert!(
22928            last.verified_at.expect("still known") > first_attempt_at,
22929            "review_loop must have actually retried the check, not left it exactly as found"
22930        );
22931        assert_ne!(
22932            runner.state.status,
22933            RunStatus::Blocked,
22934            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22935            runner.state.status
22936        );
22937
22938        held.release();
22939    }
22940
22941    #[tokio::test]
22942    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22943        crate::run::pin_test_home();
22944        for status in [RunStatus::Blocked, RunStatus::Gating] {
22945            let mut runner = runner_at(status);
22946            runner.state.config.graph.land = true;
22947            runner.state.gate_ran = true;
22948            runner.state.merge = Some(MergeOutcome {
22949                mode: MergeMode::Pr,
22950                ok: false,
22951                detail: "the fixer produced no commit".into(),
22952                empty: false,
22953            });
22954            let url = "https://example.invalid/o/r/pull/1";
22955            runner.state.pr = Some(crate::run::PrRecord {
22956                url: url.into(),
22957                number: 1,
22958                state: "open".into(),
22959                checks: "red".into(),
22960                round: 1,
22961                rounds: 1,
22962                red_at_merge: Vec::new(),
22963            });
22964            runner.state.save().unwrap();
22965            // The nonexistent repository makes observation fail before a forge
22966            // command can run. We still must reach land, rather than silently
22967            // return from the graph with its old gate and merge records.
22968            runner.execute_graph().await.unwrap();
22969            assert_eq!(runner.state.status, RunStatus::Blocked);
22970            assert!(runner.state.land_sync_pending);
22971            assert!(runner.state.events.iter().any(|event|
22972                event.node == "land" && event.message == format!("watching {url}")));
22973            assert_eq!(
22974                runner.state.merge.as_ref().unwrap().detail,
22975                "the fixer produced no commit"
22976            );
22977        }
22978    }
22979
22980    #[tokio::test]
22981    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22982        crate::run::pin_test_home();
22983        let tmp = tempfile::tempdir().expect("tempdir");
22984        let repo = tmp.path().join("repo");
22985        std::fs::create_dir_all(&repo).unwrap();
22986        init_repo(&repo);
22987
22988        let mut config = Config::default();
22989        config.merge.mode = MergeMode::Pr;
22990        config.graph.land = true;
22991        config.graph.land_approval = false;
22992
22993        let mut state = RunState::new(
22994            repo.clone(),
22995            "main".to_owned(),
22996            "deadbeef".to_owned(),
22997            "task".to_owned(),
22998            config,
22999        );
23000        state.candidates = vec![Candidate {
23001            index: 0,
23002            label: 'A',
23003            agent: "alpha".to_owned(),
23004            branch: "does-not-exist".to_owned(),
23005            worktree: repo.clone(),
23006            summary: String::new(),
23007            stat: String::new(),
23008            files: 0,
23009            commits: 0,
23010            empty: false,
23011            failed: None,
23012            verified_noop: None,
23013            duration_ms: 0,
23014            folded: false,
23015        }];
23016        state.tally = Some(Tally {
23017            first_choice: BTreeMap::from([('A', 1)]),
23018            borda: BTreeMap::new(),
23019            winner: 'A',
23020            rankings: 1,
23021            unanimous_initial: true,
23022            deliberated: false,
23023            changed_votes: 0,
23024            unanimous_final: true,
23025            tie_break: None,
23026            judges: 0,
23027            present: 0,
23028            quorum: 0,
23029            met_quorum: true,
23030            uncontested: Some("only candidate A produced a change".to_owned()),
23031        });
23032        state.reviews = vec![ReviewRound {
23033            round: 1,
23034            head: "deadbeef".to_owned(),
23035            verified_head: None,
23036            verified_at: None,
23037            reviews: Vec::new(),
23038            e2e: Vec::new(),
23039            fix: None,
23040            blocking: 0,
23041            answered: 0,
23042            expected: 0,
23043            clean: true,
23044            verify_retried: false,
23045            e2e_deferred: false,
23046            e2e_defer_reason: None,
23047            progressed: false,
23048            vote_split: false,
23049            reconsideration: Vec::new(),
23050            verdict: None,
23051        }];
23052        state.gate = vec![CommandOutcome {
23053            command: "test".to_owned(),
23054            code: Some(0),
23055            output_tail: String::new(),
23056            duration_ms: 0,
23057            resource_blocked: false,
23058            ..Default::default()
23059        }];
23060        state.gate_ran = true;
23061        // A first pass through `merge` already pushed and opened this pull
23062        // request; `status` is `Landing` because a previous call into `land`
23063        // parked or was interrupted before it reached a terminal outcome.
23064        state.status = RunStatus::Landing;
23065        state.merge = Some(MergeOutcome {
23066            mode: MergeMode::Pr,
23067            ok: true,
23068            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23069            empty: false,
23070        });
23071
23072        // The Landing-resume shortcut calls `run_land` directly rather than
23073        // through `merge`, which is exactly the call site that used to skip
23074        // `settle_questions` - see the fixture below.
23075        ask_test_home();
23076        // A real resume loads a persisted run; driver ownership is checked
23077        // against that record before the Landing shortcut is entered.
23078        state.save().expect("save landing run");
23079        let store = ask::Questions::open();
23080        let q = ask_open_question(&store, &state.id);
23081
23082        let mut runner = Runner {
23083            state,
23084            roles: ResolvedRoles {
23085                implementers: Vec::new(),
23086                judges: Vec::new(),
23087                reviewers: Vec::new(),
23088                fixer: None,
23089                conductor: conductor(),
23090                implementer_roster: Vec::new(),
23091                judge_roster: Vec::new(),
23092                reviewer_roster: Vec::new(),
23093            },
23094            sem: Arc::new(Semaphore::new(1)),
23095            pause: Pause::new(),
23096            interrupt: Pause::new(),
23097        };
23098
23099        // `execute`, not `merge` directly: the Landing-resume shortcut lives
23100        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
23101        // exactly because `review_loop` would otherwise clobber the marker
23102        // first.
23103        runner.execute().await.expect("execute");
23104
23105        assert_eq!(
23106            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
23107            Some("https://example.invalid/x/y/pull/1"),
23108            "reentry must not push again or open a second pull request over the \
23109             one `land` is already watching"
23110        );
23111        assert_ne!(
23112            runner.state.status,
23113            RunStatus::Landing,
23114            "land could not actually reach the fake pull request, so it must \
23115             have given up rather than left the run silently parked forever"
23116        );
23117        // `land` could not reach the fake pull request, so it gave up into
23118        // `Blocked` - still resumable, so the question must not have been
23119        // swept just because this branch now also calls `settle_questions`.
23120        assert_eq!(runner.state.status, RunStatus::Blocked);
23121        assert!(
23122            store.get(&q.id).unwrap().status.open(),
23123            "Blocked is still alive; settle_questions must have been a no-op here"
23124        );
23125    }
23126
23127    fn state_with_round(round: ReviewRound) -> RunState {
23128        let mut s = RunState::new(
23129            PathBuf::from("/repo"),
23130            "main".to_owned(),
23131            "abc1234".to_owned(),
23132            "add retries".to_owned(),
23133            Config::default(),
23134        );
23135        s.reviews = vec![round];
23136        s
23137    }
23138
23139    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
23140        crate::verdict::Finding {
23141            id: id.to_owned(),
23142            severity,
23143            file: None,
23144            line: None,
23145            title: title.to_owned(),
23146            detail: String::new(),
23147        }
23148    }
23149
23150    #[test]
23151    fn pr_body_names_open_findings_and_declined_ones() {
23152        let round = ReviewRound {
23153            round: 2,
23154            head: "deadbee".to_owned(),
23155            verified_head: None,
23156            verified_at: None,
23157            reviews: vec![ReviewRecord {
23158                attempts: 0,
23159                reviewer: 1,
23160                agent: "alpha".to_owned(),
23161                summary: String::new(),
23162                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
23163                vote: None,
23164                failed: None,
23165                duration_ms: 0,
23166            }],
23167            e2e: vec![CommandOutcome {
23168                command: "cargo test".to_owned(),
23169                code: Some(0),
23170                output_tail: String::new(),
23171                duration_ms: 0,
23172                resource_blocked: false,
23173                ..Default::default()
23174            }],
23175            verify_retried: false,
23176            e2e_deferred: false,
23177            e2e_defer_reason: None,
23178            fix: Some(FixRecord {
23179                agent: "alpha".to_owned(),
23180                addressed: Vec::new(),
23181                rejected: vec![crate::verdict::Rejection {
23182                    id: "R1-1-1".to_owned(),
23183                    why: "not reachable from any caller".to_owned(),
23184                }],
23185                notes: String::new(),
23186                committed: true,
23187                failed: None,
23188                duration_ms: 0,
23189                continuation: None,
23190            }),
23191            blocking: 0,
23192            answered: 1,
23193            expected: 1,
23194            clean: false,
23195            progressed: true,
23196            vote_split: false,
23197            reconsideration: Vec::new(),
23198            verdict: None,
23199        };
23200        let state = state_with_round(round);
23201        let body = pr_message(&state, 'A').body;
23202
23203        assert!(body.contains("add retries"), "the task must still be there");
23204        assert!(body.contains("R2-1-1"), "{body}");
23205        assert!(!body.contains("unused import"), "{body}");
23206        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
23207        assert!(
23208            !body.contains("not reachable from any caller"),
23209            "the reason it was declined: {body}"
23210        );
23211    }
23212
23213    #[test]
23214    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
23215        let round = ReviewRound {
23216            round: 1,
23217            head: "deadbee".to_owned(),
23218            verified_head: None,
23219            verified_at: None,
23220            reviews: vec![ReviewRecord {
23221                attempts: 0,
23222                reviewer: 1,
23223                agent: "alpha".to_owned(),
23224                summary: String::new(),
23225                findings: Vec::new(),
23226                vote: None,
23227                failed: None,
23228                duration_ms: 0,
23229            }],
23230            e2e: Vec::new(),
23231            verify_retried: false,
23232            e2e_deferred: false,
23233            e2e_defer_reason: None,
23234            fix: None,
23235            blocking: 0,
23236            answered: 1,
23237            expected: 1,
23238            clean: true,
23239            progressed: false,
23240            vote_split: false,
23241            reconsideration: Vec::new(),
23242            verdict: None,
23243        };
23244        let state = state_with_round(round);
23245        let body = pr_message(&state, 'A').body;
23246        assert!(!body.contains("Open review findings"), "{body}");
23247        assert!(!body.contains("Declined"), "{body}");
23248    }
23249
23250    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
23251        let mut state = RunState::new(
23252            PathBuf::from("/repo"),
23253            "main".to_owned(),
23254            "abc1234".to_owned(),
23255            instruction.to_owned(),
23256            Config::default(),
23257        );
23258        // These fixtures test execution flow, independent of host disk capacity.
23259        state.config.disk.min_free_bytes = 0;
23260        state.candidates.push(Candidate {
23261            index: 0,
23262            label: 'A',
23263            agent: "alpha".to_owned(),
23264            branch: "magi/x/A".to_owned(),
23265            worktree: PathBuf::from("/wt"),
23266            summary: summary.to_owned(),
23267            stat: String::new(),
23268            files: 1,
23269            commits: 1,
23270            empty: false,
23271            failed: None,
23272            verified_noop: None,
23273            folded: false,
23274            duration_ms: 0,
23275        });
23276        state
23277    }
23278
23279    fn review_state(subjects: &[&str]) -> RunState {
23280        let mut state = state_with_summary(
23281            "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",
23282            "",
23283        );
23284        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23285        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
23286        state
23287    }
23288
23289    /// A branch rebased onto a main that moved past the recorded
23290    /// `base_commit` is titled from its own first commit, never main's.
23291    #[tokio::test]
23292    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
23293        ask_test_home();
23294        let tmp = tempfile::tempdir().unwrap();
23295        let repo = tmp.path().join("repo");
23296        std::fs::create_dir_all(&repo).unwrap();
23297        init_repo(&repo);
23298        let origin = tmp.path().join("origin.git");
23299        let g = |dir: &Path, args: &[&str]| {
23300            let out = std::process::Command::new("git")
23301                .args(args)
23302                .current_dir(dir)
23303                .quiet()
23304                .output()
23305                .expect("spawn git");
23306            assert!(
23307                out.status.success(),
23308                "git {args:?}: {}",
23309                String::from_utf8_lossy(&out.stderr)
23310            );
23311        };
23312        g(
23313            tmp.path(),
23314            &[
23315                "clone",
23316                "--bare",
23317                "-q",
23318                repo.to_str().unwrap(),
23319                origin.to_str().unwrap(),
23320            ],
23321        );
23322        g(
23323            &repo,
23324            &["remote", "add", "origin", origin.to_str().unwrap()],
23325        );
23326        let c1 = git::rev_parse(&repo, "main").await.unwrap();
23327
23328        // Main moves on; the branch is built on top of the new main.
23329        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
23330        g(&repo, &["add", "-A"]);
23331        g(
23332            &repo,
23333            &["commit", "-q", "-m", "chore(deps): update a crate"],
23334        );
23335        g(&repo, &["push", "-q", "origin", "main"]);
23336        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
23337        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23338        g(&repo, &["add", "-A"]);
23339        g(
23340            &repo,
23341            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
23342        );
23343        g(&repo, &["checkout", "-q", "main"]);
23344
23345        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
23346        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
23347        // Without a readable tracking ref the recorded base's merge base is used.
23348        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
23349        assert_eq!(fallback, c1);
23350
23351        let mut state = review_state(&[
23352            "chore(deps): update a crate",
23353            "fix(daemon): apply a chosen action",
23354        ]);
23355        state.repo = repo.clone();
23356        state.base_branch = "main".to_owned();
23357        state.base_commit = c1;
23358        refresh_reviewed_commits(&mut state, "feat/own").await;
23359        assert_eq!(
23360            state.reviewed_commits,
23361            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
23362        );
23363        assert_eq!(
23364            review_title(&state).as_deref(),
23365            Some("fix(daemon): apply a chosen action")
23366        );
23367        assert_eq!(
23368            leaked_subjects(&state, "feat/own").await,
23369            Some(vec!["chore(deps): update a crate".to_owned()])
23370        );
23371        // A stale tracking ref is still used when the fetch fails, but the
23372        // leak list is withheld.
23373        state.config.merge.remote = "nowhere".to_owned();
23374        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
23375    }
23376
23377    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
23378    /// with `origin/main` one commit behind it, and a summarizing agent that
23379    /// prints whatever `reply` holds.
23380    struct SummaryFixture {
23381        _tmp: tempfile::TempDir,
23382        repo: PathBuf,
23383        reply: PathBuf,
23384        runner: Runner,
23385    }
23386
23387    fn summary_fixture() -> SummaryFixture {
23388        ask_test_home();
23389        let tmp = tempfile::tempdir().unwrap();
23390        let repo = tmp.path().join("repo");
23391        std::fs::create_dir_all(&repo).unwrap();
23392        init_repo(&repo);
23393        let origin = tmp.path().join("origin.git");
23394        let g = |args: &[&str]| {
23395            let out = std::process::Command::new("git")
23396                .args(args)
23397                .current_dir(&repo)
23398                .quiet()
23399                .output()
23400                .expect("spawn git");
23401            assert!(
23402                out.status.success(),
23403                "git {args:?}: {}",
23404                String::from_utf8_lossy(&out.stderr)
23405            );
23406        };
23407        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
23408        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
23409        g(&["push", "-q", "origin", "main"]);
23410        g(&["checkout", "-q", "-b", "feat/own"]);
23411        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23412        g(&["add", "-A"]);
23413        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
23414        let reply = tmp.path().join("reply.txt");
23415        std::fs::write(
23416            &reply,
23417            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
23418        )
23419        .unwrap();
23420        let mut runner = runner_at(RunStatus::Gating);
23421        let mut state = review_state(&["feat(own): add the own file"]);
23422        state.repo = repo.clone();
23423        state.base_branch = "main".to_owned();
23424        state.candidates[0].branch = "feat/own".to_owned();
23425        state.candidates[0].worktree = repo.clone();
23426        let mut author = spec("alpha");
23427        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
23428        author
23429            .env
23430            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
23431        state.config.agents = vec![author];
23432        runner.state = state;
23433        SummaryFixture {
23434            _tmp: tmp,
23435            repo,
23436            reply,
23437            runner,
23438        }
23439    }
23440
23441    async fn posted(f: &mut SummaryFixture) -> PrMessage {
23442        let winner = f.runner.state.candidates[0].clone();
23443        f.runner
23444            .guarded_pr_message(&winner, None, true)
23445            .await
23446            .unwrap()
23447            .expect("an English description never parks")
23448    }
23449
23450    fn clean_round_with_minor_findings() -> ReviewRound {
23451        let mut round = passing_round(2, None);
23452        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
23453        round.reviews = vec![ReviewRecord {
23454            attempts: 0,
23455            reviewer: 1,
23456            agent: "alpha".into(),
23457            summary: "内部レビュー".into(),
23458            findings: vec![
23459                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
23460                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
23461            ],
23462            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
23463            failed: None,
23464            duration_ms: 0,
23465        }];
23466        round
23467    }
23468
23469    #[tokio::test]
23470    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
23471        for review_only in [false, true] {
23472            let mut f = summary_fixture();
23473            if !review_only {
23474                f.runner.state.candidates[0].agent = "alpha".into();
23475            }
23476            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
23477            assert!(f.runner.state.reviews[0].clean);
23478            assert!(f.runner.state.reviews[0].fix.is_none());
23479            assert!(f.runner.state.open_findings().is_empty());
23480            assert_eq!(
23481                crate::pr_outcome::required_finding_ids(&f.runner.state),
23482                ["R2-1-1", "R2-1-2"]
23483            );
23484            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23485            let evidence = crate::pr_outcome::summary_evidence(
23486                &f.runner.state,
23487                crate::pr_outcome::FinalHead::At(&head),
23488            );
23489            assert!(
23490                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
23491            );
23492            // The ordinary reply omits both IDs: no cached description is adopted.
23493            let omitted = posted(&mut f).await;
23494            assert!(omitted.body.contains("No description"));
23495            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
23496            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
23497            assert!(f.runner.state.change_summary.is_none());
23498            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();
23499            let described = posted(&mut f).await;
23500            assert!(described.body.contains("improve documentation for callers"));
23501            assert!(described.body.contains("remaining edge case"));
23502            assert!(described.body.contains("## Open review findings"));
23503            assert!(!described.body.contains("未修正"));
23504        }
23505    }
23506
23507    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
23508        let mut f = summary_fixture();
23509        if !review_only {
23510            f.runner.state.candidates[0].agent = "alpha".into();
23511        }
23512        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23513        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
23514        fixed
23515            .fix
23516            .as_mut()
23517            .unwrap()
23518            .rejected
23519            .push(crate::verdict::Rejection {
23520                id: "R1-1-1".into(),
23521                why: "呼び出されないコードのため辞退".into(),
23522            });
23523        let mut clean = clean_round_with_minor_findings();
23524        clean.verified_head = Some(head.clone());
23525        f.runner.state.reviews = vec![fixed, clean];
23526        ok_gate(&mut f.runner.state, Some(&head));
23527        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
23528        f.runner.state.config.agents.push(scripted("beta", reply));
23529        f.runner.state.config.roles.language_judge =
23530            Some(crate::config::AgentChoice::One("beta".into()));
23531        f
23532    }
23533
23534    #[tokio::test]
23535    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
23536        for review_only in [false, true] {
23537            let mut f = rewrite_fixture_with_findings(review_only,
23538                "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;
23539            let m = posted(&mut f).await;
23540            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23541            let expected =
23542                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
23543            assert!(m.body.contains(&expected));
23544            assert!(m.body.contains("## Review rounds"));
23545            assert!(
23546                m.body
23547                    .contains("Gate (`verify.gate`): passed on the final commit")
23548            );
23549            assert!(
23550                m.body
23551                    .contains("Tests (`verify.e2e`): passed on the final commit")
23552            );
23553            let c = f.runner.state.change_summary.as_ref().unwrap();
23554            assert!(
23555                m.body
23556                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
23557            );
23558            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23559            assert!(crate::pr_outcome::covers_required_findings(
23560                &f.runner.state,
23561                &m.body
23562            ));
23563            assert!(m.body.contains("documentation remains incomplete"));
23564            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23565            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23566            assert!(f.runner.state.github_text.is_none());
23567        }
23568    }
23569
23570    #[tokio::test]
23571    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23572        for review_only in [false, true] {
23573            for reply in [
23574                "TITLE: fix: public description\nA short English description.",
23575                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23576            ] {
23577                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23578                let winner = f.runner.state.candidates[0].clone();
23579                let posted = f
23580                    .runner
23581                    .guarded_pr_message(&winner, None, true)
23582                    .await
23583                    .unwrap();
23584                assert!(posted.is_none());
23585                assert!(f.runner.state.parked);
23586                let withheld = f.runner.state.github_text.as_ref().unwrap();
23587                assert!(
23588                    withheld.rewrite.is_none(),
23589                    "an incomplete rewrite must not be selectable"
23590                );
23591                let q = ask::Questions::open()
23592                    .get(withheld.question.as_ref().unwrap())
23593                    .unwrap();
23594                assert!(
23595                    !q.choices
23596                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23597                );
23598                assert!(
23599                    q.detail.contains("R1-1-1")
23600                        && q.detail.contains("R2-1-1")
23601                        && q.detail.contains("R2-1-2")
23602                );
23603            }
23604        }
23605    }
23606
23607    #[tokio::test]
23608    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23609        for review_only in [false, true] {
23610            let mut f = summary_fixture();
23611            if !review_only {
23612                f.runner.state.candidates[0].agent = "alpha".into();
23613            }
23614            f.runner.state.instruction = "内部タスクの説明".into();
23615            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23616            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23617            f.runner.state.reviews = vec![
23618                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23619                round_with_notes(2, Some("二回目の内部修正報告です。")),
23620                passing_round(3, Some(&head)),
23621            ];
23622            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23623            ok_gate(&mut f.runner.state, Some(&head));
23624            let captured = f.repo.join("public-prompt.txt");
23625            let author = &mut f.runner.state.config.agents[0];
23626            author.command = vec![
23627                "sh".into(),
23628                "-c".into(),
23629                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23630            ];
23631            author.env.insert(
23632                "PROMPT_FILE".into(),
23633                captured.to_string_lossy().into_owned(),
23634            );
23635            let m = posted(&mut f).await;
23636            assert!(m.body.contains("Adds `own.txt`"));
23637            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23638            assert!(m.body.contains("R1-1-1"));
23639            assert!(
23640                m.body
23641                    .contains("Gate (`verify.gate`): passed on the final commit")
23642            );
23643            assert!(
23644                m.body
23645                    .contains("Tests (`verify.e2e`): passed on the final commit")
23646            );
23647            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23648            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23649            let prompt = std::fs::read_to_string(captured).unwrap();
23650            assert!(prompt.contains(&format!(
23651                "git diff {} {head}",
23652                f.runner.state.change_summary.as_ref().unwrap().base
23653            )));
23654            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23655            assert_eq!(
23656                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23657                "二回目の内部修正報告です。"
23658            );
23659        }
23660    }
23661
23662    #[tokio::test]
23663    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23664        for review_only in [false, true] {
23665            let mut f = summary_fixture();
23666            if !review_only {
23667                f.runner.state.candidates[0].agent = "alpha".into();
23668            }
23669            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23670            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23671            std::fs::write(&f.reply, "no usable description").unwrap();
23672            let failed = posted(&mut f).await;
23673            assert!(
23674                failed
23675                    .body
23676                    .contains("No description of what this change does could be generated")
23677            );
23678            assert!(failed.body.is_ascii());
23679            assert!(f.runner.state.github_text.is_none());
23680            assert!(f.runner.state.change_summary.is_none());
23681            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23682            let evidence = crate::pr_outcome::summary_evidence(
23683                &f.runner.state,
23684                crate::pr_outcome::FinalHead::At(&head),
23685            );
23686            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23687            assert!(
23688                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23689                    .exists()
23690            );
23691            f.runner.state =
23692                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23693            std::fs::write(
23694                &f.reply,
23695                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23696            )
23697            .unwrap();
23698            let retried = posted(&mut f).await;
23699            assert!(retried.body.contains("Adds the committed own file."));
23700            assert_eq!(
23701                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23702                "日本語の修正報告"
23703            );
23704        }
23705    }
23706
23707    #[tokio::test]
23708    async fn same_head_verification_and_findings_invalidate_public_prose() {
23709        let mut f = summary_fixture();
23710        posted(&mut f).await;
23711        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23712        let original = f
23713            .runner
23714            .state
23715            .change_summary
23716            .as_ref()
23717            .unwrap()
23718            .evidence
23719            .clone();
23720        ok_gate(&mut f.runner.state, Some(&head));
23721        std::fs::write(
23722            &f.reply,
23723            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23724        )
23725        .unwrap();
23726        let verified = posted(&mut f).await;
23727        assert!(verified.body.contains("now verified"));
23728        assert_ne!(
23729            f.runner.state.change_summary.as_ref().unwrap().evidence,
23730            original
23731        );
23732        let mut round = round_with_notes(1, Some("内部報告"));
23733        round.reviews.push(ReviewRecord {
23734            attempts: 0,
23735            reviewer: 1,
23736            agent: "alpha".into(),
23737            summary: "内部レビュー".into(),
23738            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23739            vote: None,
23740            failed: None,
23741            duration_ms: 0,
23742        });
23743        round
23744            .fix
23745            .as_mut()
23746            .unwrap()
23747            .rejected
23748            .push(crate::verdict::Rejection {
23749                id: "R1-1-1".into(),
23750                why: "呼び出し元から到達できない".into(),
23751            });
23752        f.runner.state.reviews = vec![round];
23753        // A description omitting the required ID is unusable, even with a title.
23754        let omitted = posted(&mut f).await;
23755        assert!(omitted.body.contains("No description"));
23756        assert!(omitted.body.contains("R1-1-1"));
23757        assert!(!omitted.body.contains("到達"));
23758        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();
23759        let described = posted(&mut f).await;
23760        assert!(described.body.contains("unreachable from callers"));
23761        assert!(described.body.contains("R1-1-1"));
23762        assert!(!described.body.contains("到達"));
23763        let evidence = f
23764            .runner
23765            .state
23766            .change_summary
23767            .as_ref()
23768            .unwrap()
23769            .evidence
23770            .clone();
23771        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23772        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23773        assert!(posted(&mut f).await.body.contains("rationale updated"));
23774        assert_ne!(
23775            f.runner.state.change_summary.as_ref().unwrap().evidence,
23776            evidence
23777        );
23778        // Old serialized summaries have no evidence fingerprint and must regenerate.
23779        f.runner
23780            .state
23781            .change_summary
23782            .as_mut()
23783            .unwrap()
23784            .evidence
23785            .clear();
23786        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23787        assert!(posted(&mut f).await.body.contains("current specification"));
23788    }
23789
23790    #[tokio::test]
23791    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23792        let mut f = summary_fixture();
23793        let m = posted(&mut f).await;
23794        assert_eq!(m.title, "feat(own): add the own file");
23795        assert!(
23796            m.body
23797                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23798            "{}",
23799            m.body
23800        );
23801        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23802        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23803        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23804        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23805        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23806        let kept = f.runner.state.change_summary.as_ref().unwrap();
23807        assert_eq!(
23808            (kept.head.as_str(), kept.base.as_str()),
23809            (head.as_str(), base.as_str())
23810        );
23811        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23812    }
23813
23814    #[tokio::test]
23815    async fn review_only_summary_receives_the_configured_github_language() {
23816        let mut f = summary_fixture();
23817        f.runner.state.config.graph.github_language = "ja".into();
23818        let captured = f.repo.join("summary-prompt.txt");
23819        let author = &mut f.runner.state.config.agents[0];
23820        author.command = vec![
23821            "sh".into(),
23822            "-c".into(),
23823            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23824        ];
23825        author.env.insert(
23826            "PROMPT_FILE".into(),
23827            captured.to_string_lossy().into_owned(),
23828        );
23829        std::fs::write(
23830            &f.reply,
23831            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23832        )
23833        .unwrap();
23834        let m = posted(&mut f).await;
23835        let prompt = std::fs::read_to_string(captured).unwrap();
23836        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23837        assert!(!prompt.contains("in English"));
23838        assert_eq!(m.title, "feat(own): ファイルを追加");
23839        assert!(m.body.contains("own.txt を追加します。"));
23840    }
23841
23842    #[tokio::test]
23843    async fn review_fixes_come_after_the_whole_change_summary() {
23844        let mut f = summary_fixture();
23845        f.runner.state.reviews = vec![
23846            round_with_notes(1, Some("handled the PATH case")),
23847            round_with_notes(2, None),
23848        ];
23849        let m = posted(&mut f).await;
23850        let summary = m.body.find("## Summary").expect("summary");
23851        let fixes = m.body.find("## Review rounds").expect("review rounds");
23852        assert!(summary < fixes, "{}", m.body);
23853        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23854        assert!(m.body.contains("## Final verification"), "{}", m.body);
23855    }
23856
23857    #[tokio::test]
23858    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23859        let mut f = summary_fixture();
23860        let first = posted(&mut f).await;
23861        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23862        // The same head reuses the record: a different reply is not read.
23863        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23864        let again = posted(&mut f).await;
23865        assert_eq!((again.title, again.body), (first.title, first.body));
23866
23867        let g = |args: &[&str]| {
23868            let out = std::process::Command::new("git")
23869                .args(args)
23870                .current_dir(&f.repo)
23871                .quiet()
23872                .output()
23873                .expect("spawn git");
23874            assert!(out.status.success(), "git {args:?}");
23875        };
23876        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23877        g(&["add", "-A"]);
23878        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23879        let second = posted(&mut f).await;
23880        let kept = f.runner.state.change_summary.clone().unwrap();
23881        assert_ne!(kept.head, first_head);
23882        assert!(second.body.contains("Not read yet."), "{}", second.body);
23883        assert!(!second.body.contains("so the first summary is read"));
23884        assert_eq!(second.title, "feat(own): other");
23885    }
23886
23887    #[tokio::test]
23888    async fn an_unavailable_summary_is_stated_and_never_invented() {
23889        let mut f = summary_fixture();
23890        std::fs::write(&f.reply, "no title line here").unwrap();
23891        let m = posted(&mut f).await;
23892        assert!(
23893            m.body
23894                .contains("No description of what this change does could be generated"),
23895            "{}",
23896            m.body
23897        );
23898        assert!(m.body.contains("internal reports remain in local records"));
23899        assert!(f.runner.state.change_summary.is_none());
23900        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23901        // A preview asks nobody and claims nothing.
23902        let winner = f.runner.state.candidates[0].clone();
23903        let preview = f
23904            .runner
23905            .guarded_pr_message(&winner, None, false)
23906            .await
23907            .unwrap()
23908            .unwrap();
23909        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23910    }
23911
23912    #[test]
23913    fn pr_message_review_single_commit_uses_its_subject() {
23914        let state = review_state(&["feat(nats): per-role user"]);
23915        let m = pr_message(&state, 'A');
23916        assert_eq!(m.title, "feat(nats): per-role user");
23917        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23918        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23919    }
23920
23921    #[test]
23922    fn pr_message_review_multi_commit_takes_the_oldest() {
23923        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23924        let m = pr_message(&state, 'A');
23925        assert_eq!(m.title, "feat: the change");
23926        for s in ["feat: the change", "fix: typo", "fix: again"] {
23927            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23928        }
23929    }
23930
23931    #[test]
23932    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23933        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23934            let mut state = review_state(&[first, "fix: later fixup"]);
23935            state.candidates[0].branch = "機能/ログイン".to_owned();
23936            let m = pr_message(&state, 'A');
23937            assert!(
23938                m.title.starts_with("chore: land candidate A of run"),
23939                "{}",
23940                m.title
23941            );
23942        }
23943    }
23944
23945    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23946        BranchFacts {
23947            commits: commits
23948                .iter()
23949                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23950                .collect(),
23951            stat: stat.to_owned(),
23952        }
23953    }
23954
23955    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23956        let mut r = review_round(true, 0, 1, 1, true, true);
23957        r.round = round;
23958        r.fix = notes.map(|n| FixRecord {
23959            agent: "fixer".to_owned(),
23960            addressed: Vec::new(),
23961            rejected: Vec::new(),
23962            notes: n.to_owned(),
23963            committed: true,
23964            failed: None,
23965            duration_ms: 0,
23966            continuation: None,
23967        });
23968        r
23969    }
23970
23971    #[test]
23972    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23973        let state = review_state(&["ignored"]);
23974        let f = facts(
23975            &[
23976                (
23977                    "fix(login): resolve PATH on macOS",
23978                    "Login shells skip rc files.",
23979                ),
23980                ("fix: address review", ""),
23981            ],
23982            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23983        );
23984        let m = pr_message_with(&state, 'A', Some(&f));
23985        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23986        assert!(
23987            m.body
23988                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23989            "{}",
23990            m.body
23991        );
23992        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23993        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23994        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23995        for banned in [
23996            "Review the work already",
23997            "no task statement",
23998            "Original task",
23999        ] {
24000            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24001        }
24002        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24003    }
24004
24005    #[test]
24006    fn pr_message_review_truncates_a_huge_first_commit_body() {
24007        let state = review_state(&["ignored"]);
24008        let f = facts(
24009            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24010            "s",
24011        );
24012        let m = pr_message_with(&state, 'A', Some(&f));
24013        assert!(m.body.len() < 30_000, "{}", m.body.len());
24014        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24015        assert!(
24016            m.body.contains("- ... 1 more commit(s)"),
24017            "{}",
24018            m.body.len()
24019        );
24020        assert!(m.body.ends_with("magi:candidate-a\n"));
24021    }
24022
24023    #[test]
24024    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24025        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24026        assert_eq!(m.title, "feat: x");
24027        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24028        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24029        assert!(!m.body.contains("no task statement"), "{}", m.body);
24030    }
24031
24032    #[test]
24033    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24034        let mut state = review_state(&["日本語の件名"]);
24035        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24036        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24037        state.candidates[0].branch = "機能/ログイン".to_owned();
24038        assert!(
24039            pr_message(&state, 'A')
24040                .title
24041                .starts_with("chore: land candidate A")
24042        );
24043    }
24044
24045    #[test]
24046    fn pr_message_review_fixes_survive_a_clean_final_round() {
24047        let mut state = review_state(&["feat: x"]);
24048        state.reviews = vec![
24049            round_with_notes(1, Some("handled the PATH case")),
24050            round_with_notes(2, None),
24051        ];
24052        let body = pr_message(&state, 'A').body;
24053        assert!(
24054            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24055            "{body}"
24056        );
24057        assert!(body.contains("### Round 1"), "{body}");
24058
24059        state.reviews = vec![
24060            round_with_notes(1, Some("first fix")),
24061            round_with_notes(2, Some("")),
24062            round_with_notes(3, Some("second fix")),
24063            round_with_notes(4, None),
24064        ];
24065        let body = pr_message(&state, 'A').body;
24066        assert!(
24067            body.contains("### Round 1") && !body.contains("first fix"),
24068            "{body}"
24069        );
24070        assert!(
24071            body.contains("### Round 3") && !body.contains("second fix"),
24072            "{body}"
24073        );
24074        assert!(body.contains("### Round 2"), "{body}");
24075    }
24076
24077    const FINAL: &str = "abcdef1234567890";
24078
24079    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
24080        let mut r = round_with_notes(round, None);
24081        r.verified_head = verified.map(str::to_owned);
24082        r
24083    }
24084
24085    fn ok_gate(state: &mut RunState, head: Option<&str>) {
24086        state.gate = vec![CommandOutcome {
24087            command: "gate".to_owned(),
24088            code: Some(0),
24089            output_tail: String::new(),
24090            duration_ms: 0,
24091            resource_blocked: false,
24092            ..Default::default()
24093        }];
24094        state.gate_ran = true;
24095        state.gate_head = head.map(str::to_owned);
24096    }
24097
24098    fn body_at(state: &RunState) -> String {
24099        pr_message_raw(
24100            state,
24101            'A',
24102            None,
24103            crate::pr_outcome::FinalHead::At(FINAL),
24104            ChangeNote::NotAsked,
24105        )
24106        .body
24107    }
24108
24109    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
24110
24111    #[test]
24112    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
24113        let mut state = review_state(&["feat: x"]);
24114        state.reviews = vec![
24115            round_with_notes(1, Some(SANDBOXED)),
24116            passing_round(2, Some(FINAL)),
24117        ];
24118        ok_gate(&mut state, Some(FINAL));
24119        let body = body_at(&state);
24120        assert!(!body.contains("Handled the PATH case."), "{body}");
24121        assert!(!body.contains("could not commit"), "{body}");
24122        assert!(!body.contains("could not run"), "{body}");
24123        assert!(
24124            body.contains("The fix is committed on the branch"),
24125            "{body}"
24126        );
24127        assert!(!body.contains("sandbox"), "{body}");
24128        assert!(
24129            body.contains("Tests (`verify.e2e`): passed on the final commit"),
24130            "{body}"
24131        );
24132        assert!(
24133            body.contains("Gate (`verify.gate`): passed on the final commit"),
24134            "{body}"
24135        );
24136        // The raw report is untouched in the record.
24137        assert!(
24138            state.reviews[0]
24139                .fix
24140                .as_ref()
24141                .unwrap()
24142                .notes
24143                .contains("could not commit")
24144        );
24145    }
24146
24147    #[test]
24148    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
24149        let mut state = review_state(&["feat: x"]);
24150        let mut r1 = round_with_notes(1, Some(SANDBOXED));
24151        r1.fix.as_mut().unwrap().committed = false;
24152        let mut r2 = passing_round(2, Some(FINAL));
24153        r2.e2e[0].code = Some(1);
24154        state.reviews = vec![r1, r2];
24155        let body = body_at(&state);
24156        assert!(!body.contains("could not commit"), "{body}");
24157        assert!(!body.contains("could not run"), "{body}");
24158        assert!(body.contains("This round produced no commit"), "{body}");
24159        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
24160        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
24161        assert!(!body.contains("passed"), "{body}");
24162    }
24163
24164    #[test]
24165    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
24166        let mut state = review_state(&["feat: x"]);
24167        state.reviews = vec![
24168            round_with_notes(1, Some(SANDBOXED)),
24169            passing_round(2, Some("0123456789abcdef")),
24170        ];
24171        ok_gate(&mut state, Some("0123456789abcdef"));
24172        let body = body_at(&state);
24173        assert!(!body.contains("HTTP tests could not run"), "{body}");
24174        // The commit claim is still settled by the structured record.
24175        assert!(!body.contains("could not commit"), "{body}");
24176        assert!(
24177            body.contains("passed on an earlier commit (`0123456`)"),
24178            "{body}"
24179        );
24180        assert!(!body.contains("passed on the final commit"), "{body}");
24181
24182        // A gate recorded before `gate_head` existed is "not recorded".
24183        ok_gate(&mut state, None);
24184        let body = body_at(&state);
24185        assert!(
24186            body.contains("passed on a commit that was not recorded"),
24187            "{body}"
24188        );
24189    }
24190
24191    #[test]
24192    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
24193        let state = state_with_summary(
24194            "add retries to the client",
24195            "TITLE: feat: retries\n\nDid it.",
24196        );
24197        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
24198        assert_eq!(m.title, "feat: retries");
24199        assert!(
24200            m.body.contains("<summary>Original task</summary>"),
24201            "{}",
24202            m.body
24203        );
24204        assert!(!m.body.contains("Commits under review"), "{}", m.body);
24205        assert!(
24206            m.body
24207                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
24208            "{}",
24209            m.body
24210        );
24211    }
24212
24213    #[test]
24214    fn pr_message_review_bounds_a_long_english_subject() {
24215        let long = format!("feat: {}", "word ".repeat(100));
24216        let m = pr_message(&review_state(&[&long]), 'A');
24217        assert!(m.title.starts_with("feat: word"), "{}", m.title);
24218        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24219    }
24220
24221    #[test]
24222    fn pr_message_implementation_run_is_unchanged_by_review_support() {
24223        let state = state_with_summary("add retries\n\ndetails", "- did some things");
24224        let m = pr_message(&state, 'A');
24225        assert_eq!(m.title, "add retries");
24226        assert!(m.body.contains("<summary>Original task</summary>"));
24227        assert!(!m.body.contains("Commits under review"));
24228        assert_eq!(landing_subject_source(&state), state.instruction);
24229    }
24230
24231    #[test]
24232    fn review_run_squash_subject_is_the_change_not_the_prompt() {
24233        let state = review_state(&["feat: the change", "fix: typo"]);
24234        let source = landing_subject_source(&state);
24235        assert_eq!(land::merge_subject("", &source), "feat: the change");
24236        assert_eq!(
24237            land::merge_subject("magi: candidate A (uncommitted work)", &source),
24238            "feat: the change"
24239        );
24240        // An operator's rename still wins.
24241        assert_eq!(
24242            land::merge_subject("feat: renamed by hand", &source),
24243            "feat: renamed by hand"
24244        );
24245        let blank = review_state(&["日本語"]);
24246        assert!(
24247            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
24248        );
24249    }
24250
24251    #[test]
24252    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
24253        let state = review_state(&["feat: the change"]);
24254        let source = landing_subject_source(&state);
24255        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
24256        assert_eq!(
24257            land::merge_subject(landing_title(&state, old), &source),
24258            "feat: the change"
24259        );
24260        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
24261        let task = state_with_summary("add retries", "");
24262        assert_eq!(landing_title(&task, old), old);
24263    }
24264
24265    #[test]
24266    fn pr_message_describes_the_change_not_the_task() {
24267        let state = state_with_summary(
24268            "今回やってほしいこと: results projector を直す",
24269            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
24270        );
24271        let m = pr_message(&state, 'A');
24272        assert_eq!(m.title, "fix(web): batch the runs list reads");
24273        assert!(
24274            m.body.starts_with("## Summary\n\n- reads run.json once"),
24275            "{}",
24276            m.body
24277        );
24278        assert!(!m.body.contains("TITLE:"), "{}", m.body);
24279        let task_at = m.body.find("今回やってほしいこと").unwrap();
24280        let details_at = m.body.find("<details>").unwrap();
24281        assert!(
24282            details_at < task_at,
24283            "the task lives inside <details>: {}",
24284            m.body
24285        );
24286        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
24287        assert!(m.body.contains("magi:candidate-a"));
24288    }
24289
24290    #[test]
24291    fn pr_message_falls_back_to_the_task_without_a_title_line() {
24292        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
24293        let m = pr_message(&state, 'A');
24294        assert_eq!(m.title, "add retries");
24295        assert!(
24296            m.body.contains("## Summary\n\n- did some things"),
24297            "{}",
24298            m.body
24299        );
24300
24301        let none = RunState::new(
24302            PathBuf::from("/repo"),
24303            "main".to_owned(),
24304            "abc1234".to_owned(),
24305            "add retries".to_owned(),
24306            Config::default(),
24307        );
24308        let m = pr_message(&none, 'A');
24309        assert_eq!(m.title, "add retries");
24310        assert!(!m.body.contains("## Summary"), "{}", m.body);
24311    }
24312
24313    #[test]
24314    fn pr_message_refuses_the_candidate_commit_subject() {
24315        for bad in [
24316            "TITLE: magi: candidate A (uncommitted work)",
24317            "TITLE: chore: stuff (uncommitted work)",
24318            "TITLE:   ",
24319        ] {
24320            let state = state_with_summary("add retries", bad);
24321            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
24322        }
24323    }
24324
24325    #[test]
24326    fn pr_message_bounds_a_very_long_task_and_title() {
24327        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
24328        let state = state_with_summary(&long, "- nothing");
24329        let m = pr_message(&state, 'A');
24330        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24331        assert!(!m.title.contains('\n'));
24332
24333        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
24334        let m = pr_message(&state, 'A');
24335        assert!(m.title.starts_with("feat: "));
24336        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24337        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
24338    }
24339
24340    fn long_title_of(instruction: &str) -> String {
24341        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
24342    }
24343
24344    #[test]
24345    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
24346        let first = "Make the landing path keep a readable title for long tasks";
24347        let line = format!(
24348            "{first}. {}",
24349            "And then keep going with more words ".repeat(20)
24350        );
24351        let t = long_title_of(&line);
24352        assert_eq!(t, first);
24353        assert!(!t.starts_with("chore: land"));
24354    }
24355
24356    #[test]
24357    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
24358        let line = "word ".repeat(200);
24359        let t = long_title_of(&line);
24360        assert!(t.ends_with("word..."), "{t}");
24361        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
24362    }
24363
24364    #[test]
24365    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
24366        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
24367            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
24368        }
24369    }
24370
24371    #[test]
24372    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
24373        let mut state = state_with_summary("再試行を追加する", "- nothing");
24374        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
24375        state.config.graph.github_language = "ja".into();
24376        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
24377    }
24378
24379    #[test]
24380    fn pr_message_title_limit_is_exact() {
24381        let at = "a".repeat(PR_TITLE_MAX);
24382        assert_eq!(long_title_of(&at), at);
24383        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
24384        assert!(over.ends_with("..."), "{over}");
24385        assert_eq!(over.chars().count(), PR_TITLE_MAX);
24386    }
24387
24388    #[test]
24389    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
24390        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
24391        let t = long_title_of(&line);
24392        assert!(t.ends_with("..."), "{t}");
24393        assert!(t.is_ascii(), "{t}");
24394    }
24395
24396    #[test]
24397    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
24398        let line = format!(
24399            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
24400            "plus more filler words ".repeat(20)
24401        );
24402        let t = long_title_of(&line);
24403        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
24404    }
24405
24406    #[test]
24407    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
24408        let line = format!("\n\n# {}", "title words ".repeat(40));
24409        let state = state_with_summary(&line, "- nothing");
24410        let m = pr_message(&state, 'A');
24411        assert!(m.title.starts_with("title words"), "{}", m.title);
24412        assert_eq!(
24413            land::merge_subject(&m.title, &landing_subject_source(&state)),
24414            m.title
24415        );
24416        // An operator's rename wins untouched.
24417        assert_eq!(
24418            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
24419            "feat: renamed by hand"
24420        );
24421    }
24422
24423    #[tokio::test]
24424    async fn github_text_rewrite_is_bounded_and_falls_back() {
24425        crate::run::pin_test_home();
24426        for (reply, accepted) in [
24427            (
24428                "TITLE: fix: retries\nAdd retries for failed requests.",
24429                true,
24430            ),
24431            (
24432                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
24433                false,
24434            ),
24435            (
24436                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
24437                true,
24438            ),
24439            (
24440                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
24441                true,
24442            ),
24443            (
24444                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
24445                true,
24446            ),
24447            (
24448                "TITLE: fix: retries\n日本語の説明です。 token=secret",
24449                false,
24450            ),
24451            ("TITLE: fix: retries\n", false),
24452        ] {
24453            let dir = tempfile::tempdir().unwrap();
24454            let mut runner = runner_at(RunStatus::Gating);
24455            runner.state = state_with_summary(
24456                "add retries",
24457                "TITLE: fix: retries\n日本語の説明を書きます。",
24458            );
24459            runner.state.repo = dir.path().to_owned();
24460            runner.state.candidates[0].worktree = dir.path().to_owned();
24461            let mut author = spec("alpha");
24462            author.command = vec![
24463                "sh".into(),
24464                "-c".into(),
24465                "printf '%s' \"$REWRITE_REPLY\"".into(),
24466            ];
24467            author.env.insert("REWRITE_REPLY".into(), reply.into());
24468            runner.state.config.agents = vec![author];
24469            seed_public_summary(&mut runner);
24470            let winner = runner.state.candidates[0].clone();
24471            let first = runner
24472                .guarded_pr_message(&winner, None, true)
24473                .await
24474                .unwrap();
24475            let message = if accepted {
24476                first.expect("a passing rewrite never asks")
24477            } else {
24478                // Withheld: the run parks on a question and posts nothing yet.
24479                assert!(first.is_none());
24480                assert!(runner.state.parked);
24481                let store = ask::Questions::open();
24482                let asked: Vec<_> = store
24483                    .list()
24484                    .into_iter()
24485                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24486                    .collect();
24487                assert_eq!(asked.len(), 1);
24488                assert!(!asked[0].detail.contains("secret"));
24489                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
24490                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
24491                assert_eq!(
24492                    asked[0]
24493                        .choices
24494                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
24495                    rewrite.is_some()
24496                );
24497                // Silence: the question lapses and the neutral text is used,
24498                // without a second rewrite call or a second question.
24499                store
24500                    .update(&asked[0].id, |q| {
24501                        q.abandon("test");
24502                        Ok(())
24503                    })
24504                    .unwrap();
24505                let again = runner
24506                    .guarded_pr_message(&winner, None, true)
24507                    .await
24508                    .unwrap()
24509                    .expect("an abandoned question falls back");
24510                let n = store
24511                    .list()
24512                    .into_iter()
24513                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24514                    .count();
24515                assert_eq!(n, 1, "asked once per rejected text");
24516                again
24517            };
24518            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
24519            assert!(!message.body.contains("secret"));
24520            assert!(!message.body.contains("prefix"));
24521            assert!(!message.title.contains("secret"));
24522            assert_eq!(
24523                message.body.contains("Add retries for failed requests."),
24524                accepted
24525            );
24526            assert_eq!(
24527                runner.state.seats["github-text-rewrite"].turns, 1,
24528                "only one rewrite invocation"
24529            );
24530            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
24531            if accepted {
24532                assert!(runner.state.github_text.is_none());
24533                assert!(!runner.state.parked);
24534                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
24535                assert!(message.body.contains("## Final verification"));
24536                assert!(message.body.contains("Evidence: final diff"));
24537                assert!(
24538                    message
24539                        .body
24540                        .contains(&format!("magi:run/{}", runner.state.id))
24541                );
24542            }
24543            if !accepted {
24544                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24545                assert!(
24546                    message
24547                        .body
24548                        .contains(&format!("magi:run/{}", runner.state.id))
24549                );
24550            }
24551        }
24552    }
24553
24554    fn scripted(id: &str, reply: &str) -> AgentSpec {
24555        let mut a = spec(id);
24556        a.command = vec![
24557            "sh".into(),
24558            "-c".into(),
24559            "printf '%s' \"$REWRITE_REPLY\"".into(),
24560        ];
24561        a.env.insert("REWRITE_REPLY".into(), reply.into());
24562        a
24563    }
24564
24565    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24566    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24567
24568    /// Gate tests inject generated public output, not internal reports.
24569    fn seed_public_summary(runner: &mut Runner) {
24570        let repo = &runner.state.repo;
24571        let g = |args: &[&str]| {
24572            let out = std::process::Command::new("git")
24573                .args(args)
24574                .current_dir(repo)
24575                .quiet()
24576                .output()
24577                .unwrap();
24578            assert!(out.status.success(), "git {args:?}");
24579            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24580        };
24581        g(&["init", "-q", "-b", "main"]);
24582        g(&[
24583            "-c",
24584            "user.name=Test",
24585            "-c",
24586            "user.email=test@example.invalid",
24587            "commit",
24588            "-q",
24589            "--allow-empty",
24590            "-m",
24591            "feat: fixture",
24592        ]);
24593        let head = g(&["rev-parse", "HEAD"]);
24594        g(&["update-ref", "refs/remotes/origin/main", &head]);
24595        let evidence = crate::pr_outcome::summary_evidence(
24596            &runner.state,
24597            crate::pr_outcome::FinalHead::At(&head),
24598        );
24599        let generated = &runner.state.candidates[0].summary;
24600        runner.state.change_summary = Some(crate::run::ChangeSummary {
24601            base: head.clone(),
24602            head,
24603            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24604            title: summary_title(generated).unwrap(),
24605            body: summary_without_title(generated),
24606        });
24607    }
24608
24609    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24610        let mut runner = runner_at(RunStatus::Gating);
24611        runner.state = state_with_summary("add retries", JA_SUMMARY);
24612        if review_only {
24613            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24614        }
24615        runner.state.repo = dir.to_owned();
24616        runner.state.candidates[0].worktree = dir.to_owned();
24617        runner.state.config.agents = agents;
24618        seed_public_summary(&mut runner);
24619        runner
24620    }
24621
24622    fn gate_questions(runner: &Runner) -> usize {
24623        ask::Questions::open()
24624            .list()
24625            .into_iter()
24626            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24627            .count()
24628    }
24629
24630    #[tokio::test]
24631    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24632        crate::run::pin_test_home();
24633        let dir = tempfile::tempdir().unwrap();
24634        let mut runner = rewrite_runner(
24635            dir.path(),
24636            true,
24637            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24638        );
24639        runner.state.config.roles.language_judge =
24640            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24641        let winner = runner.state.candidates[0].clone();
24642        let msg = runner
24643            .guarded_pr_message(&winner, None, true)
24644            .await
24645            .unwrap()
24646            .expect("an English rewrite posts without asking");
24647        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24648        assert!(msg.body.contains("<details>kept</details>"));
24649        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24650        assert_eq!(gate_questions(&runner), 0);
24651        assert!(runner.state.github_text.is_none());
24652        assert!(!runner.state.seats.contains_key("impl-A"));
24653        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24654    }
24655
24656    #[tokio::test]
24657    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24658        crate::run::pin_test_home();
24659        let dir = tempfile::tempdir().unwrap();
24660        let mut runner = rewrite_runner(
24661            dir.path(),
24662            false,
24663            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24664        );
24665        runner.state.config.roles.language_judge =
24666            Some(crate::config::AgentChoice::One("beta".into()));
24667        runner.state.seats.insert(
24668            "impl-A".into(),
24669            SeatState::new("impl-A", "alpha", runner.state.seed),
24670        );
24671        let winner = runner.state.candidates[0].clone();
24672        let msg = runner
24673            .guarded_pr_message(&winner, None, true)
24674            .await
24675            .unwrap()
24676            .expect("rewritten");
24677        assert!(msg.body.contains("<details>kept</details>"));
24678        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24679        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24680        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24681    }
24682
24683    #[tokio::test]
24684    async fn rewrite_reuses_a_resumable_implementer_session() {
24685        crate::run::pin_test_home();
24686        let dir = tempfile::tempdir().unwrap();
24687        let mut runner = rewrite_runner(
24688            dir.path(),
24689            false,
24690            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24691        );
24692        runner.state.config.roles.language_judge =
24693            Some(crate::config::AgentChoice::One("beta".into()));
24694        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24695        seat.turns = 1;
24696        runner.state.seats.insert("impl-A".into(), seat);
24697        let winner = runner.state.candidates[0].clone();
24698        runner
24699            .guarded_pr_message(&winner, None, true)
24700            .await
24701            .unwrap()
24702            .expect("rewritten");
24703        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24704        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24705    }
24706
24707    #[tokio::test]
24708    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24709        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24710        // session, was out of quota, and nothing else was asked.
24711        crate::run::pin_test_home();
24712        let dir = tempfile::tempdir().unwrap();
24713        let mut exhausted = spec("alpha");
24714        exhausted.command = vec!["false".into()];
24715        let mut runner = rewrite_runner(
24716            dir.path(),
24717            false,
24718            vec![exhausted, scripted("beta", EN_REWRITE)],
24719        );
24720        // The implementer's own agent is in the role too: it is not asked twice.
24721        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24722            "alpha".into(),
24723            "beta".into(),
24724        ]));
24725        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24726        seat.turns = 1;
24727        runner.state.seats.insert("impl-A".into(), seat);
24728        let winner = runner.state.candidates[0].clone();
24729        let msg = runner
24730            .guarded_pr_message(&winner, None, true)
24731            .await
24732            .unwrap()
24733            .expect("the role rewrites after the implementer fails");
24734        assert!(msg.body.contains("`src/net.rs`"));
24735        assert_eq!(
24736            runner.state.seats["impl-A"].turns, 2,
24737            "the implementer was tried once"
24738        );
24739        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24740        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24741    }
24742
24743    #[tokio::test]
24744    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24745        crate::run::pin_test_home();
24746        let dir = tempfile::tempdir().unwrap();
24747        let mut broken = spec("bad");
24748        broken.command = vec!["false".into()];
24749        let mut runner = rewrite_runner(
24750            dir.path(),
24751            true,
24752            vec![
24753                broken,
24754                scripted("noformat", "Add retries."),
24755                scripted("good", EN_REWRITE),
24756            ],
24757        );
24758        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24759            "bad".into(),
24760            "noformat".into(),
24761            "good".into(),
24762        ]));
24763        let winner = runner.state.candidates[0].clone();
24764        let msg = runner
24765            .guarded_pr_message(&winner, None, true)
24766            .await
24767            .unwrap()
24768            .expect("the third agent rewrites");
24769        assert!(msg.body.contains("`src/net.rs`"));
24770        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24771        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24772    }
24773
24774    #[tokio::test]
24775    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24776        crate::run::pin_test_home();
24777        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24778        for (agents, role, saved) in [
24779            (
24780                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24781                Some("beta"),
24782                true,
24783            ),
24784            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24785            (Vec::new(), None, false),
24786        ] {
24787            let dir = tempfile::tempdir().unwrap();
24788            let mut runner = rewrite_runner(dir.path(), true, agents);
24789            runner.state.config.roles.language_judge =
24790                role.map(|r| crate::config::AgentChoice::One(r.into()));
24791            let winner = runner.state.candidates[0].clone();
24792            let first = runner
24793                .guarded_pr_message(&winner, None, true)
24794                .await
24795                .unwrap();
24796            assert!(first.is_none(), "withheld text parks the run");
24797            assert!(runner.state.parked);
24798            assert_eq!(gate_questions(&runner), 1);
24799            let g = runner.state.github_text.as_ref().unwrap();
24800            assert_eq!(g.rewrite.is_some(), saved);
24801            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24802        }
24803    }
24804
24805    #[tokio::test]
24806    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24807        crate::run::pin_test_home();
24808        let dir = tempfile::tempdir().unwrap();
24809        let mut runner = runner_at(RunStatus::Gating);
24810        runner.state =
24811            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24812        runner.state.repo = dir.path().to_owned();
24813        runner.state.candidates[0].worktree = dir.path().to_owned();
24814        let mut author = spec("alpha");
24815        author.command = vec![
24816            "sh".into(),
24817            "-c".into(),
24818            "printf '%s' \"$REWRITE_REPLY\"".into(),
24819        ];
24820        author.env.insert(
24821            "REWRITE_REPLY".into(),
24822            format!(
24823                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24824                "English sentence. ".repeat(600)
24825            ),
24826        );
24827        runner.state.config.agents = vec![author];
24828        seed_public_summary(&mut runner);
24829        let winner = runner.state.candidates[0].clone();
24830        assert!(
24831            runner
24832                .guarded_pr_message(&winner, None, true)
24833                .await
24834                .unwrap()
24835                .is_none()
24836        );
24837        let record = runner.state.github_text.clone().unwrap();
24838        let rewrite = record.rewrite.clone().unwrap();
24839        assert_eq!(rewrite.failed, ["body-language"]);
24840        assert!(
24841            rewrite
24842                .body
24843                .ends_with(&format!("magi:run/{}", runner.state.id))
24844        );
24845        let store = ask::Questions::open();
24846        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24847        assert!(
24848            q.choices
24849                .contains(&crate::github_text::USE_REWRITE.to_owned())
24850        );
24851        for label in [
24852            "ORIGINAL",
24853            "FALLBACK",
24854            "REWRITE",
24855            "Rules still failed: body-language",
24856            "truncated",
24857        ] {
24858            assert!(q.detail.contains(label), "{label}");
24859        }
24860        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24861            &runner.state,
24862            &crate::github_text::artifact_name(&record.fingerprint),
24863        ))
24864        .unwrap();
24865        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24866        // Restart from serialized state, then retry after a bad owner title.
24867        runner.state =
24868            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24869        store
24870            .update(&q.id, |q| {
24871                q.say("まだ日本語")?;
24872                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24873            })
24874            .unwrap();
24875        assert!(
24876            runner
24877                .guarded_pr_message(&winner, None, true)
24878                .await
24879                .unwrap()
24880                .is_none()
24881        );
24882        let retry = runner.state.github_text.as_ref().unwrap();
24883        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24884        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24885        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24886        assert!(
24887            q.posting_comparison
24888                .as_ref()
24889                .unwrap()
24890                .matches_detail(&q.detail)
24891        );
24892        store
24893            .update(&q.id, |q| {
24894                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24895            })
24896            .unwrap();
24897        let message = runner
24898            .guarded_pr_message(&winner, None, true)
24899            .await
24900            .unwrap()
24901            .unwrap();
24902        assert_eq!(message.title, rewrite.title);
24903        assert_eq!(message.body, rewrite.body);
24904        assert_eq!(
24905            runner.state.github_text.as_ref().unwrap().choice,
24906            Some(GithubTextChoice::Rewrite)
24907        );
24908        let again = runner
24909            .guarded_pr_message(&winner, None, true)
24910            .await
24911            .unwrap()
24912            .unwrap();
24913        assert_eq!(again.title, message.title);
24914        assert_eq!(again.body, message.body);
24915        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24916        assert!(
24917            !runner
24918                .state
24919                .events
24920                .iter()
24921                .any(|e| e.message.contains(&rewrite.title)
24922                    || e.message.contains("English sentence."))
24923        );
24924    }
24925
24926    #[tokio::test]
24927    async fn historical_posting_reply_never_expires_into_fallback() {
24928        crate::run::pin_test_home();
24929        let dir = tempfile::tempdir().unwrap();
24930        let mut runner = runner_at(RunStatus::Gating);
24931        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24932        runner.state.repo = dir.path().to_owned();
24933        runner.state.candidates[0].worktree = dir.path().to_owned();
24934        seed_public_summary(&mut runner);
24935        let winner = runner.state.candidates[0].clone();
24936        assert!(
24937            runner
24938                .guarded_pr_message(&winner, None, true)
24939                .await
24940                .unwrap()
24941                .is_none()
24942        );
24943        let id = runner
24944            .state
24945            .github_text
24946            .as_ref()
24947            .unwrap()
24948            .question
24949            .clone()
24950            .unwrap();
24951        let store = ask::Questions::open();
24952        let mut q = store.get(&id).unwrap();
24953        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24954        q.answer(ask::Answer::Choice(
24955            crate::github_text::POST_ORIGINAL.into(),
24956        ))
24957        .unwrap();
24958        q.answer_delivered = true;
24959        store.put(&mut q).unwrap();
24960        let source = std::fs::read(store.path_of(&id)).unwrap();
24961        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24962        std::fs::create_dir_all(&migration).unwrap();
24963        std::fs::write(
24964            migration.join("state.json"),
24965            serde_json::to_vec(&serde_json::json!({
24966                "schema": 1, "sources": [id], "pending": [id]
24967            }))
24968            .unwrap(),
24969        )
24970        .unwrap();
24971        for _ in 0..2 {
24972            assert!(
24973                runner
24974                    .guarded_pr_message(&winner, None, true)
24975                    .await
24976                    .unwrap()
24977                    .is_none()
24978            );
24979            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24980            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24981        }
24982        let home = crate::run::home();
24983        crate::task_chat::sweep(
24984            &crate::queue::Queue::at(home.join("queue")),
24985            &crate::talk::Talks::at(home.join("talks")),
24986            &store,
24987            &home,
24988        );
24989        let outbox = crate::task_inquiry::Outbox::at(&home);
24990        outbox
24991            .update_decision(&id, |d| {
24992                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24993                d.source_answer_at = q.answered_at;
24994                Ok(true)
24995            })
24996            .unwrap();
24997        outbox
24998            .settle(
24999                &id,
25000                "owner-chat",
25001                "Owner confirms no publication remains necessary",
25002                None,
25003            )
25004            .unwrap();
25005        assert!(
25006            runner
25007                .guarded_pr_message(&winner, None, true)
25008                .await
25009                .unwrap()
25010                .is_none()
25011        );
25012        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25013        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25014    }
25015
25016    #[tokio::test]
25017    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25018        crate::run::pin_test_home();
25019        let dir = tempfile::tempdir().unwrap();
25020        let mut runner = runner_at(RunStatus::Gating);
25021        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25022        runner.state.repo = dir.path().to_owned();
25023        runner.state.candidates[0].worktree = dir.path().to_owned();
25024        seed_public_summary(&mut runner);
25025        let winner = runner.state.candidates[0].clone();
25026        assert!(
25027            runner
25028                .guarded_pr_message(&winner, None, true)
25029                .await
25030                .unwrap()
25031                .is_none()
25032        );
25033        let record = runner.state.github_text.as_ref().unwrap();
25034        assert!(record.rewrite.is_none());
25035        // Records written before the additive field deserialize with no rewrite.
25036        let mut old = serde_json::to_value(record).unwrap();
25037        old.as_object_mut().unwrap().remove("rewrite");
25038        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25039        assert!(old.rewrite.is_none());
25040        let id = record.question.clone().unwrap();
25041        ask::Questions::open()
25042            .update(&id, |q| {
25043                q.choices.push(crate::github_text::USE_REWRITE.into());
25044                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25045            })
25046            .unwrap();
25047        let message = runner
25048            .guarded_pr_message(&winner, None, true)
25049            .await
25050            .unwrap()
25051            .unwrap();
25052        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25053        assert_eq!(
25054            runner.state.github_text.as_ref().unwrap().choice,
25055            Some(GithubTextChoice::Fallback)
25056        );
25057    }
25058
25059    #[tokio::test]
25060    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25061        crate::run::pin_test_home();
25062        let dir = tempfile::tempdir().unwrap();
25063        let mut runner = runner_at(RunStatus::Gating);
25064        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25065        runner.state.repo = dir.path().to_owned();
25066        runner.state.candidates[0].worktree = dir.path().to_owned();
25067        seed_public_summary(&mut runner);
25068        let winner = runner.state.candidates[0].clone();
25069        assert!(
25070            runner
25071                .guarded_pr_message(&winner, None, true)
25072                .await
25073                .unwrap()
25074                .is_none()
25075        );
25076        let store = ask::Questions::open();
25077        let find = |run: &str| {
25078            store
25079                .list()
25080                .into_iter()
25081                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
25082                .unwrap()
25083        };
25084        let run = runner.state.id.clone();
25085        let q = find(&run);
25086        let fp = runner
25087            .state
25088            .github_text
25089            .as_ref()
25090            .unwrap()
25091            .fingerprint
25092            .clone();
25093        let name = crate::github_text::artifact_name(&fp);
25094        let path = crate::run::artifact_path(&runner.state, &name);
25095        assert!(q.detail.contains(&path.display().to_string()));
25096        assert!(q.detail.contains("title-language: title"));
25097        let saved = std::fs::read_to_string(&path).expect("artifact written");
25098        assert!(saved.contains("日本語のタイトル"));
25099        assert!(q.cwd.is_none());
25100        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
25101        // A bad replacement is refused and asked about once more.
25102        let say = |id: &str, text: &str, choice: &str| {
25103            store
25104                .update(id, |q| {
25105                    q.thread.push(ask::Turn {
25106                        who: ask::Who::Operator,
25107                        body: text.to_owned(),
25108                        at: jiff::Timestamp::now(),
25109                        note: None,
25110                    });
25111                    q.answer(ask::Answer::Choice(choice.to_owned()))
25112                })
25113                .unwrap();
25114        };
25115        say(&q.id, "まだ日本語", "use my text");
25116        assert!(
25117            runner
25118                .guarded_pr_message(&winner, None, true)
25119                .await
25120                .unwrap()
25121                .is_none()
25122        );
25123        let second = find(&run);
25124        assert_ne!(second.id, q.id);
25125        assert!(second.detail.contains("did not pass"));
25126        // The retry still compares the original text; the rejected
25127        // replacement is named by category only.
25128        assert!(second.detail.contains("日本語のタイトル"));
25129        assert!(!second.detail.contains("まだ日本語"));
25130        assert!(second.detail.contains(&path.display().to_string()));
25131        say(&second.id, "fix: retry failed requests", "use my text");
25132        let message = runner
25133            .guarded_pr_message(&winner, None, true)
25134            .await
25135            .unwrap()
25136            .expect("a vetted replacement is posted");
25137        assert_eq!(message.title, "fix: retry failed requests");
25138        assert_eq!(
25139            runner
25140                .state
25141                .github_text
25142                .as_ref()
25143                .unwrap()
25144                .chosen_title
25145                .as_deref(),
25146            Some("fix: retry failed requests")
25147        );
25148        assert!(runner.state.github_text.as_ref().unwrap().resolved);
25149        // Resumed again: the saved decision is applied, nothing is re-asked.
25150        let again = runner
25151            .guarded_pr_message(&winner, None, true)
25152            .await
25153            .unwrap()
25154            .unwrap();
25155        assert_eq!(again.title, message.title);
25156        assert_eq!(
25157            store
25158                .list()
25159                .into_iter()
25160                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
25161                .count(),
25162            2
25163        );
25164    }
25165
25166    #[test]
25167    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
25168        // What magi itself writes stays English under any configured language,
25169        // so a future localisation of these headings fails here. (The agents'
25170        // own text is also checked by the posting gate.)
25171        let mut state = state_with_summary(
25172            "add retries",
25173            "TITLE: fix(web): batch reads\n- reads run.json once",
25174        );
25175        state.config.graph.language = "ja".to_owned();
25176        let m = pr_message(&state, 'A');
25177        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
25178        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
25179
25180        // The task is the operator's own text: it goes in untouched, and the
25181        // fallback title (no summary) may be in its language too.
25182        let task = "今回やってほしいこと: results projector を直す";
25183        let mut state = state_with_summary(task, "- no title line");
25184        state.config.graph.language = "ja".to_owned();
25185        let m = pr_message(&state, 'A');
25186        assert_eq!(
25187            m.title,
25188            format!("chore: land candidate A of run {}", state.id)
25189        );
25190        assert!(
25191            m.body.contains(&format!(
25192                "<summary>Original task</summary>\n\n{task}\n\n</details>"
25193            )),
25194            "{}",
25195            m.body
25196        );
25197    }
25198
25199    #[test]
25200    fn pr_message_scrubs_home_paths_and_addresses() {
25201        let state = state_with_summary(
25202            "fix it in /Users/someone/src/x",
25203            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
25204        );
25205        let m = pr_message(&state, 'A');
25206        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
25207            assert!(!m.body.contains(leak), "{}", m.body);
25208        }
25209        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
25210    }
25211
25212    #[test]
25213    fn pr_message_survives_a_task_that_closes_details() {
25214        let state = state_with_summary("a </details> b", "TITLE: fix: x");
25215        let m = pr_message(&state, 'A');
25216        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
25217    }
25218
25219    #[test]
25220    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
25221        let cmd = manual_merge_command(
25222            MergeStyle::Squash,
25223            Path::new("/repo"),
25224            "b",
25225            "fix: \"quoted\" $(x) `y`\n\nbody",
25226        );
25227        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
25228    }
25229
25230    #[test]
25231    fn manual_merge_command_matches_the_configured_style() {
25232        let repo = Path::new("/repo");
25233        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
25234
25235        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
25236        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
25237
25238        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
25239        assert_eq!(
25240            squash,
25241            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
25242             \"Merge magi run 0832 (candidate A)\""
25243        );
25244
25245        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
25246        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
25247    }
25248
25249    #[test]
25250    fn a_nudge_gets_a_quarter_of_the_budget() {
25251        // The judge and implement budgets magi ships with.
25252        assert_eq!(retry_budget(secs(1200), true), secs(300));
25253        assert_eq!(retry_budget(secs(3600), true), secs(900));
25254    }
25255
25256    #[test]
25257    fn a_resent_prompt_keeps_the_whole_budget() {
25258        // The seat kept no context, so the retry is the original job again and
25259        // shortening it would only guarantee a second failure.
25260        assert_eq!(retry_budget(secs(1200), false), secs(1200));
25261        assert_eq!(retry_budget(secs(60), false), secs(60));
25262    }
25263
25264    #[test]
25265    fn the_floor_never_exceeds_the_original_budget() {
25266        // A short configured timeout must not be *raised* by the floor: the
25267        // operator asked for a bound, and a retry may not outlast the attempt
25268        // it is retrying.
25269        assert_eq!(retry_budget(secs(60), true), secs(60));
25270        assert_eq!(retry_budget(secs(480), true), secs(120));
25271        assert_eq!(retry_budget(secs(0), true), secs(0));
25272    }
25273
25274    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
25275        agent::CommandEvidence {
25276            id: "item1".to_owned(),
25277            description: "cargo test".to_owned(),
25278            exit_code,
25279            result_summary: String::new(),
25280            source: "codex".to_owned(),
25281        }
25282    }
25283
25284    #[test]
25285    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
25286        // No evidence is not the same fact as unconfirmed evidence: a
25287        // backend with no adapter, or a reply that ran no commands at all,
25288        // must not be misread as carrying a dangling job.
25289        assert!(!has_unconfirmed_command(&[]));
25290    }
25291
25292    #[test]
25293    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
25294        // Deliberately not a check on the exit code's *value*: a fixer
25295        // legitimately runs something that fails mid-iteration before it
25296        // succeeds, and that must never by itself reopen a valid report.
25297        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
25298        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
25299        assert!(!has_unconfirmed_command(&[
25300            evidence(Some(0)),
25301            evidence(Some(101))
25302        ]));
25303    }
25304
25305    #[test]
25306    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
25307        assert!(has_unconfirmed_command(&[
25308            evidence(Some(0)),
25309            evidence(None)
25310        ]));
25311    }
25312
25313    fn evidence_with(
25314        description: &str,
25315        exit_code: Option<i32>,
25316        result_summary: &str,
25317    ) -> agent::CommandEvidence {
25318        agent::CommandEvidence {
25319            id: "item1".to_owned(),
25320            description: description.to_owned(),
25321            exit_code,
25322            result_summary: result_summary.to_owned(),
25323            source: "codex".to_owned(),
25324        }
25325    }
25326
25327    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
25328        format!(
25329            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{commit}","method":"git merge-base --is-ancestor {commit} HEAD","observed":"exit 0; {commit} is on base","passed":true}},{{"id":"c2","kind":"test","target":"{test_name}","method":"cargo test --lib {test_name}","observed":"test result: ok. 1 passed; 0 failed","passed":true}}],"unresolved":[]}}"#
25330        )
25331    }
25332
25333    #[test]
25334    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
25335        let text = valid_noop_summary("b32cfc4", "retry_test");
25336        let claim = verified_noop_claim(true, &[], &text)
25337            .expect("valid structured report with no CommandEvidence must be accepted");
25338        assert!(claim.contains("b32cfc4"), "{claim}");
25339        assert!(claim.contains("retry_test"), "{claim}");
25340    }
25341
25342    #[test]
25343    fn operational_regression_and_legacy_noop_claims_are_rejected() {
25344        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
25345        assert!(verified_noop_claim(true, &[], regression).is_none());
25346        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
25347        assert!(err.contains("single JSON object"), "{err}");
25348
25349        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25350        assert!(verified_noop_claim(true, &[], legacy).is_none());
25351    }
25352
25353    #[test]
25354    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
25355        // A timeout or a bad exit code reads as the ordinary loss it is,
25356        // whatever the reply's own structured JSON claims.
25357        let text = valid_noop_summary("b32cfc4", "retry_test");
25358        assert!(verified_noop_claim(false, &[], &text).is_none());
25359    }
25360
25361    #[test]
25362    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
25363        let text = valid_noop_summary("b32cfc4", "retry_test");
25364        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
25365        // A matching confirmed command alongside the marker is fine.
25366        assert!(
25367            verified_noop_claim(
25368                true,
25369                &[evidence_with(
25370                    "cargo test --lib retry_test",
25371                    Some(0),
25372                    "1 passed"
25373                )],
25374                &text
25375            )
25376            .is_some()
25377        );
25378    }
25379
25380    #[test]
25381    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
25382     {
25383        let text = valid_noop_summary("b32cfc4", "retry_test");
25384
25385        // Unrelated passing command cannot substantiate a claimed test run.
25386        let err = evaluate_noop_claim(
25387            true,
25388            &[evidence_with("git status", Some(0), "nothing to commit")],
25389            &text,
25390        )
25391        .unwrap_err();
25392        assert!(err.contains("no matching command was recorded"), "{err}");
25393
25394        // Final matching command exited non-zero -> rejected even if an
25395        // unrelated command succeeded afterward.
25396        let err = evaluate_noop_claim(
25397            true,
25398            &[
25399                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
25400                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25401                evidence_with("rg retry_test src", Some(0), "retry_test"),
25402            ],
25403            &text,
25404        )
25405        .unwrap_err();
25406        assert!(err.contains("exited with"), "{err}");
25407
25408        // A different invocation containing the entire method is not a rerun.
25409        let err = evaluate_noop_claim(
25410            true,
25411            &[evidence_with(
25412                "echo 'cargo test --lib retry_test'",
25413                Some(0),
25414                "retry_test",
25415            )],
25416            &text,
25417        )
25418        .unwrap_err();
25419        assert!(err.contains("no matching command was recorded"), "{err}");
25420
25421        // Mid-investigation failure followed by a passing re-run -> accepted!
25422        assert!(
25423            verified_noop_claim(
25424                true,
25425                &[
25426                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25427                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
25428                ],
25429                &text
25430            )
25431            .is_some()
25432        );
25433    }
25434
25435    #[test]
25436    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
25437        let text = valid_noop_summary("b32cfc4", "retry_test");
25438        let method = "cargo test --lib retry_test";
25439        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
25440        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
25441        let failed =
25442            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
25443        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
25444        for output in [empty, ignored, failed] {
25445            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
25446                .unwrap_err();
25447            assert!(err.contains("failure or no passing tests"), "{err}");
25448        }
25449        // Multiple harnesses can legitimately include a filtered-out suite.
25450        let mixed = format!("{passed}\n{empty}");
25451        assert!(
25452            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
25453        );
25454        // A later real rerun of the same command can establish success.
25455        assert!(
25456            verified_noop_claim(
25457                true,
25458                &[
25459                    evidence_with(method, Some(0), empty),
25460                    evidence_with(method, Some(0), passed),
25461                ],
25462                &text,
25463            )
25464            .is_some()
25465        );
25466    }
25467
25468    #[test]
25469    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
25470        let text = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"README includes the expected header","satisfied":true,"evidence":["p1"]}],"checks":[{"id":"p1","kind":"path","target":"README.md","method":"rg expected README.md","observed":"expected header found","passed":true}],"unresolved":[]}"#;
25471        let failed = evidence_with("rg expected README.md", Some(1), "");
25472        let unrelated = evidence_with("cat README.md", Some(0), "README");
25473        let err =
25474            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
25475        assert!(err.contains("exited with"), "{err}");
25476        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
25477        assert!(
25478            evaluate_noop_claim(
25479                true,
25480                &[
25481                    failed,
25482                    evidence_with("rg expected README.md", Some(0), "expected header"),
25483                ],
25484                text,
25485            )
25486            .unwrap()
25487            .is_some()
25488        );
25489    }
25490
25491    #[test]
25492    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
25493        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
25494        assert!(matches!(
25495            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
25496            Ok(None)
25497        ));
25498    }
25499
25500    #[tokio::test]
25501    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
25502        let tmp = tempfile::tempdir().unwrap();
25503        let repo = tmp.path().join("repo");
25504        std::fs::create_dir_all(&repo).unwrap();
25505        let run_git = |args: &[&str]| {
25506            let out = std::process::Command::new("git")
25507                .args(args)
25508                .current_dir(&repo)
25509                .output()
25510                .unwrap();
25511            assert!(out.status.success(), "git {args:?} failed");
25512            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25513        };
25514        run_git(&["init", "-b", "main"]);
25515        run_git(&["config", "user.name", "test"]);
25516        run_git(&["config", "user.email", "test@example.com"]);
25517        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
25518        run_git(&["add", "-A"]);
25519        run_git(&["commit", "-m", "base commit"]);
25520        let base = run_git(&["rev-parse", "HEAD"]);
25521
25522        // Create a commit on a side branch not on `base`.
25523        run_git(&["checkout", "-b", "side"]);
25524        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
25525        run_git(&["add", "-A"]);
25526        run_git(&["commit", "-m", "side commit"]);
25527        let side = run_git(&["rev-parse", "HEAD"]);
25528        run_git(&["checkout", "main"]);
25529
25530        // Valid commit on base + existing path -> Accepted.
25531        let valid = format!(
25532            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"readme exists","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{base}","method":"git merge-base --is-ancestor {base} HEAD","observed":"exit 0; base commit is on main","passed":true}},{{"id":"c2","kind":"path","target":"README.md:1","method":"read README.md","observed":"contains expected greeting","passed":true}}],"unresolved":[]}}"#
25533        );
25534        assert!(matches!(
25535            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
25536            NoopClaimVerdict::Accepted
25537        ));
25538
25539        // Non-existent commit SHA -> Rejected.
25540        let missing_sha = valid.replace(&base, "deadbeef");
25541        assert!(matches!(
25542            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
25543            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
25544        ));
25545
25546        // Commit on unmerged side branch -> Rejected.
25547        let side_sha = valid.replace(&base, &side);
25548        assert!(matches!(
25549            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
25550            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
25551        ));
25552
25553        // Missing file path -> Rejected.
25554        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
25555        assert!(matches!(
25556            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
25557            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
25558        ));
25559    }
25560
25561    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
25562    /// pair, in order, labelled A, B, C, ...
25563    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
25564        runner.state.candidates = shape
25565            .iter()
25566            .enumerate()
25567            .map(|(i, &(empty, verified))| {
25568                let (summary, verified_noop) = match verified {
25569                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
25570                    None => (String::new(), None),
25571                };
25572                Candidate {
25573                    index: i,
25574                    label: (b'A' + i as u8) as char,
25575                    agent: "sonnet".to_owned(),
25576                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
25577                    worktree: PathBuf::from(format!("/wt/{i}")),
25578                    summary,
25579                    stat: String::new(),
25580                    files: 0,
25581                    commits: 0,
25582                    empty,
25583                    failed: None,
25584                    verified_noop,
25585                    duration_ms: 0,
25586                    folded: false,
25587                }
25588            })
25589            .collect();
25590    }
25591
25592    #[test]
25593    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
25594        ask_test_home();
25595        let mut runner = runner_at(RunStatus::Implementing);
25596        let a = valid_noop_summary("b32cfc4", "test_a");
25597        let b = valid_noop_summary("b32cfc4", "test_b");
25598        set_candidates(
25599            &mut runner,
25600            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
25601        );
25602
25603        runner
25604            .after_implement()
25605            .expect("a verified no-op is not an error");
25606
25607        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
25608    }
25609
25610    #[test]
25611    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
25612        ask_test_home();
25613        let mut runner = runner_at(RunStatus::Implementing);
25614        let a = valid_noop_summary("b32cfc4", "test_a");
25615        // Candidate A declares a verified no-op; candidate B simply wrote
25616        // nothing and said nothing about why. One candidate's claim is not
25617        // the whole run's agreement.
25618        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
25619
25620        let err = runner
25621            .after_implement()
25622            .expect_err("an unverified empty candidate must still fail the run");
25623
25624        assert!(
25625            err.to_string().contains("no candidate produced a change"),
25626            "{err}"
25627        );
25628        assert_eq!(runner.state.status, RunStatus::Failed);
25629    }
25630
25631    #[test]
25632    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
25633        ask_test_home();
25634        let mut runner = runner_at(RunStatus::Implementing);
25635        // Simulate a saved incomplete run that stored a legacy/incomplete
25636        // `verified_noop` string before this build's strict contract.
25637        set_candidates(
25638            &mut runner,
25639            &[(
25640                true,
25641                Some(
25642                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
25643                ),
25644            )],
25645        );
25646
25647        let err = runner
25648            .after_implement()
25649            .expect_err("invalid saved noop claim must fail the run");
25650        assert!(
25651            err.to_string().contains("no candidate produced a change"),
25652            "{err}"
25653        );
25654        assert_eq!(runner.state.status, RunStatus::Failed);
25655        assert!(runner.state.candidates[0].verified_noop.is_none());
25656        assert!(runner.state.candidates[0].failed.is_some());
25657        assert!(runner.state.events.iter().any(|e| {
25658            e.message
25659                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
25660        }));
25661    }
25662
25663    #[test]
25664    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
25665        ask_test_home();
25666        let mut runner = runner_at(RunStatus::Implementing);
25667        let a = valid_noop_summary("b32cfc4", "test_a");
25668        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
25669        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
25670
25671        let err = runner
25672            .after_implement()
25673            .expect_err("a failed candidate must never settle as verified no-op");
25674        assert!(err.to_string().contains("no candidate produced a change"));
25675        assert_eq!(runner.state.status, RunStatus::Failed);
25676        assert!(runner.state.candidates[0].verified_noop.is_none());
25677    }
25678
25679    #[test]
25680    fn after_implement_still_fails_an_ordinary_all_empty_run() {
25681        ask_test_home();
25682        let mut runner = runner_at(RunStatus::Implementing);
25683        set_candidates(&mut runner, &[(true, None), (true, None)]);
25684
25685        let err = runner
25686            .after_implement()
25687            .expect_err("no candidate declared anything; this is an ordinary failure");
25688
25689        assert!(
25690            err.to_string().contains("no candidate produced a change"),
25691            "{err}"
25692        );
25693        assert_eq!(runner.state.status, RunStatus::Failed);
25694    }
25695}
25696
25697/// A graft rollback whose restore could not be confirmed (see
25698/// [`Runner::graft`]).
25699#[derive(Debug)]
25700struct GraftRestoreFailed(String);
25701
25702impl std::fmt::Display for GraftRestoreFailed {
25703    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25704        write!(
25705            f,
25706            "could not restore the winner to its pre-graft commit: {}",
25707            self.0
25708        )
25709    }
25710}
25711
25712impl std::error::Error for GraftRestoreFailed {}
25713
25714/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
25715/// not the agent: they never draw on an agent's own timeout, and running out of
25716/// them never reads as an agent failure.
25717#[cfg(test)]
25718mod resource_wait_tests {
25719    use super::*;
25720    use std::collections::BTreeMap;
25721
25722    fn sh(id: &str, script: &str) -> AgentSpec {
25723        AgentSpec {
25724            id: id.to_owned(),
25725            kind: crate::config::AgentKind::Command,
25726            model: None,
25727            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
25728            extra_args: Vec::new(),
25729            env: BTreeMap::new(),
25730            prompt_delivery: None,
25731            max_turn_secs: None,
25732        }
25733    }
25734
25735    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
25736        SeatJob {
25737            seat: SeatState::new("impl-A", &spec.id, 1),
25738            spec,
25739            cwd: dir.to_path_buf(),
25740            prompt: "do it".to_owned(),
25741            timeout,
25742            allow_write: true,
25743            sessions: false,
25744            artifacts: dir.join("art"),
25745            stem: "impl-A".to_owned(),
25746            handover: None,
25747        }
25748    }
25749
25750    fn state(resource_wait_secs: u64) -> RunState {
25751        let mut config = Config::default();
25752        config.graph.timeout_resource_wait = resource_wait_secs;
25753        RunState::new(
25754            PathBuf::from("/repo"),
25755            "main".to_owned(),
25756            "abc1234".to_owned(),
25757            "task".to_owned(),
25758            config,
25759        )
25760    }
25761
25762    fn hold(cache: &Path) -> crate::cache::Guard {
25763        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
25764        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
25765            crate::cache::AcquireOutcome::Acquired(g) => g,
25766            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
25767        }
25768    }
25769
25770    async fn run(
25771        jobs: Vec<SeatJob>,
25772        sem: Arc<Semaphore>,
25773        cache: Option<&Path>,
25774        st: &mut RunState,
25775    ) -> Vec<(usize, SeatState, AgentOutcome)> {
25776        let prompts = Prompts::default();
25777        let ctx = WaveCtx {
25778            run: "r",
25779            node: "implement",
25780            prompts: &prompts,
25781            cache,
25782            round: None,
25783            carry_seats: false,
25784            pauses: None,
25785        };
25786        wave(jobs, sem, &ctx, st, 0).await
25787    }
25788
25789    #[tokio::test]
25790    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
25791        crate::run::pin_test_home();
25792        let home = crate::run::home();
25793        let tmp = tempfile::tempdir().unwrap();
25794        let repo = tmp.path().join("repo");
25795        let checkout = tmp.path().join("checkout");
25796        std::fs::create_dir(&repo).unwrap();
25797        git::git(&repo, &["init"]).await.unwrap();
25798        git::git(
25799            &repo,
25800            &[
25801                "-c",
25802                "user.name=Fixture",
25803                "-c",
25804                "user.email=fixture@example.invalid",
25805                "commit",
25806                "--allow-empty",
25807                "-m",
25808                "initial",
25809            ],
25810        )
25811        .await
25812        .unwrap();
25813        git::worktree_add_detached(&repo, &checkout, "HEAD")
25814            .await
25815            .unwrap();
25816        let target = crate::build_target::resolve(&home, &checkout).unwrap();
25817        let target_lease = hold(&target);
25818        let shared = tmp.path().join("unrelated");
25819        let _shared_lease = hold(&shared);
25820        let mut st = state(0);
25821        st.repo = repo.clone();
25822        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
25823        st.config.verify.e2e = vec![format!(
25824            "CARGO_TARGET_DIR='{}' cargo test",
25825            git::path_arg(&shared)
25826        )];
25827        let config = tmp.path().join("config.toml");
25828        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
25829        let prompts = Prompts::default();
25830        let run_id = st.id.clone();
25831        let ctx = WaveCtx {
25832            run: &run_id,
25833            node: "implement",
25834            prompts: &prompts,
25835            cache: None,
25836            round: None,
25837            carry_seats: false,
25838            pauses: None,
25839        };
25840        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
25841        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
25842        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25843        assert_eq!(results[0].1.turns, 0);
25844        let saved = RunState::load_under(&run_id, &home).unwrap();
25845        let block = saved.resource_block.unwrap();
25846        assert!(matches!(
25847            block.cause,
25848            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
25849                if actual == &target
25850        ));
25851        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
25852        let mut task = crate::queue::Task::new(
25853            "build".into(),
25854            "build".into(),
25855            repo,
25856            crate::queue::Source::Human,
25857        );
25858        task.runs.push(run_id);
25859        task.hold_machine(Some(format!(
25860            "{}{}",
25861            crate::cache::RESOURCE_HOLD,
25862            block.description()
25863        )));
25864        queue.put(&mut task).unwrap();
25865        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
25866        let triage =
25867            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
25868        let pending = triage();
25869        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
25870        assert_eq!(
25871            queue.get(&task.id).unwrap().status,
25872            crate::queue::TaskStatus::Held
25873        );
25874        drop(target_lease);
25875        assert_eq!(triage().resumed, vec![task.id.clone()]);
25876        assert_eq!(
25877            queue.get(&task.id).unwrap().status,
25878            crate::queue::TaskStatus::Queued
25879        );
25880        assert!(crate::cache::in_use(&home, &shared));
25881    }
25882
25883    #[tokio::test]
25884    async fn verification_cache_wait_preserves_the_command_budget() {
25885        crate::run::pin_test_home();
25886        let tmp = tempfile::tempdir().unwrap();
25887        let cache = tmp.path().join("target");
25888        let guard = hold(&cache);
25889        let release = tokio::spawn(async move {
25890            tokio::time::sleep(Duration::from_millis(100)).await;
25891            guard.release();
25892        });
25893        let mut st = state(10);
25894        let budget = Duration::from_millis(50);
25895        let wait = repository_wait(&st, None);
25896        let (outcomes, _) = with_cache_lease(
25897            &mut st,
25898            Some(&cache),
25899            "gate",
25900            "gate",
25901            tmp.path(),
25902            "abc1234",
25903            budget,
25904            "test gate",
25905            &wait,
25906            |_, available| async move {
25907                assert_eq!(
25908                    available, budget,
25909                    "contention must not shorten verification"
25910                );
25911                (Vec::new(), false, Vec::new())
25912            },
25913        )
25914        .await
25915        .unwrap();
25916        release.await.unwrap();
25917        assert!(outcomes.is_empty(), "{outcomes:?}");
25918        assert!(
25919            st.events
25920                .iter()
25921                .any(|event| event.message.contains("waiting for"))
25922        );
25923        assert!(st.resource_wait.is_none());
25924        // The verification body no longer owns the lease after returning.
25925        hold(&cache).release();
25926    }
25927
25928    #[tokio::test]
25929    async fn verification_cache_wait_expires_without_starting_commands() {
25930        crate::run::pin_test_home();
25931        let tmp = tempfile::tempdir().unwrap();
25932        let cache = tmp.path().join("target");
25933        let _held = hold(&cache);
25934        let mut st = state(0);
25935        let wait = repository_wait(&st, None);
25936        let (outcomes, _) = with_cache_lease(
25937            &mut st,
25938            Some(&cache),
25939            "gate",
25940            "gate",
25941            tmp.path(),
25942            "abc1234",
25943            Duration::from_secs(60),
25944            "test gate",
25945            &wait,
25946            |_, _| async { panic!("commands must not start without the cache lease") },
25947        )
25948        .await
25949        .unwrap();
25950        assert_eq!(outcomes.len(), 1);
25951        assert!(outcomes[0].resource_blocked);
25952        assert!(st.resource_wait.is_none());
25953        assert!(matches!(
25954            st.resource_block.unwrap().cause,
25955            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25956        ));
25957    }
25958
25959    #[tokio::test]
25960    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25961        crate::run::pin_test_home();
25962        let tmp = tempfile::tempdir().unwrap();
25963        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25964        let cache = tmp.path().join("cache");
25965        let mut state = state(21600);
25966        let wait = repository_wait(&state, None);
25967        let (outcomes, _) = with_cache_lease(
25968            &mut state,
25969            Some(&cache),
25970            "gate",
25971            "gate",
25972            tmp.path(),
25973            "head",
25974            Duration::from_secs(60),
25975            "gate",
25976            &wait,
25977            |_, _| async { panic!("freshness failure must not start verification") },
25978        )
25979        .await
25980        .unwrap();
25981        assert_eq!(outcomes.len(), 1);
25982        assert!(outcomes[0].resource_blocked);
25983        let block = state.resource_block.unwrap();
25984        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25985        assert!(!block.description().contains("timed out"));
25986    }
25987
25988    #[tokio::test]
25989    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25990        crate::run::pin_test_home();
25991        let tmp = tempfile::tempdir().unwrap();
25992        let cache = tmp.path().join("cache");
25993        let _held = hold(&cache);
25994        let mut state = state(21600);
25995        let pause = Pause::new();
25996        let interrupt = Pause::new();
25997        let cause = ParkCause::Operator;
25998        pause.park_for(cause.clone());
25999        let prompts = Prompts::default();
26000        let ctx = WaveCtx {
26001            run: "test",
26002            node: "fix",
26003            prompts: &prompts,
26004            cache: Some(&cache),
26005            round: None,
26006            carry_seats: false,
26007            pauses: Some((&pause, &interrupt)),
26008        };
26009        let result = wave(
26010            vec![job(
26011                sh("writer", "exit 99"),
26012                tmp.path(),
26013                Duration::from_secs(1),
26014            )],
26015            Arc::new(Semaphore::new(1)),
26016            &ctx,
26017            &mut state,
26018            0,
26019        )
26020        .await;
26021        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
26022        assert_eq!(result[0].1.turns, 0);
26023        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26024        assert_eq!(
26025            state.resource_block.unwrap().cause,
26026            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
26027        );
26028        assert!(state.active.is_empty());
26029    }
26030
26031    #[tokio::test]
26032    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
26033        crate::run::pin_test_home();
26034        let tmp = tempfile::tempdir().unwrap();
26035        let cache = tmp.path().join("target-a");
26036        let guard = hold(&cache);
26037        // Held for longer than the agent's whole 1s budget.
26038        tokio::spawn(async move {
26039            tokio::time::sleep(Duration::from_millis(1500)).await;
26040            guard.release();
26041        });
26042        let mut st = state(60);
26043        let results = run(
26044            vec![job(
26045                sh("alpha", "echo ok"),
26046                tmp.path(),
26047                Duration::from_secs(1),
26048            )],
26049            Arc::new(Semaphore::new(1)),
26050            Some(&cache),
26051            &mut st,
26052        )
26053        .await;
26054        assert!(
26055            matches!(results[0].2, AgentOutcome::Ok(_)),
26056            "the wait must not be charged to the agent"
26057        );
26058        assert!(st.resource_block.is_none());
26059        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26060        assert!(st.resource_wait.is_none() && st.active.is_empty());
26061    }
26062
26063    #[tokio::test]
26064    #[cfg(unix)]
26065    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
26066        use std::os::fd::AsRawFd as _;
26067        crate::run::pin_test_home();
26068        let tmp = tempfile::tempdir().unwrap();
26069        crate::git::git(tmp.path(), &["init"]).await.unwrap();
26070        let common = tmp.path().join(".git");
26071        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
26072        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
26073        assert_eq!(
26074            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
26075            0
26076        );
26077        let mut st = state(1);
26078        st.config.coordination = crate::config::test_coordination();
26079        let mut reader = job(
26080            sh("reader", "echo must-not-run"),
26081            tmp.path(),
26082            Duration::from_secs(30),
26083        );
26084        reader.allow_write = false;
26085        let results = run(
26086            vec![reader.clone()],
26087            Arc::new(Semaphore::new(1)),
26088            None,
26089            &mut st,
26090        )
26091        .await;
26092        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26093        assert_eq!(results[0].1.turns, 0);
26094        assert!(FailClass::of(&results[0].2).is_none());
26095        assert_eq!(
26096            st.resource_block.as_ref().unwrap().kind,
26097            "repository coordination"
26098        );
26099        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26100        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26101        drop(external);
26102        let editor = crate::repo_lock::SeatLease::for_checkout(
26103            tmp.path(),
26104            true,
26105            crate::config::test_coordination().as_ref(),
26106        )
26107        .await
26108        .unwrap();
26109        let pause = Pause::new();
26110        let interrupt = Pause::new();
26111        let prompts = Prompts::default();
26112        let ctx = WaveCtx {
26113            run: "r",
26114            node: "review",
26115            prompts: &prompts,
26116            cache: None,
26117            round: None,
26118            carry_seats: false,
26119            pauses: Some((&pause, &interrupt)),
26120        };
26121        let (results, ()) = tokio::join!(
26122            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
26123            async {
26124                tokio::time::sleep(Duration::from_millis(50)).await;
26125                pause.park();
26126            }
26127        );
26128        assert!(
26129            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
26130        );
26131        assert_eq!(results[0].1.turns, 0);
26132        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26133        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26134        drop(editor);
26135    }
26136
26137    #[tokio::test]
26138    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
26139        crate::run::pin_test_home();
26140        let tmp = tempfile::tempdir().unwrap();
26141        let cache = tmp.path().join("target-b");
26142        let _held = hold(&cache);
26143        let mut st = state(1);
26144        let results = run(
26145            vec![job(
26146                sh("alpha", "echo ok"),
26147                tmp.path(),
26148                Duration::from_secs(1),
26149            )],
26150            Arc::new(Semaphore::new(1)),
26151            Some(&cache),
26152            &mut st,
26153        )
26154        .await;
26155        let (_, seat, out) = &results[0];
26156        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
26157        assert!(wave_blocked(&results));
26158        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
26159        assert_eq!(seat.turns, 0, "nothing was asked");
26160        assert!(
26161            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
26162            "no agent was spawned"
26163        );
26164        assert!(FailClass::of(out).is_none(), "not a failure class");
26165        let block = st.resource_block.as_ref().expect("recorded for the resume");
26166        assert_eq!(block.kind, "shared build cache");
26167        assert!(matches!(
26168            block.cause,
26169            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
26170        ));
26171        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26172        assert!(st.active.is_empty());
26173    }
26174
26175    #[tokio::test]
26176    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
26177        crate::run::pin_test_home();
26178        let tmp = tempfile::tempdir().unwrap();
26179        let mut st = state(1);
26180        let results = run(
26181            vec![job(
26182                sh("alpha", "echo ok"),
26183                tmp.path(),
26184                Duration::from_secs(1),
26185            )],
26186            Arc::new(Semaphore::new(0)),
26187            None,
26188            &mut st,
26189        )
26190        .await;
26191        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26192        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
26193        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
26194    }
26195
26196    #[tokio::test]
26197    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
26198        crate::run::pin_test_home();
26199        let tmp = tempfile::tempdir().unwrap();
26200        let mut st = state(60);
26201        let results = run(
26202            vec![job(
26203                sh("alpha", "sleep 30"),
26204                tmp.path(),
26205                Duration::from_secs(1),
26206            )],
26207            Arc::new(Semaphore::new(1)),
26208            None,
26209            &mut st,
26210        )
26211        .await;
26212        let out = &results[0].2;
26213        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
26214        let class = FailClass::of(out).expect("a failure");
26215        assert_eq!(class, FailClass::Timeout);
26216        assert!(should_hand_over(None, &class), "existing handover policy");
26217        assert!(st.resource_block.is_none());
26218    }
26219}