Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61use crate::worktree_setup;
62
63/// Bytes of a failing command's output kept in an event, so the reason a run
64/// stopped is readable from the report without opening `run.json`.
65const EVENT_OUTPUT_TAIL: usize = 2_000;
66
67/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
68/// command's pid before releasing the build cache's lease.
69const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
70
71/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
72/// command's pid to actually exit before giving up and releasing anyway.
73///
74/// A timeout means the process was asked to die (`kill_on_drop`,
75/// `start_kill`), not that it already has — on Windows in particular that can
76/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
77/// the instant the command returns would let the very next acquirer (this
78/// run's own next round, another run's verification, the janitor's prune)
79/// start touching the same directory while it might still be writing to it,
80/// so this polls the actual pid — real confirmation, not a fixed guess —
81/// until it is gone or this ceiling is reached. It is still not full
82/// process-tree reaping: a grandchild the timed-out process spawned and that
83/// outlives it independently is invisible to a pid check, and continuing to
84/// observe and collect *that* stays a different piece of work with its own
85/// owner. Set generously because the common case returns early the moment
86/// the pid is confirmed gone, not because every timeout pays this in full.
87const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
88
89/// Consecutive review rounds with no tree progress (see
90/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
91/// instead of spending the rest of the round budget.
92///
93/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
94/// legitimately finds nothing left to change (its previous round's fix already
95/// covered it, and this round's reviewers re-raised only nits) looks the same
96/// as one that is spinning, for exactly one round. Two in a row is where the
97/// two stop being distinguishable, and a review round on this workload has
98/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
99/// third attempt at a tree that has not moved twice running is pure cost.
100/// This does not touch `review_rounds` itself, which stays the operator's
101/// call.
102pub(crate) const STAGNANT_LIMIT: usize = 2;
103
104/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
105/// a base that moved before giving up and leaving the run `Blocked` for a
106/// person.
107///
108/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
109/// that keeps moving faster than a run can catch it is not something more
110/// rebasing fixes, it is a person's call. Not the same *number as*
111/// `land_rounds` - this budget is spent before a pull request exists, land's
112/// after - but bounded for the identical reason, so it uses the same
113/// default. Counted across both call sites in [`Runner::finish_after_tally`]
114/// (once before review, once before the gate), because either one finding
115/// the base still moving is the same signal.
116pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
117
118/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
119/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
120/// reply held no [`FixReport`].
121///
122/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
123/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
124/// "I'll pause here until the `cargo make check` background run reports
125/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
126/// No `FixReport` was ever collected from that seat, and the run moved on to
127/// the next review round regardless.
128///
129/// Bounded independently of `review_rounds` and `graph.retries`: this
130/// recovers one seat's missing report mid-round, not a new round of review or
131/// an ordinary parse retry, and must not itself become the unbounded wait the
132/// rest of this module exists to avoid.
133const MAX_FIX_CONTINUATIONS: usize = 2;
134
135/// One queued agent invocation.
136///
137/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
138/// CLI hung up on its own stream is asked again from the same job rather than
139/// rebuilt from scratch. See [`Runner::resume_undelivered`].
140#[derive(Clone)]
141struct SeatJob {
142    spec: AgentSpec,
143    seat: SeatState,
144    cwd: PathBuf,
145    prompt: String,
146    timeout: Duration,
147    allow_write: bool,
148    sessions: bool,
149    artifacts: PathBuf,
150    stem: String,
151    /// The prompt for a seat that has been handed to another roster agent
152    /// (a fresh session): everything the original seat would have
153    /// remembered. `None` when `prompt` already carries it, as the first
154    /// ranking and the implement prompt do. Never a resume-style prompt.
155    handover: Option<String>,
156}
157
158/// How the graph reads one agent invocation.
159///
160/// Quota is split out from an ordinary failure on purpose: a rate-limited call
161/// is known to fail again if retried now, so the retry loop must not spend an
162/// attempt on it. `Dropped` is split out for the opposite reason: unlike
163/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
164/// error JSON, never the agent's answer — a caller that matched only
165/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
166/// left to read that JSON as if it were usable output. `resume_undelivered`
167/// is the only caller that acts on it; everywhere else it is reported like an
168/// ordinary failure.
169enum AgentOutcome {
170    /// A usable output.
171    Ok(AgentOutput),
172    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
173    Quota(AgentOutput),
174    /// The CLI hung up on its own stream after billed work. See
175    /// [`agent::AgentOutput::work_undelivered`].
176    Dropped(AgentOutput),
177    /// Any other failure: a timeout, a bad exit code, an empty reply.
178    Failed(String),
179    /// A resource prevented admission or interrupted execution. Not an agent
180    /// failure: never advance a fallback chain or spend an attempt on it.
181    /// Post-spawn interruptions carry a typed error into wave, which records
182    /// implementation preservation before returning this outcome. This outcome
183    /// alone is not proof that no source changes were made.
184    /// [`RunState::resource_block`] says why.
185    ResourceBlocked(String),
186}
187
188/// A request to park the run at its next node boundary.
189///
190/// Cloning is how the request travels: the loop keeps one handle and hands a
191/// clone to each [`Runner`], and every clone points at the same flag. There
192/// is no channel because there is nothing to send - the only message is
193/// "park", it is idempotent, and a flag cannot be missed by a receiver that
194/// was not listening yet.
195///
196/// The boundary is what makes this cheap. Every node writes the run's state
197/// before the next one starts, and every node skips what is already recorded:
198/// `prep` returns early once candidates exist, `implement` asks only the seats
199/// with nothing on disk, `judge` returns early once judgements exist. So a
200/// parked run resumes into exactly the node it stopped before, and no agent
201/// work is thrown away. Killing the process mid-node, by contrast, loses
202/// whatever the seats in flight had not yet written - which for an implement
203/// wave is an hour of paid work.
204///
205/// A [`Runner`] watches two independent handles of this type - see
206/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
207/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
208/// clone covering the whole daemon's lifetime and is never asked to un-park,
209/// which is correct exactly because nothing is dispatched after it fires.
210/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
211/// that parks for an interrupted task must go on to run other tasks
212/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
213/// reusing the daemon-wide one.
214#[derive(Debug, Clone, Default)]
215pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
216
217impl Pause {
218    /// A pause nobody has asked for yet.
219    #[must_use]
220    pub fn new() -> Self {
221        Self::default()
222    }
223
224    /// Ask the run to park at its next node boundary. Idempotent.
225    pub fn park(&self) {
226        self.0.store(true, Ordering::SeqCst);
227    }
228
229    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
230    /// fold into the run's own `park` event - so an operator reading the run
231    /// later knows this was a deliberate interrupt rather than a shutdown or
232    /// a binary swap. The first reason recorded wins; a park already in
233    /// flight is not relabelled by a second, unrelated request.
234    pub fn park_because(&self, reason: impl Into<String>) {
235        self.park_for(ParkCause::Interrupt {
236            reason: reason.into(),
237        });
238    }
239
240    /// [`Pause::park`], recording the structured cause. The first cause
241    /// recorded wins, like [`Pause::park_because`].
242    pub fn park_for(&self, cause: ParkCause) {
243        let mut reason_guard = self
244            .1
245            .lock()
246            .unwrap_or_else(std::sync::PoisonError::into_inner);
247        if reason_guard.is_none() {
248            *reason_guard = Some(cause);
249        }
250        drop(reason_guard);
251        self.park();
252    }
253
254    /// Has a park been asked for?
255    #[must_use]
256    pub fn parked(&self) -> bool {
257        self.0.load(Ordering::SeqCst)
258    }
259
260    /// Why the park was asked for, when the caller used [`Pause::park_because`].
261    #[must_use]
262    pub fn reason(&self) -> Option<String> {
263        self.cause().map(|c| c.label())
264    }
265
266    /// The structured cause, when one was recorded.
267    #[must_use]
268    pub fn cause(&self) -> Option<ParkCause> {
269        self.1
270            .lock()
271            .unwrap_or_else(std::sync::PoisonError::into_inner)
272            .clone()
273    }
274}
275
276/// Drives one run.
277pub struct Runner {
278    /// Run state; public so the CLI can report on it.
279    pub state: RunState,
280    roles: ResolvedRoles,
281    sem: Arc<Semaphore>,
282    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
283    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
284    /// this is never the same handle as `interrupt`.
285    pause: Pause,
286    /// Set when `magi serve`'s interrupt scheduler wants this specific run
287    /// parked at its next node boundary, to let a task marked
288    /// [`crate::queue::Task::interrupt`] run alone before this one carries
289    /// on. Unlike `pause`, a fresh, unshared handle per run - see
290    /// [`Runner::watch_interrupt`].
291    interrupt: Pause,
292}
293
294/// Where the branch's own commits start: its merge base with the base branch
295/// as the remote has it now, else with the recorded `base_commit`. A branch
296/// rebased onto a base that moved past `base_commit` would otherwise count
297/// the base's commits as its own under `base_commit..branch`.
298async fn review_base(
299    repo: &Path,
300    remote: &str,
301    base_branch: &str,
302    base_commit: &str,
303    branch: &str,
304) -> String {
305    review_base_checked(repo, remote, base_branch, base_commit, branch)
306        .await
307        .0
308}
309
310/// [`review_base`] plus whether the base was read from a freshly fetched
311/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
312/// never older than `base_commit`'s view of the base), but the answer is then
313/// not trusted to rewrite a pull request's title.
314async fn review_base_checked(
315    repo: &Path,
316    remote: &str,
317    base_branch: &str,
318    base_commit: &str,
319    branch: &str,
320) -> (String, bool) {
321    let tracking = format!("{remote}/{base_branch}");
322    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
323    if git::rev_exists(repo, &tracking).await
324        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
325        && !mb.is_empty()
326    {
327        return (mb, fresh);
328    }
329    let mb = git::merge_base(repo, base_commit, branch)
330        .await
331        .ok()
332        .filter(|mb| !mb.is_empty())
333        .unwrap_or_else(|| base_commit.to_owned());
334    (mb, false)
335}
336
337/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
338/// when git cannot say or finds nothing: a stale list is better than a wrong
339/// or empty one.
340pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
341    if !is_review_run(state) {
342        return;
343    }
344    let base = review_base(
345        &state.repo,
346        &state.config.merge.remote,
347        &state.base_branch,
348        &state.base_commit,
349        branch,
350    )
351    .await;
352    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
353        && !subjects.is_empty()
354        && state.reviewed_commits.as_ref() != Some(&subjects)
355    {
356        state.reviewed_commits = Some(subjects);
357        state.save().ok();
358    }
359}
360
361/// Subjects of the base's commits between the recorded start and the branch's
362/// merge base: what a stale `base_commit..branch` would have mistaken for the
363/// branch's own work.
364async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
365    let (base, trusted) = review_base_checked(
366        &state.repo,
367        &state.config.merge.remote,
368        &state.base_branch,
369        &state.base_commit,
370        branch,
371    )
372    .await;
373    if !trusted {
374        return None;
375    }
376    git::subjects(&state.repo, &state.base_commit, &base)
377        .await
378        .ok()
379}
380
381/// May an adopted pull request's title be replaced with `computed`? Only when
382/// it is empty, magi's own shape, or a base commit's subject that leaked in;
383/// a title a person wrote stays. Never when `computed` is itself a leak.
384pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
385    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
386    if is_leak(computed) {
387        return false;
388    }
389    let cur = current.trim();
390    cur.is_empty()
391        || cur.starts_with(REVIEW_PROMPT_OPENING)
392        || cur.starts_with("chore: land candidate")
393        || cur.starts_with("magi: candidate")
394        || is_leak(cur)
395}
396
397/// The commit a run branches from: the base branch as the remote has it.
398///
399/// Two failures this replaces. A run used to branch off `HEAD` and so refused
400/// to start on a dirty tree, which made `magi serve` decline every task for as
401/// long as the operator had work in progress - most of the time. Branching off
402/// the *local* base branch fixed that and introduced a worse one: `land` merges
403/// the winner on GitHub, nothing updates the local ref, and the next run
404/// branches off a base missing everything the previous runs landed. Two tasks
405/// in a row from a phone would have had the second silently re-implementing
406/// against stale code and opening a pull request that reverted the first.
407///
408/// Only refs move here - no checkout, no local branch, no merge - so it is safe
409/// with uncommitted work in the tree. A machine with no network still starts:
410/// the fetch may fail and the local tip is used with a warning, because
411/// refusing to run offline is a worse failure than running against a base the
412/// operator can see for themselves.
413///
414/// One function, called by both entry points. Two answers to "where does a run
415/// branch from" is the kind of drift nobody notices until a diff is wrong.
416/// Bring the local `branch` in line with `<remote>/<branch>` before a review
417/// checks it out.
418///
419/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
420/// anything other than plain `git push` from this checkout (a jj colocated
421/// workspace, another clone) moves only the remote-tracking ref - so the local
422/// one can be a stale placeholder. It moves only when local is behind the remote or is an
423/// empty placeholder that diverged from it; unpushed local work is kept, and a real
424/// divergence is refused rather than guessed at.
425async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
426    let tracking = format!("{remote}/{branch}");
427    let fetched = git::fetch(repo, remote, branch).await;
428    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
429    let local_exists = git::branch_exists(repo, branch).await?;
430    if !fresh {
431        if !local_exists {
432            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
433        }
434        tracing::warn!(
435            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
436        );
437        return Ok(());
438    }
439    let remote_sha = git::rev_parse(repo, &tracking).await?;
440    if !local_exists {
441        git::git(repo, &["branch", branch, &tracking]).await?;
442        return Ok(());
443    }
444    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
445    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
446        return Ok(());
447    }
448    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
449        // Diverged. `reconcile` settles it only when it can prove nothing is
450        // lost: a local tip that is the remote's change rebased is pushed over
451        // it (lease pinned to the tip read here), a tip whose every extra
452        // commit is empty is a placeholder the remote's work replaced, and
453        // anything else is two different changes - a question for a person.
454        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
455            .await?
456        {
457            crate::reconcile::Reconciliation::Pushed => {
458                tracing::warn!(
459                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
460                    short(&local_sha),
461                    short(&remote_sha)
462                );
463                return Ok(());
464            }
465            crate::reconcile::Reconciliation::Placeholder => {}
466            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
467        }
468    }
469    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
470    if !out.ok() {
471        bail!(
472            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
473            short(&local_sha),
474            short(&remote_sha),
475            out.stderr
476        );
477    }
478    tracing::warn!(
479        "local `{branch}` was stale: fast-forwarded {} -> {}",
480        short(&local_sha),
481        short(&remote_sha)
482    );
483    Ok(())
484}
485
486async fn resolve_base(
487    repo: &Path,
488    base_branch: &str,
489    remote: &str,
490    coordination: Option<&crate::config::Coordination>,
491) -> Result<crate::run::FetchedBase> {
492    let _lease = crate::repo_lock::SeatLease::operation_with(
493        repo,
494        coordination,
495        &crate::repo_lock::WaitPolicy::current(),
496    )
497    .await?;
498    let tracking = format!("{remote}/{base_branch}");
499    let fetched = git::fetch(repo, remote, base_branch).await;
500    if let Ok(out) = &fetched
501        && out.ok()
502        && git::rev_exists(repo, &tracking).await
503    {
504        return Ok(crate::run::FetchedBase {
505            remote: remote.to_owned(),
506            branch: base_branch.to_owned(),
507            commit: git::rev_parse(repo, &tracking).await?,
508            fetched_at: jiff::Timestamp::now(),
509        });
510    }
511    let why = match &fetched {
512        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
513        Ok(_) => format!("{remote} has no {base_branch}"),
514        Err(e) => e.to_string(),
515    };
516    // No fallback to the local branch: it may be behind, and branching off an
517    // old commit is the stale-checkout bug this check exists to prevent.
518    bail!(
519        "cannot read {tracking} ({why}); refusing to branch off the local \
520         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
521         base / remote in magi.toml. This is launcher preparation: check the \
522         launcher's network, Git access and repository coordination before \
523         retrying"
524    )
525}
526
527/// Outcome of the shared fixer chain, before caller-owned stop policy.
528enum FixStep {
529    Resource,
530    Recorded { report_lost: bool },
531}
532
533/// Exclusive claim shared by targeted repairs and repository reassignment.
534/// Held before asynchronous fix preflight and released on every return or panic.
535///
536/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
537/// manual `magi fix` invocations against the same run are otherwise
538/// invisible to each other and would race to remove and recreate the same
539/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
540/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
541/// which is only ever reclaimed later, out of band, by
542/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
543/// `magi fix` invocation is not necessarily running under either of those, so
544/// nothing would ever sweep a lock a killed or crashed process left behind.
545/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
546/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
547/// lease use: an unreadable or unparsable pid, or a liveness query the
548/// platform cannot answer, reads as alive and the lock is left in place.
549pub(crate) struct FixClaim {
550    path: PathBuf,
551}
552
553impl FixClaim {
554    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
555        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
556        let path = dir.join("fix.lock");
557        let retry = crate::lock_file::Retry::new(None);
558        match Self::create(&path, retry) {
559            Ok(claim) => Ok(claim),
560            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
561                if Self::reclaim_if_dead(&path) {
562                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
563                } else {
564                    bail!(
565                        "another repair or `magi fix` is already running for this run ({} exists)",
566                        path.display()
567                    )
568                }
569            }
570            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
571        }
572    }
573
574    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
575        let mut f = retry.create(path)?;
576        use std::io::Write as _;
577        // Read back by `reclaim_if_dead` on a later, stuck invocation.
578        writeln!(f, "{}", std::process::id())?;
579        Ok(Self {
580            path: path.to_owned(),
581        })
582    }
583
584    /// True if the lock named a process confirmed dead, in which case it was
585    /// also removed. Never true on an unreadable file, an unparsable pid, or
586    /// a liveness query the platform cannot answer — see this type's own doc.
587    fn reclaim_if_dead(path: &Path) -> bool {
588        let dead = std::fs::read_to_string(path)
589            .ok()
590            .and_then(|body| body.trim().parse::<u32>().ok())
591            .is_some_and(|pid| !crate::proc::pid_alive(pid));
592        dead && std::fs::remove_file(path).is_ok()
593    }
594}
595
596impl Drop for FixClaim {
597    fn drop(&mut self) {
598        let _ = std::fs::remove_file(&self.path);
599    }
600}
601
602#[doc(hidden)]
603pub struct ExecutionLeaseGuard {
604    _lease: crate::driver::ExecutionLease,
605}
606
607#[doc(hidden)]
608pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
609    Ok(ExecutionLeaseGuard {
610        _lease: crate::driver::maintenance(home, run_id)?,
611    })
612}
613
614/// Holds the mutable runner as well as its durable lease: cancellation must
615/// clear both copies of ownership, including state a caller may save later.
616struct DriverExecution<'a> {
617    runner: &'a mut Runner,
618    driver: crate::driver::DriverGuard,
619}
620
621impl Drop for DriverExecution<'_> {
622    fn drop(&mut self) {
623        self.driver.release_local(&mut self.runner.state);
624    }
625}
626
627fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
628    if let Some(startup) = &mut state.startup {
629        startup.stage = stage.to_owned();
630    }
631    state.save()
632}
633
634/// Keep a reservation visible as blocked until startup finishes. A killed process
635/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
636struct StartupGuard {
637    id: String,
638    armed: bool,
639}
640
641impl StartupGuard {
642    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
643        state.startup = Some(crate::run::Startup {
644            kind: kind.to_owned(),
645            branch: branch.map(str::to_owned),
646            stage: "reserved".to_owned(),
647            complete: false,
648            failure: None,
649        });
650        state.status = RunStatus::Blocked;
651        state.reserve()?;
652        Ok(Self {
653            id: state.id.clone(),
654            armed: true,
655        })
656    }
657
658    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
659        startup_stage(state, stage)
660    }
661
662    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
663        let result = result.and_then(|()| {
664            state.startup.as_mut().expect("reserved startup").complete = true;
665            state.save()
666        });
667        self.armed = false;
668        match result {
669            Ok(()) => Ok(()),
670            Err(error) => {
671                let startup = state.startup.as_mut().expect("reserved startup");
672                startup.complete = false;
673                startup.failure = Some(format!("{error:#}"));
674                let context = crate::run::StartupFailure {
675                    run: state.id.clone(),
676                    stage: startup.stage.clone(),
677                };
678                // Repository assets may remain. Never infer that a failed startup
679                // is safe to resume or that an earlier owner has been restored.
680                state.status = RunStatus::Failed;
681                state.driver_exited = true;
682                state.event(
683                    "startup-failed",
684                    format!("{context}: {error:#}; retained assets require inspection"),
685                );
686                if let Err(save) = state.save() {
687                    tracing::warn!(
688                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
689                        state.id
690                    );
691                }
692                Err(error.context(context))
693            }
694        }
695    }
696}
697
698impl Drop for StartupGuard {
699    fn drop(&mut self) {
700        if self.armed
701            && let Ok(mut state) = RunState::load(&self.id)
702        {
703            state.status = RunStatus::Blocked;
704            state.driver_exited = true;
705            if let Some(startup) = &mut state.startup {
706                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
707            }
708            state.event(
709                "startup-interrupted",
710                "startup did not finish; inspect retained assets before recovery",
711            );
712            if let Err(error) = state.save() {
713                tracing::error!(
714                    "could not record interrupted startup {}: {error:#}",
715                    self.id
716                );
717            }
718        }
719    }
720}
721
722impl Runner {
723    /// A queue-side failure after construction must not strand an unexecuted run.
724    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
725        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
726            return error;
727        }
728        if let Some(startup) = &mut self.state.startup {
729            startup.stage = stage.to_owned();
730        } else {
731            // A resumed run already has execution history: do not rewrite it.
732            return error;
733        }
734        StartupGuard {
735            id: self.state.id.clone(),
736            armed: true,
737        }
738        .finish(&mut self.state, Err(error))
739        .expect_err("startup failed")
740    }
741
742    /// Start a fresh run against `repo`.
743    pub async fn start(
744        repo: &Path,
745        instruction: String,
746        config: Config,
747        origin: Origin,
748    ) -> Result<Self> {
749        Self::start_naming(repo, instruction, "", config, origin).await
750    }
751
752    /// [`Runner::start`] for a queued task. Titles and instructions never
753    /// select implementation sources. The title argument is retained for callers.
754    pub async fn start_naming(
755        repo: &Path,
756        instruction: String,
757        _also_scan: &str,
758        config: Config,
759        origin: Origin,
760    ) -> Result<Self> {
761        let repo = git::toplevel(repo).await?;
762        let missing = agent::missing_programs(&config.agents);
763        if !missing.is_empty() {
764            bail!(
765                "these agent programs are not on PATH: {}. Fix the roster in \
766                 magi.toml or install them.",
767                missing.join(", ")
768            );
769        }
770        let base_branch =
771            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
772                .await?;
773        let fetched_base = resolve_base(
774            &repo,
775            &base_branch,
776            &config.merge.remote,
777            config.coordination.as_ref(),
778        )
779        .await?;
780        let base_commit = fetched_base.commit.clone();
781        let roles = config.resolve_roles()?;
782        let max_parallel = config.graph.max_parallel.max(1);
783        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
784        // Capture task identity and repository assignment before the first
785        // save, so publication scope survives crashes and later task moves.
786        state.fetched_base = Some(fetched_base);
787        state.set_origin(origin)?;
788        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
789        state.status = RunStatus::Prep;
790        state.event("start", format!("run {} created", state.id));
791        startup.finish(&mut state, Ok(()))?;
792        Ok(Self {
793            state,
794            roles,
795            sem: Arc::new(Semaphore::new(max_parallel)),
796            pause: Pause::new(),
797            interrupt: Pause::new(),
798        })
799    }
800
801    /// Open a review-only run against work that already exists on `branch`.
802    ///
803    /// The expensive half of the graph is the implement wave — measured at
804    /// 111 and 134 internal tool-loop turns on this repository, against a
805    /// handful for a judge or a reviewer. The cheap half is worth running on
806    /// hand-written work too, and there was no way to reach it.
807    ///
808    /// No new state and no schema change are needed: a run with **one** viable
809    /// candidate and a tally already decided degrades `execute` to exactly
810    /// review → gate → merge, because `judge` skips a single-candidate field,
811    /// `deliberate` has fewer than two first choices to reconcile, `vote`
812    /// returns early, `tally` is already present and `fold_losers` has no
813    /// losers. Resuming such a run therefore does the right thing as well.
814    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
815        Self::review_taking_over(repo, branch, config, None, origin).await
816    }
817
818    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
819    /// at the same task still has `branch` checked out, its worktree is
820    /// released first if that is safe (see [`crate::handover`]), and the
821    /// review refuses with the reason if it is not. `None` is a hand-run
822    /// review: it has no earlier attempts, so only a worktree of a dead run
823    /// magi recorded itself can be released.
824    pub async fn review_taking_over(
825        repo: &Path,
826        branch: &str,
827        config: Config,
828        takeover: Option<crate::handover::Takeover>,
829        origin: Origin,
830    ) -> Result<Self> {
831        let repo = git::toplevel(repo).await?;
832        let missing = agent::missing_programs(&config.agents);
833        if !missing.is_empty() {
834            bail!(
835                "these agent programs are not on PATH: {}. Fix the roster in \
836                 magi.toml or install them.",
837                missing.join(", ")
838            );
839        }
840        let base_branch =
841            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
842                .await?;
843        if base_branch == branch {
844            bail!("`{branch}` is the base branch; there is nothing to review against");
845        }
846        let fetched_base = resolve_base(
847            &repo,
848            &base_branch,
849            &config.merge.remote,
850            config.coordination.as_ref(),
851        )
852        .await?;
853        let base_commit = fetched_base.commit.clone();
854
855        let roles = config.resolve_roles()?;
856        let max_parallel = config.graph.max_parallel.max(1);
857        let mut state = RunState::new(
858            repo.clone(),
859            base_branch,
860            base_commit.clone(),
861            format!("Review the work already on branch `{branch}`."),
862            config,
863        );
864        state.fetched_base = Some(fetched_base);
865        state.set_origin(origin)?;
866        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
867        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
868        let opened = async {
869            startup.stage(&mut state, "handover")?;
870
871            // Released before anything else touches the branch: a stale local
872            // branch is moved with `git branch -f`, which git refuses while an
873            // earlier attempt's worktree still has it checked out. Everything
874            // after this point that can fail puts the old run back.
875            // A hand-run review has no task, hence no earlier attempts, but a
876            // worktree of a dead run magi made may still be released.
877            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
878                earlier: Vec::new(),
879                home: crate::run::home(),
880                choice: None,
881                task_instruction: None,
882            });
883            let wait = repository_wait(&state, None);
884            let coordination_config = state.config.coordination.clone();
885            let coordination =
886                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
887                    .await?;
888            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
889            if let Some(released) = &released {
890                state.event(
891                    "release",
892                    format!(
893                        "took `{branch}` over from run {}: its worktree was released: {}",
894                        crate::run::short_of(&released.old_id),
895                        released.audit
896                    ),
897                );
898            }
899            let opened = async {
900                startup.stage(&mut state, "review-preflight")?;
901                // The owner's answer to an earlier divergence question is applied
902                // here: after the release (git will not move a checked-out branch)
903                // and before the sync that would otherwise ask again.
904                state.foreign_checkout = crate::handover::preflight_review(
905                    &repo,
906                    branch,
907                    &takeover.home,
908                    &state.config.merge.remote,
909                )
910                .await?;
911                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
912                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
913                }
914                if let Some(choice) = takeover.choice.as_ref()
915                    && let Err(e) =
916                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
917                            .await
918                {
919                    return Err(e.context("applying the owner's answer about the diverged branch"));
920                }
921                // An earlier attempt of this task that published the task head, and
922                // whose work is the branch under review, hands that head over: the
923                // review run updates the same pull request. Without one (a legacy
924                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
925                // own head and its own open pull request is adopted as before.
926                for id in takeover.earlier.iter().rev() {
927                    if let Ok(old) = RunState::load_under(id, &takeover.home)
928                        && let Some(head) = old.pr_head.clone()
929                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
930                    {
931                        state.pr_head = Some(head);
932                        break;
933                    }
934                }
935                drop(coordination);
936                startup.stage(&mut state, "open-review")?;
937                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
938            }
939            .await;
940            if opened.is_err()
941                && let Some(released) = &released
942            {
943                // Restoration is ownership checked and best effort. Keep the original
944                // startup cause even if reacquiring coordination is no longer possible.
945                match crate::repo_lock::SeatLease::operation_with(
946                    &repo,
947                    coordination_config.as_ref(),
948                    &wait,
949                )
950                .await
951                {
952                    Ok(_coordination) => {
953                        released.restore(&repo, branch).await;
954                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
955                            .map(|old| {
956                                format!(
957                                    "predecessor released_to={:?}; candidate path exists={}",
958                                    old.released_to,
959                                    old.candidates.iter().any(|c| {
960                                        c.branch == branch && c.worktree.exists()
961                                    }),
962                                )
963                            })
964                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
965                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
966                    }
967                    Err(error) => {
968                        tracing::warn!(
969                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
970                            state.id
971                        );
972                        state.event(
973                            "startup-restore",
974                            format!("restoration not attempted: {error:#}"),
975                        );
976                    }
977                }
978            }
979            opened
980        }
981        .await;
982        startup.finish(&mut state, opened)?;
983        Ok(Self {
984            state,
985            roles,
986            sem: Arc::new(Semaphore::new(max_parallel)),
987            pause: Pause::new(),
988            interrupt: Pause::new(),
989        })
990    }
991
992    /// Recover exactly the operator-selected public implementation, without touching old sources.
993    pub async fn recover_pr(
994        repo: &Path,
995        task: &str,
996        selection: crate::pr_recovery::Selection,
997        mut config: Config,
998    ) -> Result<Self> {
999        selection.configure(&mut config)?;
1000        let assignment = crate::run::task_assignment_for(task)?;
1001        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1002        let base_branch =
1003            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1004                .await?;
1005        let fetched_base = resolve_base(
1006            repo,
1007            &base_branch,
1008            &config.merge.remote,
1009            config.coordination.as_ref(),
1010        )
1011        .await?;
1012        let base_commit = fetched_base.commit.clone();
1013        selection
1014            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1015            .await?;
1016        Box::pin(selection.verify_source(repo)).await?;
1017        if let Some(proof) = &selection.source_proof {
1018            anyhow::ensure!(
1019                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1020                "source rebase base is outside the fetched landing base"
1021            );
1022        }
1023        let roles = config.resolve_roles()?;
1024        let max_parallel = config.graph.max_parallel.max(1);
1025        let mut state = RunState::new(
1026            repo.to_path_buf(),
1027            base_branch,
1028            base_commit.clone(),
1029            selection.instruction.clone(),
1030            config,
1031        );
1032        state.fetched_base = Some(fetched_base);
1033        state.set_origin(crate::run::Origin::queue(task))?;
1034        state.pr_head = Some(selection.branch.clone());
1035        state.pr_recovery = Some(selection.clone());
1036        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1037    }
1038
1039    async fn open_selected(
1040        repo: &Path,
1041        mut state: RunState,
1042        roles: ResolvedRoles,
1043        max_parallel: usize,
1044        base_commit: String,
1045        selection: crate::pr_recovery::Selection,
1046    ) -> Result<Self> {
1047        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1048        let opened = async {
1049            startup.stage(&mut state, "predecessors")?;
1050            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1051            startup.stage(&mut state, "open-selected")?;
1052            let branch = state.branch_for('A');
1053            let wait = repository_wait(&state, None);
1054            let prepared = async {
1055                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1056                git::git(repo, &["branch", &branch, selection.source()]).await?;
1057                drop(coordination);
1058                anyhow::Ok(())
1059            }
1060            .await;
1061            prepared?;
1062            state.event(
1063                "recovery",
1064                format!(
1065                    "selected implementation {} for {} (public lease {})",
1066                    selection.source(),
1067                    selection.url,
1068                    selection.head
1069                ),
1070            );
1071            let takeover = crate::handover::Takeover {
1072                earlier: Vec::new(),
1073                home: crate::run::home(),
1074                choice: None,
1075                task_instruction: Some(selection.instruction.clone()),
1076            };
1077            state.save()?;
1078            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1079        }
1080        .await;
1081        startup.finish(&mut state, opened)?;
1082        Ok(Self {
1083            state,
1084            roles,
1085            sem: Arc::new(Semaphore::new(max_parallel)),
1086            pause: Pause::new(),
1087            interrupt: Pause::new(),
1088        })
1089    }
1090
1091    /// What the newest earlier attempt that reviewed `branch` leaves for this
1092    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1093    /// no earlier attempts. Reads the earlier record only: ownership of its
1094    /// worktree and branch is [`crate::handover`]'s business.
1095    async fn inherit(
1096        repo: &Path,
1097        branch: &str,
1098        base_commit: &str,
1099        takeover: &crate::handover::Takeover,
1100    ) -> Option<crate::recovery::RecoveryRecord> {
1101        use crate::recovery::{Relation, assess};
1102        let newest = takeover.earlier.last()?;
1103        let mut chosen = None;
1104        for id in takeover.earlier.iter().rev() {
1105            if let Ok(old) = RunState::load_under(id, &takeover.home)
1106                && !old.reviews.is_empty()
1107                && (old.winner().is_some_and(|w| w.branch == branch)
1108                    || old.pr_head.as_deref() == Some(branch))
1109            {
1110                chosen = Some(old);
1111                break;
1112            }
1113        }
1114        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1115            .await
1116            .unwrap_or_default();
1117        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1118            Some(last) if last.head == tip => Relation::Same,
1119            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1120            _ => Relation::Diverged,
1121        };
1122        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1123        Some(assess(from, chosen.as_ref(), base_commit, relation))
1124    }
1125
1126    /// The half of [`Runner::review_taking_over`] that can fail after an
1127    /// earlier attempt's worktree was released.
1128    async fn open_review(
1129        repo: &Path,
1130        branch: &str,
1131        state: &mut RunState,
1132        base_commit: String,
1133        takeover: &crate::handover::Takeover,
1134    ) -> Result<()> {
1135        startup_stage(state, "review-sync")?;
1136        let wait = repository_wait(state, None);
1137        let _coordination = coordinate_operation(state, repo, &wait).await?;
1138        if state.foreign_checkout.is_some() {
1139            // Never reconcile or force-move a ref checked out by the operator.
1140            if state.pr_head.is_none() {
1141                state.pr_head = Some(branch.to_owned());
1142            }
1143        } else if state.pr_recovery.is_none() {
1144            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1145        }
1146        // The commit subjects are the closest thing to a task statement that
1147        // existing work carries, and the reviewers are told as much.
1148        let start = review_base(
1149            repo,
1150            &state.config.merge.remote,
1151            &state.base_branch,
1152            &base_commit,
1153            branch,
1154        )
1155        .await;
1156        let log = git::log_oneline(repo, &start, branch)
1157            .await
1158            .unwrap_or_default();
1159        let log_text = if log.trim().is_empty() {
1160            "(no commit messages)"
1161        } else {
1162            log.trim()
1163        };
1164        let mut instruction = format!(
1165            "Review the work already on branch `{branch}`. There is no task \
1166             statement: what the change claims to do is whatever its commits \
1167             say.\n\n{log_text}"
1168        );
1169        // A retry of a task whose earlier attempt left reviews behind carries
1170        // that attempt's evidence, and the task's own statement with it: the
1171        // completion criteria are the task's, not whatever the commits claim.
1172        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1173            if let Some(task) = takeover
1174                .task_instruction
1175                .as_deref()
1176                .filter(|t| !t.trim().is_empty())
1177                && rec.reviewed_head.is_some()
1178            {
1179                instruction = format!(
1180                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1181                    task.trim()
1182                );
1183                rec.criteria_inherited = true;
1184            }
1185            state.event("recovery", rec.summary());
1186            state.recovery = Some(rec);
1187        }
1188        if let Some(selected) = &state.pr_recovery {
1189            instruction = selected.instruction.clone();
1190        }
1191        state.task_instruction = takeover.task_instruction.clone();
1192        state.instruction = instruction;
1193        state.reviewed_commits = Some(
1194            git::subjects(repo, &start, branch)
1195                .await
1196                .unwrap_or_default(),
1197        );
1198
1199        // A takeover must not forget a hold that a previous review observed,
1200        // even if repairs have since removed it from the branch.
1201        for id in &takeover.earlier {
1202            if let Ok(old) = RunState::load_under(id, &takeover.home)
1203                && old.repo == state.repo
1204                && (old.pr_head.as_deref() == Some(branch)
1205                    || old.winner().is_some_and(|w| w.branch == branch))
1206            {
1207                for hold in old.branch_owner_holds {
1208                    if !state.branch_owner_holds.contains(&hold) {
1209                        state.event(
1210                            "approval-policy",
1211                            format!(
1212                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1213                                hold.control.key(),
1214                                hold.file,
1215                                hold.head
1216                            ),
1217                        );
1218                        state.branch_owner_holds.push(hold);
1219                    }
1220                }
1221            }
1222        }
1223        // Select the actual review tip before observing owner policy. A foreign
1224        // checkout can lag its remote descendant, and repairs must not erase
1225        // holds introduced only on that selected commit.
1226        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1227            let tracking = format!("{}/{branch}", state.config.merge.remote);
1228            // A surviving tracking ref is not evidence that the remote still
1229            // offers this tip. Adopt it only after a successful fetch here.
1230            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1231            let mut head = checkout.synced_head.clone();
1232            if matches!(fetched, Ok(out) if out.ok()) {
1233                let remote = git::rev_parse(repo, &tracking).await?;
1234                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1235                    head = remote;
1236                }
1237            }
1238            head
1239        } else {
1240            git::rev_parse(repo, branch).await?
1241        };
1242        state.observe_branch_owner_holds(&reviewed_head).await;
1243
1244        // An attached worktree, so the fixer's commits land on the branch under
1245        // review rather than on a detached head nobody will look at again.
1246        let worktree = state.worktree_root().join("under-review");
1247        if let Some(parent) = worktree.parent() {
1248            tokio::fs::create_dir_all(parent).await.ok();
1249        }
1250        let path = worktree.to_string_lossy().to_string();
1251        let review_branch = if state.foreign_checkout.is_some() {
1252            let shadow = format!("magi/{}/review", state.short());
1253            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1254            shadow
1255        } else {
1256            branch.to_owned()
1257        };
1258        startup_stage(state, "review-checkout")?;
1259        git::git(repo, &["worktree", "add", &path, &review_branch])
1260            .await
1261            .with_context(|| {
1262                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1263            })?;
1264
1265        startup_stage(state, "worktree-setup")?;
1266        let setup = match ensure_setup_config(state, repo).await {
1267            Ok(()) => {
1268                worktree_setup::prepare_with(
1269                    &state.config,
1270                    repo,
1271                    &worktree,
1272                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1273                )
1274                .await
1275            }
1276            Err(e) => Err(e),
1277        };
1278        if let Err(e) = setup {
1279            git::worktree_remove_clean(repo, &worktree).await.ok();
1280            return Err(e);
1281        }
1282        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1283            .await
1284            .unwrap_or(0);
1285        if commits == 0 {
1286            git::worktree_remove_clean(repo, &worktree).await.ok();
1287            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1288        }
1289        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1290            .await
1291            .map(|f| f.len())
1292            .unwrap_or(0);
1293        if files == 0
1294            && let (Ok(head_tree), Ok(base_tree)) = (
1295                git::tree_of(&worktree, "HEAD").await,
1296                git::tree_of(&worktree, &base_commit).await,
1297            )
1298            && head_tree == base_tree
1299        {
1300            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1301            git::worktree_remove_clean(repo, &worktree).await.ok();
1302            bail!(
1303                "`{branch}` at {} has a tree identical to base {}; this usually means \
1304                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1305                 against `{}/{branch}`) rather than an empty change",
1306                short(&head),
1307                short(&base_commit),
1308                state.config.merge.remote
1309            );
1310        }
1311        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1312            .await
1313            .unwrap_or_default();
1314
1315        state.candidates.push(Candidate {
1316            index: 0,
1317            label: 'A',
1318            // Not an agent id on purpose: nothing in the roster wrote this, and
1319            // the stats tables must not credit anyone with a win for it.
1320            agent: EXISTING_BRANCH.to_owned(),
1321            branch: review_branch,
1322            worktree,
1323            summary: String::new(),
1324            stat,
1325            files,
1326            commits,
1327            empty: false,
1328            failed: None,
1329            verified_noop: None,
1330            duration_ms: 0,
1331            folded: false,
1332        });
1333        state.tally = Some(Tally {
1334            first_choice: BTreeMap::from([('A', 0)]),
1335            borda: BTreeMap::new(),
1336            winner: 'A',
1337            rankings: 0,
1338            unanimous_initial: false,
1339            deliberated: false,
1340            changed_votes: 0,
1341            unanimous_final: false,
1342            tie_break: None,
1343            // No panel sat, so no quorum applies. Zero judges is the correct
1344            // number for work that never competed, and must not be reported as
1345            // a collapsed panel.
1346            judges: 0,
1347            present: 0,
1348            quorum: 0,
1349            met_quorum: true,
1350            uncontested: Some("review-only run: nothing competed".to_owned()),
1351        });
1352        state.status = RunStatus::Reviewing;
1353        state.prep_complete = Some(true);
1354        state.event(
1355            "start",
1356            format!(
1357                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1358                state.id
1359            ),
1360        );
1361        Ok(())
1362    }
1363
1364    /// Authorize one bounded synchronization interval, under the caller's queue task
1365    /// claim and the same owner/execution locks used by run maintenance.
1366    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1367        Self::authorize_base_recovery_request(home, id, task, false, None).await
1368    }
1369
1370    /// Queue release uses its durable approval generation exactly once.
1371    pub(crate) async fn authorize_base_recovery_from_resumption(
1372        home: &Path,
1373        id: &str,
1374        task: &str,
1375    ) -> Result<()> {
1376        Self::authorize_base_recovery_request(home, id, task, true, None).await
1377    }
1378
1379    pub(crate) async fn authorize_base_recovery_control(
1380        home: &Path,
1381        task: &str,
1382        control: &mut crate::base_recovery_control::Transaction,
1383    ) -> Result<()> {
1384        let id = control.request.run.clone();
1385        Self::authorize_base_recovery_request(home, &id, task, false, Some(control)).await
1386    }
1387
1388    async fn authorize_base_recovery_request(
1389        home: &Path,
1390        id: &str,
1391        task: &str,
1392        resumption: bool,
1393        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1394    ) -> Result<()> {
1395        let _owner = crate::pr_head::owner_lock(home, id)?;
1396        let mut state = RunState::load_under(id, home)?;
1397        crate::pr_head::ensure_owner(&state)?;
1398        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1399        anyhow::ensure!(
1400            queued.execution_runs().last().is_some_and(|run| run == id)
1401                && queued.status != crate::queue::TaskStatus::Done
1402                && !queued.fresh_start
1403                && queued.review_branch.is_none(),
1404            "run task ownership changed"
1405        );
1406        anyhow::ensure!(
1407            state
1408                .origin
1409                .as_ref()
1410                .and_then(|o| o.task.as_deref())
1411                .is_none_or(|owner| owner == task),
1412            "run belongs to another task"
1413        );
1414        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1415        anyhow::ensure!(
1416            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1417            "run is live or its ownership is unknown"
1418        );
1419        // Judge the previous driver's lease before acquiring our maintenance
1420        // lease. The owner lock excludes new driver claims across both steps.
1421        let _execution = crate::driver::maintenance(home, id)?;
1422        anyhow::ensure!(
1423            state.status.resumable()
1424                && state.released_to.is_none()
1425                && state.retired_to.is_none()
1426                && state.pr_taken_over_by.is_none(),
1427            "run ownership is final"
1428        );
1429        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1430        anyhow::ensure!(
1431            !state.pr_publication_pending
1432                && !crate::handover::landing_checkpoint(&state)
1433                && state.merge_decision.is_none(),
1434            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1435        );
1436        let winner = state.winner().context("run has no retained winner")?;
1437        anyhow::ensure!(
1438            git::is_clean(&winner.worktree).await?,
1439            "retained worktree has uncommitted changes"
1440        );
1441        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1442        anyhow::ensure!(
1443            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1444            "retained worktree does not match the winner branch"
1445        );
1446        if let Some(control) = control.as_ref() {
1447            anyhow::ensure!(
1448                head.starts_with(&control.request.head),
1449                "retained HEAD changed since the owner request"
1450            );
1451            anyhow::ensure!(
1452                state
1453                    .base_sync_recovery
1454                    .stop
1455                    .as_ref()
1456                    .is_none_or(|stop| stop.head == head),
1457                "retained HEAD differs from the recorded stop head; inspect it first"
1458            );
1459        }
1460        state.ensure_base_episode();
1461        state.record_base_sync_stop(&head);
1462        anyhow::ensure!(
1463            state
1464                .base_sync_recovery
1465                .stop
1466                .as_ref()
1467                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1468            "base recovery refused: missing eligible movement-exhaustion evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1469        );
1470        let fetched =
1471            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1472        anyhow::ensure!(
1473            fetched.ok(),
1474            "cannot authorize base recovery without a fetched base"
1475        );
1476        let approved_tip = git::rev_parse(
1477            &state.repo,
1478            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1479        )
1480        .await?;
1481        if let Some(control) = control.as_deref_mut() {
1482            let queue = crate::queue::Queue::at(home.join("queue"));
1483            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1484            if let Some(prior) = state
1485                .base_sync_recovery
1486                .authorizations
1487                .iter()
1488                .find(|a| a.request.as_deref() == Some(&control.key()))
1489            {
1490                anyhow::ensure!(
1491                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1492                    "recovery request was consumed or invalidated; it cannot queue again"
1493                );
1494                return control.enqueue(&queue);
1495            }
1496        }
1497        if resumption {
1498            anyhow::ensure!(
1499                crate::daemon::compatible_run_instruction(&state, &queued),
1500                "resumption instruction does not match the retained run"
1501            );
1502            let approval = queued
1503                .resumption
1504                .as_ref()
1505                .context("no operator resumption")?;
1506            anyhow::ensure!(
1507                approval.instruction == queued.instruction,
1508                "resumption approval does not match the current task instruction"
1509            );
1510            state.authorize_base_sync_resumption(task, approval)?;
1511        } else {
1512            state.authorize_base_sync(task)?;
1513        }
1514        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1515        state
1516            .base_sync_recovery
1517            .authorizations
1518            .last_mut()
1519            .unwrap()
1520            .scope = Some(crate::base_sync_recovery::Scope {
1521            tip: approved_tip,
1522            instruction: queued.instruction.clone(),
1523            episode,
1524        });
1525        if let Some(control) = control.as_deref_mut() {
1526            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1527            authorization.request = Some(control.key());
1528            authorization.generation = control.generation();
1529            authorization.decision = control.decision();
1530            authorization.question = control
1531                .request
1532                .decision
1533                .as_ref()
1534                .map(|_| control.request.request.clone());
1535        }
1536        state.event(
1537            "base-recovery",
1538            "owner authorized a bounded base synchronization interval; fresh verification required",
1539        );
1540        state.save_under(home)?;
1541        if let Some(control) = control {
1542            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1543        }
1544        Ok(())
1545    }
1546
1547    /// Reopen an existing run.
1548    pub fn resume(id: &str) -> Result<Self> {
1549        let state = RunState::load(id)?;
1550        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1551        if state.startup.as_ref().is_some_and(|s| !s.complete)
1552            || (state.status == RunStatus::Prep
1553                && state.instruction.trim().is_empty()
1554                && state.candidates.is_empty()
1555                && state.prep_complete == Some(false))
1556        {
1557            bail!(
1558                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1559            );
1560        }
1561        crate::pr_head::ensure_owner(&state)?;
1562        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1563            bail!(
1564                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1565            );
1566        }
1567        if let Some(to) = &state.released_to {
1568            bail!(
1569                "run {} cannot be resumed: its worktree was released to run {}",
1570                state.short(),
1571                crate::run::short_of(to)
1572            );
1573        }
1574        let roles = state.config.resolve_roles()?;
1575        if let Some(id) = &state.config.graph.selected_implementer
1576            && state.candidates.iter().any(|c| c.agent != *id)
1577        {
1578            bail!(
1579                "replacement implementer pin does not match the saved candidates; task must stay held"
1580            );
1581        }
1582        let max_parallel = state.config.graph.max_parallel.max(1);
1583        Ok(Self {
1584            state,
1585            roles,
1586            sem: Arc::new(Semaphore::new(max_parallel)),
1587            pause: Pause::new(),
1588            interrupt: Pause::new(),
1589        })
1590    }
1591
1592    /// Walk the graph to a terminal state, skipping nodes already recorded.
1593    ///
1594    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1595    /// the phone - ends here, so this is the one place a run that ended
1596    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1597    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1598    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1599        // Allocate before polling: boxing inside an async wrapper would still
1600        // retain its construction frame while the nested graph is polled.
1601        Box::pin(self.execute_inner(None))
1602    }
1603
1604    pub(crate) async fn execute_sync_only(
1605        &mut self,
1606        request: crate::base_sync_only::Request,
1607    ) -> Result<()> {
1608        Box::pin(self.execute_inner(Some(request))).await
1609    }
1610
1611    async fn execute_inner(
1612        &mut self,
1613        sync_only: Option<crate::base_sync_only::Request>,
1614    ) -> Result<()> {
1615        anyhow::ensure!(
1616            self.state.startup.as_ref().is_none_or(|s| s.complete),
1617            "startup incomplete; inspect retained evidence before explicit recovery"
1618        );
1619        if let Some(selection) = &self.state.pr_recovery
1620            && (selection.source_proof.is_some() || selection.source_run.is_some())
1621        {
1622            Box::pin(selection.verify_source(&self.state.repo)).await?;
1623        }
1624        // Queue claims cover daemon work; this also serializes manual drivers
1625        // consuming a repair answer, including the new review and decision.
1626        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1627            || self.state.land_approval.is_some()
1628            || self.state.merge_decision.is_some()
1629            || !self.state.merge_repairs.is_empty()
1630            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1631        {
1632            let claim = FixClaim::acquire(&self.state.dir())?;
1633            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1634            let disk = RunState::load(&self.state.id)?;
1635            let checkpoint = |s: &RunState| {
1636                (
1637                    s.merge_repairs.len(),
1638                    s.merge_repairs
1639                        .last()
1640                        .map(|r| (r.question.clone(), r.phase)),
1641                    s.land_approval
1642                        .as_ref()
1643                        .map(|a| (a.question.clone(), a.head.clone())),
1644                )
1645            };
1646            if checkpoint(&disk) != checkpoint(&self.state) {
1647                bail!(
1648                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1649                );
1650            }
1651            Some(claim)
1652        } else {
1653            None
1654        };
1655        let base_only = sync_only.is_some();
1656        let mut execution = self.claim_driver(sync_only).await?;
1657        let runner = &mut *execution.runner;
1658        let wait = runner.repository_wait();
1659        // Keep the graph's large future off the callers' stack, including
1660        // standalone task attempts running on a default-sized test thread.
1661        let result = if base_only {
1662            wait.scope(Box::pin(async {
1663                let repo = runner.state.repo.clone();
1664                let result = async {
1665                    let _coordination = runner.coordinate(&repo).await?;
1666                    anyhow::ensure!(
1667                        !runner.pause.parked() && !runner.interrupt.parked(),
1668                        "paused before base synchronization"
1669                    );
1670                    crate::base_sync_only::sync(&mut runner.state).await
1671                }
1672                .await;
1673                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1674                pass.result = match result {
1675                    Ok(outcome) => outcome,
1676                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1677                };
1678                let summary = pass.summary();
1679                runner.state.event("base-sync-only", summary);
1680                runner.state.save()
1681            }))
1682            .await
1683        } else {
1684            wait.scope(Box::pin(runner.execute_graph())).await
1685        };
1686        let result = match result {
1687            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1688                record_repository_block(&mut runner.state, &e);
1689                runner.park_here()?;
1690                Ok(())
1691            }
1692            other => other,
1693        };
1694        execution.driver.finish(&mut runner.state).await?;
1695        let ended = if result.is_err() {
1696            Some({
1697                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1698                if let Err(error) = &result {
1699                    notice.message = format!(
1700                        "Run {} stopped with an error: {}",
1701                        runner.state.id,
1702                        error.to_string().lines().next().unwrap_or("unknown error")
1703                    );
1704                }
1705                notice
1706            })
1707        } else {
1708            crate::notices::run_ended(&runner.state)
1709        };
1710        if let Some(notice) = ended {
1711            crate::notices::raise(notice);
1712        }
1713        result
1714    }
1715
1716    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1717        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1718    }
1719
1720    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1721        let wait = self.repository_wait();
1722        coordinate_operation(&mut self.state, cwd, &wait).await
1723    }
1724
1725    /// Validate ownership and persist the driver claim in one critical section.
1726    async fn claim_driver(
1727        &mut self,
1728        sync_only: Option<crate::base_sync_only::Request>,
1729    ) -> Result<DriverExecution<'_>> {
1730        let owner = match crate::pr_head::owner_lock_wait(
1731            &crate::run::home(),
1732            &self.state.id,
1733            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1734        )
1735        .await
1736        {
1737            Ok(owner) => owner,
1738            Err(error) => {
1739                let detail = format!("worktree maintenance or ownership update: {error:#}");
1740                // Admission did not own run.json: retain this resource outcome
1741                // in memory for queue settlement without overwriting a concurrent
1742                // retirement or publication transaction.
1743                self.state.resource_block = Some(crate::run::ResourceBlock {
1744                    cause: crate::run::ResourceBlockCause::Other,
1745                    node: "start".into(),
1746                    kind: "worktree maintenance".into(),
1747                    detail: detail.clone(),
1748                    at: Timestamp::now(),
1749                });
1750                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1751            }
1752        };
1753        let disk = RunState::load(&self.state.id)?;
1754        crate::pr_head::ensure_owner(&disk)?;
1755        let claimed =
1756            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1757        // Only proven-live ownership refuses here. Unknown records (legacy runs
1758        // with no claim marker or process identity) fall through to the
1759        // exclusive execution lease taken just below, which is what actually
1760        // keeps a second driver out.
1761        anyhow::ensure!(
1762            disk.liveness(claimed) != crate::run::Liveness::Live,
1763            "run already has a live driver; wait for its execution to end"
1764        );
1765        if let Some(to) = &disk.released_to {
1766            bail!(
1767                "run {} cannot continue: its worktree was released to run {}",
1768                self.state.short(),
1769                crate::run::short_of(to)
1770            );
1771        }
1772        anyhow::ensure!(
1773            serde_json::to_value(&disk.base_sync_recovery)?
1774                == serde_json::to_value(&self.state.base_sync_recovery)?,
1775            "base recovery changed since this run was loaded; reload the saved run"
1776        );
1777        anyhow::ensure!(
1778            disk.sync_only_passes == self.state.sync_only_passes,
1779            "base-only synchronization changed since this run was loaded; reload the saved run"
1780        );
1781        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1782        let mut execution = DriverExecution {
1783            runner: self,
1784            driver,
1785        };
1786        // Declare after the execution guard: on any claim error this short
1787        // lock must drop before that guard reloads and releases ownership.
1788        let _owner = owner;
1789        if let Some(request) = sync_only {
1790            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1791            anyhow::ensure!(
1792                request.run == disk.id,
1793                "sync-base-only request targets a different run"
1794            );
1795            let state = &mut execution.runner.state;
1796            let task_entry = state.next_pass_task_entry;
1797            *state = disk;
1798            state.next_pass_task_entry = task_entry;
1799            if state.pending_sync_only().is_some() {
1800                let pass_index = state.passes.len();
1801                let pass = state.sync_only_passes.last_mut().unwrap();
1802                anyhow::ensure!(
1803                    pass.request == request,
1804                    "interrupted base-only synchronization belongs to a different request"
1805                );
1806                pass.pass_index = pass_index;
1807            } else {
1808                let pass = crate::base_sync_only::Pass::new(request, state);
1809                state.sync_only_passes.push(pass);
1810            }
1811            if state.status == RunStatus::Failed {
1812                state.status = RunStatus::Blocked;
1813            }
1814        } else {
1815            anyhow::ensure!(
1816                disk.pending_sync_only().is_none(),
1817                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1818            );
1819            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1820                .await?;
1821        }
1822        let state = &mut execution.runner.state;
1823        // Moving again, so it is no longer parked. Set before the walk rather
1824        // than in `resume`, so every way of re-entering the graph clears it
1825        // and a card cannot claim a run is waiting to be resumed while the
1826        // agents are already working.
1827        state.parked = false;
1828        state.resource_wait = None;
1829        state.resource_block = None;
1830        // Any seat this state still lists as answering belongs to whatever
1831        // process last drove this run — this one included, if it crashed
1832        // mid-wave. Cleared and flushed immediately, before anything else
1833        // runs, so a resume can never show a seat as live when nothing is
1834        // asking it anything yet; the node that actually dispatches the next
1835        // wave repopulates it.
1836        state.clear_active();
1837        // Recorded in the same spot, and flushed together with the clear
1838        // above: this is the pid a reader checks (`RunState::liveness`) when
1839        // no daemon claim exists to answer "is a process still driving this
1840        // run" — a plain `magi run` / `magi review` typed into a terminal
1841        // claims nothing there. Always overwritten, never only-if-absent, so
1842        // a resumed run's stale pid from a previous, possibly-dead process
1843        // can never survive into this one's own report. Unlike
1844        // `clear_active`, this changes on every single `execute()` call, so
1845        // the save below is now unconditional rather than only-if-cleared.
1846        //
1847        // `driver_started_at` is recorded in the same breath, from this same
1848        // pid, so `liveness` can tell a live pid that is genuinely still us
1849        // apart from one the OS has since handed to an unrelated process —
1850        // see that field's own doc for why the pid alone is not enough.
1851        let pid = std::process::id();
1852        state.driver_pid = Some(pid);
1853        state.driver_started_at = crate::proc::process_started_at(pid);
1854        state.driver_exited = false;
1855        state.driver_claimed = Some(true);
1856        state.begin_pass();
1857        execution.driver.bind(state);
1858        state.save()?;
1859        execution.driver.record(state)?;
1860        Ok(execution)
1861    }
1862
1863    /// No conflict checkpoint proves dispatch was never reached. End that
1864    /// consumed generation so an owner can explicitly authorize a fresh one.
1865    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1866        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1867        if let Err(error) = &result
1868            && !error.is::<crate::repo_lock::ResourceBlocked>()
1869            && self
1870                .state
1871                .repair_grants
1872                .last()
1873                .is_some_and(|g| g.conflict.is_none())
1874        {
1875            self.state.repair_grants.last_mut().unwrap().phase =
1876                crate::repair_budget::Phase::Complete;
1877            self.state.status = RunStatus::Blocked;
1878            self.state.save()?;
1879            bail!(
1880                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1881                self.state.passes.last().map_or(0, |p| p.index)
1882            );
1883        }
1884        result
1885    }
1886
1887    /// A grant owns only these repair attempts. Confirmation reviews cannot
1888    /// create another fixer allowance, and every operation is restart-checkpointed.
1889    async fn execute_granted_repair(&mut self) -> Result<()> {
1890        use crate::repair_budget::{Kind, Phase};
1891        let index = self.state.repair_grants.len() - 1;
1892        let winner = self
1893            .state
1894            .winner()
1895            .cloned()
1896            .context("repair winner missing")?;
1897        loop {
1898            let grant = self.state.repair_grants[index].clone();
1899            match grant.phase {
1900                Phase::Pending => {
1901                    if grant.spent >= grant.receipt.request.rounds {
1902                        self.state.repair_grants[index].phase = Phase::Complete;
1903                        self.state.status = RunStatus::Blocked;
1904                        self.state.save()?;
1905                        return Ok(());
1906                    }
1907                    // Reserve before dispatch. A crash can consume an attempt,
1908                    // but can never duplicate it or reset saved fixer history.
1909                    self.state.repair_grants[index].spent += 1;
1910                    self.state.repair_grants[index].phase = Phase::Fixing;
1911                    self.state.save()?;
1912                    match grant.receipt.request.kind {
1913                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1914                        Kind::Gate => {
1915                            let failed = self.state.gate.clone();
1916                            let _ = self.gate_fix_round(&winner, &failed).await?;
1917                        }
1918                        Kind::Review => {
1919                            let mut record = self
1920                                .state
1921                                .reviews
1922                                .last()
1923                                .cloned()
1924                                .context("review failure missing")?;
1925                            let round = record.round;
1926                            let step = self.run_fix_round(&winner, &mut record).await?;
1927                            self.state.reviews[round - 1] = record;
1928                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1929                                self.state.repair_grants[index].phase = Phase::Complete;
1930                                self.state.status = RunStatus::Blocked;
1931                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1932                                self.state.save()?;
1933                                return Ok(());
1934                            }
1935                            if matches!(step, FixStep::Resource) {
1936                                self.stop_for_resource()?;
1937                                return Ok(());
1938                            }
1939                            self.state.save()?;
1940                        }
1941                    }
1942                    if self.resource_halt()? {
1943                        return Ok(());
1944                    }
1945                }
1946                Phase::Fixing => {
1947                    if grant.receipt.request.kind == Kind::BaseConflict {
1948                        self.repair_base_conflict(false).await?;
1949                    }
1950                    // Interrupted fixers may have left source changes or an
1951                    // unpushed commit. Preserve them before fresh assessment.
1952                    let _coordination = self.coordinate(&winner.worktree).await?;
1953                    let rescued = git::rescue_commit(
1954                        &winner.worktree,
1955                        "magi: preserve interrupted granted repair",
1956                    )
1957                    .await?;
1958                    self.state.note_withheld("repair-grant", &rescued.withheld);
1959                    // Fresh checks must supersede even a same-head failure.
1960                    // Archive rather than erase failure evidence or counters.
1961                    self.state
1962                        .verification_history
1963                        .push(crate::run::VerificationEvidence {
1964                            superseded_by: None,
1965                            archived_at: Some(Timestamp::now()),
1966                            fixes_spent: Some(self.state.gate_fixes.len()),
1967                            gate_head: self.state.gate_head.take(),
1968                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1969                            gate: std::mem::take(&mut self.state.gate),
1970                            e2e: self.state.head_e2e.take(),
1971                        });
1972                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1973                        self.state
1974                            .verification_history
1975                            .push(crate::run::VerificationEvidence {
1976                                superseded_by: None,
1977                                archived_at: Some(Timestamp::now()),
1978                                fixes_spent: Some(self.state.gate_fixes.len()),
1979                                gate_head: None,
1980                                gate_ran: false,
1981                                gate: Vec::new(),
1982                                e2e: Some(e2e),
1983                            });
1984                    }
1985                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1986                    self.state.repair_grants[index].head =
1987                        git::rev_parse(&winner.worktree, "HEAD").await?;
1988                    self.state.repair_grants[index].phase = Phase::Reviewing;
1989                    if grant.receipt.request.kind == Kind::BaseConflict {
1990                        self.state.base_sync_recovery.stop = None;
1991                        if let Some(sync) = &mut self.state.base_sync {
1992                            sync.tip = grant
1993                                .receipt
1994                                .request
1995                                .tip
1996                                .clone()
1997                                .context("repair base tip missing")?;
1998                            sync.conflict = None;
1999                            sync.behind = 0;
2000                        }
2001                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2002                    }
2003                    self.state.save()?;
2004                }
2005                Phase::Reviewing => {
2006                    self.review_loop_pass().await?;
2007                    if self.resource_halt()? {
2008                        return Ok(());
2009                    }
2010                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2011                    let clean = self.state.reviews.len() > grant.review_start
2012                        && self.state.reviews.last().is_some_and(|r| {
2013                            r.head == head
2014                                && r.clean
2015                                && r.expected > 0
2016                                && r.answered == r.expected
2017                                && matches!(
2018                                    r.e2e_status(),
2019                                    E2eStatus::Passed | E2eStatus::NotConfigured
2020                                )
2021                        });
2022                    if !clean {
2023                        // A confirmation review carries no additional fix budget.
2024                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2025                            == Kind::Review
2026                            && grant.spent < grant.receipt.request.rounds
2027                            && self.state.reviews.last().is_some_and(|r| {
2028                                r.fix.is_none()
2029                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2030                            }) {
2031                            Phase::Pending
2032                        } else {
2033                            Phase::Complete
2034                        };
2035                        self.state.status = RunStatus::Blocked;
2036                        self.state.event(
2037                            "repair-grant",
2038                            "fresh review did not clear the repaired head; no publication",
2039                        );
2040                        self.state.save()?;
2041                        if self.state.repair_grants[index].phase == Phase::Pending {
2042                            continue;
2043                        }
2044                        return Ok(());
2045                    }
2046                    self.state.repair_grants[index].phase = Phase::Gating;
2047                    self.state.save()?;
2048                }
2049                Phase::Gating => {
2050                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2051                    self.state.reconcile_verification_head(&head);
2052                    let wait = self.repository_wait();
2053                    if self
2054                        .state
2055                        .reviews
2056                        .last()
2057                        .is_none_or(|r| r.head != head || !r.clean)
2058                    {
2059                        self.state.status = RunStatus::Blocked;
2060                        self.state.repair_grants[index].phase = Phase::Complete;
2061                        self.state.event(
2062                            "repair-grant",
2063                            "head changed since fresh review; repair held",
2064                        );
2065                        self.state.save()?;
2066                        return Ok(());
2067                    }
2068                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2069                        return Ok(());
2070                    }
2071                    let outcomes = self.run_gate(&winner).await?;
2072                    if verify_inconclusive(&outcomes) {
2073                        return Ok(());
2074                    }
2075                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2076                    if after != head {
2077                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2078                        self.state.repair_grants[index].head = after;
2079                        self.state.repair_grants[index].phase = Phase::Reviewing;
2080                        self.state.status = RunStatus::Blocked;
2081                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2082                        self.state.save()?;
2083                        return Ok(());
2084                    }
2085                    let passed = outcomes.iter().all(CommandOutcome::ok);
2086                    // Follow-up grants owe the same guarded checkout delivery
2087                    // as the conflict repair that introduced the new head.
2088                    if passed
2089                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2090                    {
2091                        return Ok(());
2092                    }
2093                    self.state.repair_grants[index].succeeded = passed;
2094                    self.state.gate = outcomes;
2095                    self.state.gate_ran = true;
2096                    self.state.status = if passed {
2097                        RunStatus::Gating
2098                    } else {
2099                        RunStatus::Blocked
2100                    };
2101                    self.state.repair_grants[index].phase = if !passed
2102                        && grant.receipt.request.kind == Kind::Gate
2103                        && grant.spent < grant.receipt.request.rounds
2104                    {
2105                        Phase::Pending
2106                    } else {
2107                        Phase::Complete
2108                    };
2109                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2110                        // Persist publication debt with the successful checkpoint.
2111                        self.state.pr_publication_pending = true;
2112                    } else if passed {
2113                        self.state.status = RunStatus::Ready;
2114                    }
2115                    self.state.save()?;
2116                    if !passed {
2117                        continue;
2118                    }
2119                    // Existing PR ownership and push lease stay in place. The
2120                    // normal publisher owes the new reviewed/gated SHA, and
2121                    // land's fresh owner approval remains mandatory.
2122                    if self.state.config.merge.mode != MergeMode::Pr {
2123                        self.state.status = RunStatus::Ready;
2124                        self.state.event(
2125                            "repair-grant",
2126                            "repair verified locally; grant carries no merge authorization",
2127                        );
2128                        self.state.save()?;
2129                        return Ok(());
2130                    }
2131                    return self.merge().await;
2132                }
2133                Phase::Complete => return Ok(()),
2134            }
2135        }
2136    }
2137
2138    async fn execute_graph(&mut self) -> Result<()> {
2139        // Even a terminal run may reenter through an explicit recovery action.
2140        // Restore before prep shortcuts, saved conversations or graph nodes use
2141        // a disposable path; GC may already have removed its original objects.
2142        let archive_home = crate::run::home().canonicalize()?;
2143        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2144            let repo = self.state.repo.clone();
2145            let _coordination = self.coordinate(&repo).await?;
2146            ensure_setup_config(&mut self.state, &repo).await?;
2147            crate::retention::restore_execution_seats(
2148                &archive_home,
2149                &self.state,
2150                _coordination.as_ref(),
2151            )
2152            .await?;
2153        }
2154        self.state.configure_recovery_resume()?;
2155        if self
2156            .state
2157            .repair_grants
2158            .last()
2159            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2160        {
2161            return self.execute_granted_repair().await;
2162        }
2163        if self
2164            .state
2165            .repair_grants
2166            .last()
2167            .is_some_and(|g| !g.succeeded)
2168        {
2169            self.state.status = RunStatus::Blocked;
2170            self.state.save()?;
2171            return Ok(());
2172        }
2173        // Preservation may invalidate an old empty classification. Resolve it
2174        // before any resume shortcut can reuse a verdict or publish a branch.
2175        self.persist_candidates().await?;
2176        // A saved base stop outranks stage markers, including legacy Voting.
2177        // Recovery never reenters implementation, deliberation or voting.
2178        if self.state.base_sync_blocked() {
2179            self.sync_to_base().await?;
2180            if !self.state.base_sync_blocked()
2181                && self.state.status != RunStatus::AlreadyInBase
2182                && !self.resource_halt()?
2183            {
2184                self.finish_after_tally().await?;
2185            }
2186            return Ok(());
2187        }
2188        if self
2189            .state
2190            .merge_decision
2191            .as_ref()
2192            .is_some_and(|decision| !decision.closed)
2193            && self.state.status != RunStatus::Landing
2194        {
2195            if crate::merge_decision::resumable_hold(&self.state) {
2196                self.state.merge = Some(MergeOutcome {
2197                    mode: MergeMode::Pr,
2198                    ok: false,
2199                    detail: self
2200                        .state
2201                        .merge_decision
2202                        .as_ref()
2203                        .unwrap()
2204                        .target
2205                        .pr
2206                        .clone(),
2207                    empty: false,
2208                });
2209                self.run_land().await?;
2210                self.settle_questions();
2211                return Ok(());
2212            }
2213            bail!(
2214                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2215            );
2216        }
2217        if self.state.config.graph.selected_implementer.is_some()
2218            && self.state.status == RunStatus::Blocked
2219            && self.state.tally.is_none()
2220            && self.state.candidate_preservation.is_empty()
2221            && self.state.interrupted_implementations.is_empty()
2222        {
2223            bail!(
2224                "selected implementation is held; explicitly release the owning task to retry it"
2225            );
2226        }
2227
2228        if self.state.merge_repairs.last().is_some_and(|r| {
2229            matches!(
2230                r.phase,
2231                crate::run::MergeRepairPhase::Requested
2232                    | crate::run::MergeRepairPhase::Fixing
2233                    | crate::run::MergeRepairPhase::Reviewing
2234            )
2235        }) {
2236            if self.repair_merge_review().await? {
2237                self.run_land().await?;
2238            }
2239            self.settle_questions();
2240            return Ok(());
2241        }
2242        // Publication already passed review and gate. Resume only that node:
2243        // syncing to a newer base here could change the verified commit.
2244        if self.state.pr_publication_pending {
2245            self.merge().await?;
2246            if self.resource_halt()? {
2247                return Ok(());
2248            }
2249            self.state.save()?;
2250            self.settle_questions();
2251            return Ok(());
2252        }
2253        // A run that already lost its quorum never resumes into the verdict
2254        // machinery: `deliberate` and `vote` would otherwise clobber the
2255        // stalled marker back to Voting and the run would keep going past a
2256        // verdict that is no longer trustworthy. Everything already recorded is
2257        // kept, so the run stays resumable (or foldable) for a human to pick up.
2258        //
2259        // On --resume the run gets one chance to repair itself: the seats a
2260        // rate limit took out are re-asked. If their quota has since reset and
2261        // the quorum is restored, the run picks up and finishes; otherwise it
2262        // stays stale and still-resumable for a later retry. If it does not
2263        // recover, the returned status stays `Stalled` and nothing was
2264        // clobbered (the recovery only mutates entries for the lost seats).
2265        if self.state.status == RunStatus::Stalled {
2266            if self.recover_stall().await? {
2267                self.finish_after_tally().await?;
2268            } else {
2269                // Still below quorum: persist the marker and stay resumable.
2270                self.state.save()?;
2271            }
2272            return Ok(());
2273        }
2274        // A run parked inside `land` - watching CI, mid fix-round, or
2275        // waiting on the owner's merge approval - resumes directly into it,
2276        // never back through `prep`. Everything before `merge` already
2277        // concluded; that is the only way `status` reaches `Landing` in the
2278        // first place. Re-walking `review_loop` first would also be actively
2279        // wrong: its own status recomputation (see its doc) treats any
2280        // clean round as reason to set `status` to `Gating`, which would
2281        // clobber this marker before `merge` ever ran, and this run would
2282        // never find its way back into `land` at all.
2283        if self.state.status == RunStatus::Landing
2284            || crate::handover::landing_checkpoint(&self.state)
2285        {
2286            self.state.land_sync_pending = true;
2287            self.state.save()?;
2288            self.run_land().await?;
2289            // `run_land` may have settled the run right here - CI came back
2290            // green and the PR merged, say - without ever passing back
2291            // through `merge`'s own trailing call. Whatever it left `status`
2292            // as is what this has to read.
2293            self.settle_questions();
2294            return Ok(());
2295        }
2296        // A run parked at `merge` on the owner's word about a withheld PR text
2297        // resumes straight into `merge`. Re-walking the tail would sync to the
2298        // base again (possibly rebasing, possibly spending the fixer) after the
2299        // gate had passed, and then push a tree nobody reviewed or gated.
2300        if self.state.github_text.is_some()
2301            && self.state.merge.is_none()
2302            && self.state.status == RunStatus::Gating
2303        {
2304            self.merge().await?;
2305            if self.resource_halt()? {
2306                return Ok(());
2307            }
2308            self.state.save()?;
2309            return Ok(());
2310        }
2311        if let Err(e) = self.prep().await {
2312            if e.is::<crate::repo_lock::ResourceBlocked>() {
2313                return Err(e);
2314            }
2315            self.state.status = RunStatus::Blocked;
2316            self.state
2317                .prep_failure
2318                .get_or_insert_with(|| format!("{e:#}"));
2319            self.state
2320                .event("prep", format!("preparation stopped: {e:#}"));
2321            self.state.save()?;
2322            return Err(e);
2323        }
2324        if self.park_here()? {
2325            return Ok(());
2326        }
2327        self.advise().await?;
2328        if self.park_here()? {
2329            return Ok(());
2330        }
2331        self.implement().await?;
2332        if self.park_here()? {
2333            return Ok(());
2334        }
2335        // `after_implement` already saved the state and settled any open
2336        // questions when it set this; nothing later in the graph has
2337        // anything to judge.
2338        if self.state.status == RunStatus::VerifiedNoop {
2339            return Ok(());
2340        }
2341        self.judge().await?;
2342        if self.park_here()? {
2343            return Ok(());
2344        }
2345        self.deliberate().await?;
2346        if self.park_here()? {
2347            return Ok(());
2348        }
2349        self.vote().await?;
2350        if self.park_here()? {
2351            return Ok(());
2352        }
2353        self.tally()?;
2354        // A verdict that lost its quorum is not trustworthy: do not review,
2355        // gate, or merge on it. Everything already done is kept, so the run
2356        // stays resumable (or foldable); the human can replace the agent that
2357        // ran out of quota and pick it up.
2358        if self.state.status == RunStatus::Stalled {
2359            // Persist the stalled marker now — the normal end-of-execute save
2360            // below is below this early return, and without it a resumed run
2361            // would reload a pre-tally status and keep going.
2362            self.state.save()?;
2363            return Ok(());
2364        }
2365        self.finish_after_tally().await?;
2366        Ok(())
2367    }
2368
2369    /// A wave could not start its agents because a shared resource stayed busy
2370    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2371    /// resumable. Unstarted seats have no result; completed peers retain
2372    /// their saved candidate state.
2373    fn stop_for_resource(&mut self) -> Result<()> {
2374        // Resource acquisition observes cancellation inside a node. Complete
2375        // the same durable park as every other node boundary before returning.
2376        if self.pause.parked() || self.interrupt.parked() {
2377            self.park_here()?;
2378            return Ok(());
2379        }
2380        if self.state.resource_block.is_some() {
2381            self.state.status = RunStatus::Blocked;
2382        }
2383        self.state.save()
2384    }
2385
2386    /// Stop walking the graph if a node ended on a resource block.
2387    fn resource_halt(&mut self) -> Result<bool> {
2388        if self.state.resource_block.is_none() {
2389            return Ok(false);
2390        }
2391        self.stop_for_resource()?;
2392        Ok(true)
2393    }
2394
2395    /// Park here if asked to, recording it in the run's own timeline.
2396    ///
2397    /// Returns whether the caller should stop walking the graph. The state is
2398    /// saved either way by the node that just finished; this adds the event so
2399    /// the operator's card says why a run that is neither finished nor moving
2400    /// is sitting where it is.
2401    fn park_here(&mut self) -> Result<bool> {
2402        let parking = self.pause.parked() || self.interrupt.parked();
2403        if !parking && self.state.resource_block.is_some() {
2404            self.stop_for_resource()?;
2405            return Ok(true);
2406        }
2407        // Either handle asking is enough - see `Pause`'s own doc for why
2408        // they are never the same one. `interrupt` is checked second so a
2409        // reason it carries is preferred in the message below over a plain
2410        // shutdown park racing it at the same boundary.
2411        if !self.pause.parked() && !self.interrupt.parked() {
2412            return Ok(false);
2413        }
2414        if self.state.parked {
2415            return Ok(true);
2416        }
2417        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2418        if let Some(block) = &mut self.state.resource_block
2419            && matches!(
2420                block.cause,
2421                crate::run::ResourceBlockCause::Cancelled { .. }
2422            )
2423        {
2424            block.cause = crate::run::ResourceBlockCause::Cancelled {
2425                park: cause.clone(),
2426            };
2427        }
2428        let why = match cause.as_ref().map(ParkCause::label) {
2429            Some(reason) => format!(
2430                "parked after `{}` ({reason}) — resume to carry on from here",
2431                self.state.status.as_str()
2432            ),
2433            None => format!(
2434                "parked after `{}` — resume to carry on from here",
2435                self.state.status.as_str()
2436            ),
2437        };
2438        self.state.event("park", why);
2439        self.state
2440            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2441        self.state.parked = true;
2442        self.state.save()?;
2443        Ok(true)
2444    }
2445
2446    /// Only a new explicit operator approval may retry failed preparation.
2447    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2448        if self.state.prep_failure.is_none() {
2449            return Ok(());
2450        }
2451        let failed_at = self
2452            .state
2453            .events
2454            .iter()
2455            .rev()
2456            .find(|event| event.node == "prep")
2457            .map_or(self.state.updated_at, |event| event.at);
2458        anyhow::ensure!(
2459            approval_at > failed_at,
2460            "preparation retry requires a new explicit release after the failure"
2461        );
2462        self.state.prep_failure = None;
2463        self.state.prep_complete = Some(false);
2464        self.state
2465            .event("prep-retry", "operator approved retry of preparation");
2466        Ok(())
2467    }
2468
2469    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2470    pub fn on_pause(&mut self, pause: Pause) {
2471        self.pause = pause;
2472    }
2473
2474    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2475    /// scheduler asking this one run - and no other - to park so a task
2476    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2477    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2478    /// handle.
2479    pub fn watch_interrupt(&mut self, pause: Pause) {
2480        self.interrupt = pause;
2481    }
2482
2483    /// Abandon this run's own open questions, once `status` has actually
2484    /// settled rather than merely paused.
2485    ///
2486    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2487    /// either back up with the candidates, the review round and the seat
2488    /// sessions already on disk, so a question an implementer asked mid-round
2489    /// may still get a real answer read by a real resume. Only the statuses
2490    /// `resumable` excludes are actually final: the run merged, it reached
2491    /// `Ready` with nothing left to do, it failed outright with no
2492    /// established point to continue from, or every candidate agreed, with
2493    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2494    /// every one of those the seat that asked is gone for good, exactly like
2495    /// the run being deleted under `magi run rm` - so the same cleanup
2496    /// applies, worded for what actually happened instead of "the run was
2497    /// deleted".
2498    ///
2499    /// Best-effort and silent on success: called from every place `status`
2500    /// can land on one of those three, including ones a resumed run revisits,
2501    /// so it must cost nothing when there was nothing open to begin with.
2502    fn settle_questions(&mut self) {
2503        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2504            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2505        }
2506    }
2507
2508    /// The tail of the graph after a trustworthy tally: fold losers, review,
2509    /// gate, merge, and persist.
2510    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2511        Box::pin(self.finish_after_tally_inner())
2512    }
2513
2514    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2515        // Before the losers are folded: their branches are what the graft
2516        // reads from.
2517        self.graft().await?;
2518        if self.resource_halt()? {
2519            return Ok(());
2520        }
2521        self.fold_losers().await?;
2522        // Before review starts, and again right before the gate: a run's
2523        // review rounds can themselves take long enough for the base to move
2524        // a second time, and the gate is the one node whose "green" gets
2525        // acted on.
2526        self.sync_to_base().await?;
2527        if self.hold_base_sync().await? || self.resource_halt()? {
2528            return Ok(());
2529        }
2530        if self.state.status == RunStatus::AlreadyInBase {
2531            return Ok(());
2532        }
2533        self.review_loop().await?;
2534        if self.resource_halt()? {
2535            return Ok(());
2536        }
2537        self.sync_to_base().await?;
2538        if self.hold_base_sync().await? || self.resource_halt()? {
2539            return Ok(());
2540        }
2541        if self.state.status == RunStatus::AlreadyInBase {
2542            return Ok(());
2543        }
2544        self.gate().await?;
2545        self.merge().await?;
2546        if self.resource_halt()? {
2547            return Ok(());
2548        }
2549        self.state.save()?;
2550        Ok(())
2551    }
2552
2553    // ---------------------------------------------------------------- prep
2554
2555    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2556    /// run with the step and its output in the event; it is never swallowed.
2557    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2558    /// resume starts over instead of finding candidates and missing seats.
2559    async fn setup_seat_worktree(
2560        &mut self,
2561        repo: &Path,
2562        wt: &Path,
2563        in_prep: bool,
2564        coordination: Option<&crate::repo_lock::SeatLease>,
2565    ) -> Result<()> {
2566        let result = match ensure_setup_config(&mut self.state, repo).await {
2567            Ok(()) => {
2568                worktree_setup::prepare_with(
2569                    &self.state.config,
2570                    repo,
2571                    wt,
2572                    crate::build_target::Coordination::Held(coordination),
2573                )
2574                .await
2575            }
2576            Err(e) => Err(e),
2577        };
2578        if let Err(e) = result {
2579            git::worktree_remove_clean(repo, wt).await.ok();
2580            if in_prep {
2581                self.rollback_prep(repo).await;
2582            }
2583            self.state.status = RunStatus::Blocked;
2584            self.state.event(
2585                "setup",
2586                format!("worktree setup failed in {}: {e:#}", wt.display()),
2587            );
2588            self.state.save()?;
2589            return Err(e);
2590        }
2591        Ok(())
2592    }
2593
2594    /// Undo everything `prep` created, so a resume re-runs it whole.
2595    async fn rollback_prep(&mut self, repo: &Path) {
2596        let root = self.state.worktree_root();
2597        for c in std::mem::take(&mut self.state.candidates) {
2598            if matches!(
2599                git::worktree_remove_clean(repo, &c.worktree).await,
2600                Ok(true)
2601            ) {
2602                git::branch_delete(repo, &c.branch).await.ok();
2603            } else {
2604                self.state.candidates.push(c);
2605            }
2606        }
2607        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2608        for j in 1..=seats {
2609            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2610                .await
2611                .ok();
2612        }
2613        for k in 1..=self.state.config.graph.advisors {
2614            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2615                .await
2616                .ok();
2617        }
2618    }
2619
2620    async fn prep(&mut self) -> Result<()> {
2621        if let Some(reason) = &self.state.prep_failure {
2622            bail!(
2623                "candidate preparation previously failed: {reason}; correct the source before retrying"
2624            );
2625        }
2626        if self
2627            .state
2628            .prep_complete
2629            .unwrap_or(!self.state.candidates.is_empty())
2630        {
2631            return Ok(());
2632        }
2633        let repo = self.state.repo.clone();
2634        // Includes rollback, config, refs, checkout creation and setup. No
2635        // repository mutation may precede the real shared lock acquisition.
2636        let _coordination = self.coordinate(&repo).await?;
2637        let base = self.state.base_commit.clone();
2638        let plan = self.state.sources.plan(&repo, &base).await?;
2639        self.rollback_prep(&repo).await;
2640        if !self.state.candidates.is_empty() {
2641            bail!(
2642                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2643            );
2644        }
2645        self.state.prep_complete = Some(false);
2646        self.state.status = RunStatus::Prep;
2647        self.state.save()?;
2648        let repo = self.state.repo.clone();
2649        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2650        let root = self.state.worktree_root();
2651        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2652
2653        // The hook is the write-time half of the blindness contract; the
2654        // presentation filter in `blind` is the half that cannot be bypassed.
2655        let hooks_dir = self.state.dir().join("hooks");
2656        if self.state.config.blind.commit_msg_hook {
2657            std::fs::create_dir_all(&hooks_dir)
2658                .with_context(|| format!("create {}", hooks_dir.display()))?;
2659            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2660            let path = hooks_dir.join("commit-msg");
2661            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2662            make_executable(&path)?;
2663            // Ref-counted rather than a plain idempotent set: with more than
2664            // one run able to be in flight in the same repository at once
2665            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2666            // true?" check cannot tell "another run of mine still needs
2667            // this" from "nobody does", and the run that happens to finish
2668            // first would disable the hook out from under a sibling still
2669            // relying on it.
2670            git::acquire_worktree_config(&repo).await?;
2671            self.state.enabled_worktree_config = true;
2672        }
2673
2674        // `[worktree] setup` hides its products per worktree, which needs the
2675        // same per-worktree config the hook does. Held until fold, like it.
2676        ensure_setup_config(&mut self.state, &repo).await?;
2677
2678        for (index, (spec, label)) in self
2679            .roles
2680            .implementers
2681            .clone()
2682            .into_iter()
2683            .zip(labels)
2684            .enumerate()
2685        {
2686            let branch = self.state.branch_for(label);
2687            let worktree = root.join(format!("cand-{label}"));
2688            // Persist intent before Git can leave a partially created tree.
2689            // Candidate registration follows setup, so it cannot inventory
2690            // crashes or refusals during creation itself.
2691            self.state.event(
2692                "prep-intent",
2693                serde_json::json!({
2694                    "branch": branch,
2695                    "worktree": worktree,
2696                    "start": start,
2697                    "picks": plan.picks,
2698                })
2699                .to_string(),
2700            );
2701            self.state.save()?;
2702            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2703            if self.state.config.blind.commit_msg_hook {
2704                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2705            }
2706            git::local_exclude(&worktree, "/.magi/").await?;
2707            if let Err(e) = worktree_setup::prepare_with(
2708                &self.state.config,
2709                &repo,
2710                &worktree,
2711                crate::build_target::Coordination::Held(_coordination.as_ref()),
2712            )
2713            .await
2714            {
2715                // Nothing of this prep may survive: a resume must start over,
2716                // not find half the candidates and skip the rest.
2717                git::worktree_remove_clean(&repo, &worktree).await.ok();
2718                git::branch_delete(&repo, &branch).await.ok();
2719                self.rollback_prep(&repo).await;
2720                self.state.status = RunStatus::Blocked;
2721                self.state
2722                    .event("prep", format!("worktree setup failed: {e:#}"));
2723                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2724                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2725                }
2726                self.state.save()?;
2727                return Err(e);
2728            }
2729            self.state.candidates.push(Candidate {
2730                index,
2731                label,
2732                agent: spec.id.clone(),
2733                branch,
2734                worktree,
2735                summary: String::new(),
2736                stat: String::new(),
2737                files: 0,
2738                commits: 0,
2739                empty: false,
2740                failed: None,
2741                verified_noop: None,
2742                duration_ms: 0,
2743                folded: false,
2744            });
2745            self.state.save()?;
2746            for pick in &plan.picks {
2747                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2748                {
2749                    self.state.status = RunStatus::Blocked;
2750                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2751                    self.state
2752                        .event("prep", format!("cannot apply referenced commit: {e}"));
2753                    self.state.save()?;
2754                    return Err(e);
2755                }
2756            }
2757        }
2758
2759        for j in 1..=self.roles.judges.len() {
2760            let wt = root.join(format!("judge-{j}"));
2761            if !wt.exists() {
2762                git::worktree_add_detached(&repo, &wt, &base).await?;
2763                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2764                    .await?;
2765            }
2766        }
2767
2768        // Disposable, detached checkouts for the design-deliberation stage's
2769        // advisor seats — the same shape as the judges' above, at the same
2770        // base commit, since advisors also only ever read. Sized off the
2771        // configured count directly rather than a resolved roster: unlike
2772        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2773        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2774        // `prep` has no `ResolvedRoles` field to read a count from here.
2775        if self.state.config.graph.advise {
2776            for k in 1..=self.state.config.graph.advisors {
2777                let wt = root.join(format!("advisor-{k}"));
2778                if !wt.exists() {
2779                    git::worktree_add_detached(&repo, &wt, &base).await?;
2780                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2781                        .await?;
2782                }
2783            }
2784        }
2785
2786        // A judge cannot tell it is looking at its own patch — the seats keep
2787        // separate conversations — but a panel that shares agents with the
2788        // field is less independent than it looks, and that is worth saying out
2789        // loud once per run rather than leaving it in the config.
2790        let authors: Vec<&str> = self
2791            .roles
2792            .implementers
2793            .iter()
2794            .map(|a| a.id.as_str())
2795            .collect();
2796        let overlap: Vec<String> = self
2797            .roles
2798            .judges
2799            .iter()
2800            .enumerate()
2801            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2802            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2803            .collect();
2804        if !overlap.is_empty() {
2805            let note = format!(
2806                "{} also authored a candidate; blind, but the panel is less \
2807                 independent than {} distinct agents would be",
2808                overlap.join(", "),
2809                self.roles.judges.len()
2810            );
2811            self.state.event("prep", note);
2812        }
2813
2814        self.state.event(
2815            "prep",
2816            format!(
2817                "{} candidates, {} judges, base {} ({})",
2818                self.state.candidates.len(),
2819                self.roles.judges.len(),
2820                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2821                self.state.base_branch
2822            ),
2823        );
2824        self.state.prep_complete = Some(true);
2825        self.state.status = RunStatus::Implementing;
2826        self.state.save()?;
2827        Ok(())
2828    }
2829
2830    // -------------------------------------------------------------- advise
2831
2832    /// The design-deliberation stage: independent, read-only advisor seats
2833    /// each sketch a design before any implementer touches the repository,
2834    /// and (when at least one produced a usable proposal) a synthesis seat
2835    /// blends them into a brief `implement` carries in every candidate's
2836    /// prompt.
2837    ///
2838    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2839    /// advisors` is the proposal count. Everything here is best-effort and
2840    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2841    /// that cannot reach quota, or a synthesis seat that produced nothing
2842    /// usable all leave `implement` exactly as it was before this stage
2843    /// existed — the task instruction alone — rather than failing the whole
2844    /// competition over an enrichment stage. Every outcome is still recorded
2845    /// as an event, so a run that got nothing from this stage says why.
2846    ///
2847    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2848    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2849    /// resumed run whose stage failed would re-run it, and re-spend the
2850    /// agent calls, on every reentry before `implement`.
2851    ///
2852    /// Also skipped once any candidate shows implementation progress — the
2853    /// exact predicate `implement` itself uses to decide a candidate is no
2854    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2855    /// is not enough: a run created by an older binary that predates this
2856    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2857    /// an already-`Implementing`-or-later run under this build would
2858    /// otherwise walk straight back through `prep` (a no-op once candidates
2859    /// exist) into this node and spawn every advisor seat against worktrees
2860    /// `prep` never recreated — after implementation has already started,
2861    /// which is exactly the invariant this stage exists to guarantee.
2862    async fn advise(&mut self) -> Result<()> {
2863        let implement_untouched = self
2864            .state
2865            .candidates
2866            .iter()
2867            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2868        if !self.state.config.graph.advise || self.state.advise_attempted {
2869            return Ok(());
2870        }
2871        if !implement_untouched {
2872            self.state.event(
2873                "advise",
2874                "skipping the design-deliberation stage: at least one \
2875                 candidate already shows implementation progress, so this \
2876                 run is past the point the stage exists to run before"
2877                    .to_owned(),
2878            );
2879            self.state.advise_attempted = true;
2880            self.state.save()?;
2881            return Ok(());
2882        }
2883        let run_id = self.state.id.clone();
2884        let prompts = self.state.config.prompts.clone();
2885        let instruction = self.state.instruction.clone();
2886        let language = self.state.config.graph.language.clone();
2887        let root = self.state.worktree_root();
2888        let n = self.state.config.graph.advisors;
2889        let where_recorded = self.state.dir().join("run.json");
2890
2891        let seats = match self.state.config.advisors() {
2892            Ok(seats) if !seats.is_empty() => seats,
2893            Ok(_) => {
2894                self.state.event(
2895                    "advise",
2896                    format!(
2897                        "[graph] advisors is 0; skipping the design-deliberation \
2898                         stage and continuing without a synthesis brief (see {})",
2899                        where_recorded.display()
2900                    ),
2901                );
2902                self.state.advise_attempted = true;
2903                self.state.save()?;
2904                return Ok(());
2905            }
2906            Err(e) => {
2907                self.state.event(
2908                    "advise",
2909                    format!(
2910                        "could not resolve advisor seats ({e:#}); continuing \
2911                         without a design-deliberation brief (see {})",
2912                        where_recorded.display()
2913                    ),
2914                );
2915                self.state.advise_attempted = true;
2916                self.state.save()?;
2917                return Ok(());
2918            }
2919        };
2920
2921        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2922        let artifacts = agent::artifacts_dir(&self.state.dir());
2923        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2924
2925        let mut jobs = Vec::new();
2926        for (i, spec) in seats.iter().cloned().enumerate() {
2927            let seat_key = format!("advisor-{}", i + 1);
2928            let seat = self.seat(&seat_key, &spec.id);
2929            jobs.push(SeatJob {
2930                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2931                spec,
2932                seat,
2933                cwd: worktrees[i % worktrees.len()].clone(),
2934                timeout,
2935                allow_write: false,
2936                sessions: false,
2937                artifacts: artifacts.clone(),
2938                stem: seat_key,
2939                handover: None,
2940            });
2941        }
2942
2943        self.state.event(
2944            "advise",
2945            format!(
2946                "{} advisor seat(s) sketching a design in parallel",
2947                jobs.len()
2948            ),
2949        );
2950        let mut quota_losses = Vec::new();
2951        let cache = self.state.config.cache_dir();
2952        let ctx = WaveCtx {
2953            carry_seats: false,
2954            pauses: Some((&self.pause, &self.interrupt)),
2955            run: &run_id,
2956            node: "advise",
2957            prompts: &prompts,
2958            cache: cache.as_deref(),
2959            round: None,
2960        };
2961        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2962        let results = ask_json_wave::<Proposal>(
2963            jobs,
2964            Arc::clone(&self.sem),
2965            self.state.config.graph.retries,
2966            &advisor_roster,
2967            &ctx,
2968            &mut quota_losses,
2969            &mut self.state,
2970            &|p: &Proposal| p.validate(),
2971        )
2972        .await;
2973        if self.state.resource_block.is_some() {
2974            return self.stop_for_resource();
2975        }
2976        self.state.quota.extend(quota_losses);
2977
2978        let mut records = Vec::with_capacity(results.len());
2979        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2980            let agent_id = seat.agent.clone();
2981            self.state.seats.insert(seat.key.clone(), seat);
2982            match res {
2983                Ok((proposal, out)) => {
2984                    self.state
2985                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2986                    records.push(advise::AdvisorRecord::proposed(
2987                        i + 1,
2988                        agent_id,
2989                        proposal,
2990                        out.duration_ms,
2991                    ));
2992                }
2993                Err(e) => {
2994                    self.state.event(
2995                        "advise",
2996                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
2997                    );
2998                    records.push(advise::AdvisorRecord::failed(
2999                        i + 1,
3000                        agent_id,
3001                        e.to_string(),
3002                    ));
3003                }
3004            }
3005        }
3006
3007        let mut advice = advise::Advice {
3008            records,
3009            synthesis: None,
3010        };
3011        if advice.proposals().is_empty() {
3012            self.state.event(
3013                "advise",
3014                "no advisor produced a usable proposal; continuing without a \
3015                 synthesis brief"
3016                    .to_owned(),
3017            );
3018        } else {
3019            match self
3020                .synthesize_brief(
3021                    &advice,
3022                    &instruction,
3023                    &language,
3024                    &worktrees[0],
3025                    &artifacts,
3026                    &run_id,
3027                    &prompts,
3028                    cache.as_deref(),
3029                )
3030                .await
3031            {
3032                Ok(Some(text)) => {
3033                    self.state.event(
3034                        "advise",
3035                        "synthesized a design brief for the implementer".to_owned(),
3036                    );
3037                    advice.synthesis = Some(text);
3038                }
3039                Ok(None) => {
3040                    self.state.event(
3041                        "advise",
3042                        "the synthesis seat produced nothing usable; continuing \
3043                         without a design brief"
3044                            .to_owned(),
3045                    );
3046                }
3047                Err(e) => {
3048                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3049                        return Err(e);
3050                    }
3051                    self.state.event(
3052                        "advise",
3053                        format!("could not synthesize a design brief: {e:#}"),
3054                    );
3055                }
3056            }
3057        }
3058        advise::apply_reflection(&mut advice);
3059
3060        self.state.advice = Some(advice);
3061        self.state.advise_attempted = true;
3062        self.state.save()?;
3063        Ok(())
3064    }
3065
3066    /// The synthesis seat: reads every advisor's proposal and blends them
3067    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3068    /// out of [`Runner::advise`] only for readability — it is not called
3069    /// anywhere else.
3070    ///
3071    /// Picked the same way [`crate::talk`]'s standing conversation and
3072    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3073    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3074    /// order (a claude seat, else the first runnable agent in roster order)
3075    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3076    /// in [`crate::config`] for why a dedicated field exists here at all.
3077    #[allow(clippy::too_many_arguments)]
3078    async fn synthesize_brief(
3079        &mut self,
3080        advice: &advise::Advice,
3081        instruction: &str,
3082        language: &str,
3083        cwd: &Path,
3084        artifacts: &Path,
3085        run_id: &str,
3086        prompts: &Prompts,
3087        cache: Option<&Path>,
3088    ) -> Result<Option<String>> {
3089        let chain = agent::pick_chain(
3090            &self.state.config.agents,
3091            self.state.config.roles.synthesizer.as_ref(),
3092            &agent::installed,
3093            "synthesizer",
3094        )?;
3095        let proposals = advice.proposals();
3096        let mut prompt = prompt::with_overlay(
3097            prompt::synthesize_brief(instruction, &proposals, language),
3098            prompts.overlay("advise"),
3099        );
3100        if cache.is_some() {
3101            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3102            // below — see `prompt::build_cache_note`'s doc for why telling a
3103            // read-only seat to build through the shared cache is exactly how
3104            // a sandbox's write refusal gets misread as a defect.
3105            prompt.push('\n');
3106            prompt.push_str(&prompt::build_cache_note("advise", false));
3107        }
3108        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3109        // Each id is tried once, in order; a quota hit, error or unusable
3110        // answer moves to the next. The seat is single-turn (`sessions:
3111        // false`) and the prompt is the whole context, so a fallback agent
3112        // needs nothing carried over.
3113        let mut last = None;
3114        for (n, spec) in chain.iter().enumerate() {
3115            if n > 0 {
3116                self.state
3117                    .event("advise", format!("synthesis falling back to {}", spec.id));
3118            }
3119            let mut seat = self.seat("advise-synthesis", &spec.id);
3120            let wait = self.repository_wait();
3121            let outcome = wait
3122                .scope(agent::invoke(
3123                    spec,
3124                    &mut seat,
3125                    &Invocation {
3126                        coordination: self.state.config.coordination.as_ref(),
3127                        fetched_base: None,
3128                        cwd,
3129                        prompt: &prompt,
3130                        timeout,
3131                        allow_write: false,
3132                        sessions: false,
3133                        artifacts,
3134                        stem: &if n == 0 {
3135                            "advise-synthesis".to_owned()
3136                        } else {
3137                            format!("advise-synthesis-{}", spec.id)
3138                        },
3139                        run: run_id,
3140                        node: "advise",
3141                        cache_dir: None,
3142                        attachments: &[],
3143                        writable: &[],
3144                    },
3145                ))
3146                .await;
3147            if outcome.is_ok() {
3148                self.state.seats.insert(seat.key.clone(), seat);
3149            }
3150            let advance = agent::chain_advances(&outcome);
3151            last = Some(outcome);
3152            if !advance {
3153                break;
3154            }
3155        }
3156        // Exhausted: the last attempt's result is what a single failed seat
3157        // would have produced.
3158        let out = last.expect("a chain holds at least one agent")?;
3159        if !out.usable() {
3160            return Ok(None);
3161        }
3162        let text =
3163            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3164        Ok((!text.trim().is_empty()).then_some(text))
3165    }
3166
3167    // ----------------------------------------------------------- implement
3168
3169    async fn implement(&mut self) -> Result<()> {
3170        self.persist_candidates().await?;
3171        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3172        // agent files with `magi task add` name the run that paid for it. The
3173        // prompt overlay is cloned alongside it because the waves borrow it
3174        // while `self` is mutably borrowed by the node's own bookkeeping.
3175        let run_id = self.state.id.clone();
3176        let prompts = self.state.config.prompts.clone();
3177        let todo: Vec<usize> = self
3178            .state
3179            .candidates
3180            .iter()
3181            .enumerate()
3182            .filter(|(_, c)| {
3183                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3184                    && c.failed.is_none()
3185                    && !c.empty
3186            })
3187            .map(|(i, _)| i)
3188            .collect();
3189        if todo.is_empty() {
3190            return self.after_implement();
3191        }
3192        self.state.status = RunStatus::Implementing;
3193
3194        let language = self.state.config.graph.language.clone();
3195        let github_language = self.state.config.graph.github_language.clone();
3196        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3197        let sessions = self.state.config.graph.sessions;
3198        let artifacts = agent::artifacts_dir(&self.state.dir());
3199        // The design-deliberation stage's blended brief, when `advise` found
3200        // one — carried into every implementer's prompt the same way
3201        // regardless of which candidate it is.
3202        let brief = self
3203            .state
3204            .advice
3205            .as_ref()
3206            .and_then(|a| a.synthesis.as_deref())
3207            .map(str::to_owned);
3208        let attachments = self.state.attachments.clone();
3209
3210        let mut jobs = Vec::new();
3211        for &i in &todo {
3212            let (index, label, worktree) = {
3213                let c = &self.state.candidates[i];
3214                (c.index, c.label, c.worktree.clone())
3215            };
3216            let spec = self.roles.implementers[index].clone();
3217            let seat_key = format!("impl-{label}");
3218            let seat = self.seat(&seat_key, &spec.id);
3219            let instruction = seeded_instruction(&self.state);
3220            jobs.push(SeatJob {
3221                spec,
3222                seat,
3223                prompt: prompt::implement_in(
3224                    &instruction,
3225                    &worktree.to_string_lossy(),
3226                    &language,
3227                    &github_language,
3228                    brief.as_deref(),
3229                    &attachments,
3230                ),
3231                cwd: worktree,
3232                timeout,
3233                allow_write: true,
3234                sessions,
3235                artifacts: artifacts.clone(),
3236                stem: format!("impl-{label}"),
3237                handover: None,
3238            });
3239        }
3240
3241        self.state.event(
3242            "implement",
3243            format!("{} candidates in parallel", jobs.len()),
3244        );
3245        // Kept so a seat whose CLI hung up can be asked again from the same
3246        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3247        // can update a seat's own entry once a fallback agent takes it over —
3248        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3249        // whichever agent actually answered, not the one that quota'd out.
3250        let mut sent = jobs.clone();
3251        let cache = self.state.config.cache_dir();
3252        let ctx = WaveCtx {
3253            carry_seats: false,
3254            pauses: Some((&self.pause, &self.interrupt)),
3255            run: &run_id,
3256            node: "implement",
3257            prompts: &prompts,
3258            cache: cache.as_deref(),
3259            round: None,
3260        };
3261        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3262        if !wave_blocked(&results) {
3263            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3264                .await;
3265            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3266                .await?;
3267            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3268                .await;
3269        }
3270        // Do not finalize failed candidates when the entire wave needs machine
3271        // recovery: leaving them pending resumes this node with its work intact.
3272        if !results.is_empty()
3273            && results
3274                .iter()
3275                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3276        {
3277            let losses: Vec<_> = results
3278                .iter()
3279                .map(|(_, seat, out)| {
3280                    let AgentOutcome::Quota(o) = out else {
3281                        unreachable!()
3282                    };
3283                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3284                })
3285                .collect();
3286            self.state.quota.extend(losses.clone());
3287            for (_, seat, _) in results {
3288                self.state.seats.insert(seat.key.clone(), seat);
3289            }
3290            for &i in &todo {
3291                let label = self.state.candidates[i].label;
3292                self.state.interrupted_implementations.insert(label);
3293                self.state
3294                    .candidate_preservation
3295                    .insert(label, "machine outage awaiting persistence".into());
3296            }
3297            // Preserve partial edits too, while keeping every interrupted seat
3298            // pending even when its tree already contains an inherited patch.
3299            block_machine_outage(&mut self.state, "implement", &losses);
3300            self.state.save()?;
3301            self.persist_candidates().await?;
3302            for &i in &todo {
3303                self.state
3304                    .interrupted_implementations
3305                    .insert(self.state.candidates[i].label);
3306            }
3307            return self.stop_for_resource();
3308        }
3309        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3310
3311        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3312            && results
3313                .iter()
3314                .any(|(_, _, out)| FailClass::of(out).is_some());
3315        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3316            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3317                // Executed turns interrupted by disk pressure already carry
3318                // a preservation barrier from wave. Admission-only waits do
3319                // not. Keep the interrupted seat's session for recovery too.
3320                if self
3321                    .state
3322                    .candidate_preservation
3323                    .contains_key(&self.state.candidates[i].label)
3324                {
3325                    self.state.seats.insert(seat.key.clone(), seat);
3326                }
3327                continue;
3328            }
3329            let seat_key = seat.key.clone();
3330            // A quota fallback (`resume_seat_handovers`) may have handed this
3331            // seat to a different agent than the one `prep` recorded on the
3332            // candidate; the stats tables and any later fixer-defaults-to-
3333            // winner's-author lookup must credit whoever actually answered —
3334            // unless every fallback also quota'd out, in which case nobody
3335            // actually answered and crediting the last agent tried would
3336            // erase every earlier agent's own quota loss from the stats
3337            // tables instead of just this one seat's.
3338            let agent = seat.agent.clone();
3339            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3340            self.state.seats.insert(seat.key.clone(), seat);
3341            let label = self.state.candidates[i].label;
3342            self.state.interrupted_implementations.remove(&label);
3343
3344            let (summary, duration, failed, verified_claim) = match out {
3345                AgentOutcome::Ok(o) => {
3346                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3347                    let failed = (!o.usable()).then(|| {
3348                        if o.timed_out {
3349                            "agent timed out".to_owned()
3350                        } else {
3351                            format!(
3352                                "agent exited with {}",
3353                                crate::notices::exit_status(o.exit_code)
3354                            )
3355                        }
3356                    });
3357                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3358                    (text, o.duration_ms, failed, verified_claim)
3359                }
3360                // Left un-resumed by `resume_undelivered` (a dirty tree
3361                // already rescues the work, or there was no session left to
3362                // resume into) — reported like the ordinary failure it is,
3363                // never as if `o.text` (the CLI's raw error JSON) were an
3364                // answer.
3365                AgentOutcome::Dropped(o) => {
3366                    let why = o
3367                        .dropped
3368                        .as_ref()
3369                        .map(|d| d.why.as_str())
3370                        .unwrap_or("the CLI ended the stream without delivering its answer");
3371                    (
3372                        String::new(),
3373                        o.duration_ms,
3374                        Some(format!("the CLI dropped the stream ({why})")),
3375                        None,
3376                    )
3377                }
3378                AgentOutcome::Quota(o) => {
3379                    self.state.quota.push(QuotaLoss::from_report(
3380                        seat_key,
3381                        "implement",
3382                        o.quota.as_ref(),
3383                    ));
3384                    (
3385                        String::new(),
3386                        o.duration_ms,
3387                        Some("rate limited (quota); produced no change".to_owned()),
3388                        None,
3389                    )
3390                }
3391                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3392                    (String::new(), 0, Some(e), None)
3393                }
3394            };
3395
3396            // Save every completed turn before any fallible Git operation. A failed
3397            // rescue must not erase the reply or prevent collection of other seats.
3398            let c = &mut self.state.candidates[i];
3399            if !exhausted_the_fallback_chain {
3400                c.agent = agent;
3401            }
3402            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3403            c.duration_ms = duration;
3404            c.failed = failed;
3405            c.verified_noop = verified_claim;
3406            self.state
3407                .candidate_preservation
3408                .insert(label, "awaiting persistence".to_owned());
3409        }
3410        self.state.save()?;
3411        self.persist_candidates().await?;
3412
3413        if resource_blocked {
3414            return self.stop_for_resource();
3415        }
3416        if selected_failed {
3417            self.state.status = RunStatus::Blocked;
3418            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3419            self.state.save()?;
3420            bail!(
3421                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3422            );
3423        }
3424        self.after_implement()
3425    }
3426
3427    /// Retry only persistence after a completed implementation turn.
3428    async fn persist_candidates(&mut self) -> Result<()> {
3429        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3430        for label in labels {
3431            let i = self
3432                .state
3433                .candidates
3434                .iter()
3435                .position(|c| c.label == label)
3436                .context("pending candidate is missing")?;
3437            let c = self.state.candidates[i].clone();
3438            let interrupted = self.state.interrupted_implementations.contains(&label);
3439            let result = async {
3440                let wait = crate::repo_lock::WaitPolicy::new(
3441                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3442                    || false,
3443                );
3444                let _coordination =
3445                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3446                // Best effort evidence requires no index writes. A successful snapshot
3447                // never authorizes removal of a tree whose rescue failed.
3448                if let Err(e) = git::snapshot_uncommitted(
3449                    &c.worktree,
3450                    &self
3451                        .state
3452                        .dir()
3453                        .join("artifacts")
3454                        .join(format!("candidate-{label}-recovery")),
3455                )
3456                .await
3457                {
3458                    self.state.event(
3459                        "preserve",
3460                        format!("candidate {label} snapshot incomplete: {e:#}"),
3461                    );
3462                }
3463                let rescued = git::rescue_commit(
3464                    &c.worktree,
3465                    &format!("magi: candidate {label} (uncommitted work)"),
3466                )
3467                .await?;
3468                self.state.note_withheld("implement", &rescued.withheld);
3469                let base = &self.state.base_commit;
3470                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3471                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3472                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3473                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3474                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3475                if c.empty && commits > 0 && !patch.trim().is_empty()
3476                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3477                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3478                        || self.state.tally.is_some())
3479                {
3480                    // Keep the old classification and pending marker so every
3481                    // retry stops too. Retain decisions as recovery evidence;
3482                    // only a supported recovery operation may replace them.
3483                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3484                }
3485                let c = &mut self.state.candidates[i];
3486                c.commits = commits;
3487                c.stat = stat;
3488                c.files = files;
3489                let no_changes = commits == 0 || patch.trim().is_empty();
3490                c.empty = no_changes && !interrupted;
3491                if interrupted && no_changes {
3492                    c.failed = None;
3493                    c.verified_noop = None;
3494                }
3495                if !c.empty {
3496                    c.failed = None;
3497                    c.verified_noop = None;
3498                }
3499                self.state.event(
3500                    "preserve",
3501                    format!("candidate {label}: {files} files, {commits} commits"),
3502                );
3503                Ok::<_, anyhow::Error>(())
3504            }
3505            .await;
3506            match result {
3507                Ok(()) => {
3508                    self.state.candidate_preservation.remove(&label);
3509                    if !interrupted || self.state.candidates[i].files > 0 {
3510                        self.state.interrupted_implementations.remove(&label);
3511                    }
3512                }
3513                Err(e) => {
3514                    let reason = format!("candidate {label} preservation failed: {e:#}");
3515                    self.state.event("preserve", &reason);
3516                    self.state.candidate_preservation.insert(label, reason);
3517                }
3518            }
3519            if self.state.candidate_preservation.is_empty()
3520                && self.state.status == RunStatus::Blocked
3521                && self.state.candidates.iter().all(|c| c.failed.is_none())
3522            {
3523                // Persist the recovered phase with the cleared pending marker;
3524                // a crash between saves must not turn this into a selected-seat
3525                // failure hold on the next resume.
3526                self.state.status = RunStatus::Implementing;
3527                self.state.event(
3528                    "preserve",
3529                    "candidate persistence recovered; implementation can continue",
3530                );
3531            }
3532            self.state.save()?;
3533        }
3534        if !self.state.candidate_preservation.is_empty() {
3535            self.state.status = RunStatus::Blocked;
3536            self.state.save()?;
3537            bail!(
3538                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3539            );
3540        }
3541        Ok(())
3542    }
3543
3544    /// Ask again, once, for work a CLI did and then failed to hand over.
3545    ///
3546    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3547    /// status with an empty response and a usage report showing output tokens,
3548    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3549    /// seven minutes and 14,267 output tokens that arrived as an empty
3550    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3551    ///
3552    /// Two conditions, and both matter:
3553    ///
3554    /// - **Only when the tree is untouched.** Often the agent has already
3555    ///   written its files and only the closing message was lost; the rescue
3556    ///   commit below picks that up and there is nothing to ask for. Re-asking
3557    ///   then would pay for a second implementation of work already on disk.
3558    /// - **Once.** A CLI that drops one stream can drop the next, and this
3559    ///   node is the most expensive in the graph.
3560    ///
3561    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3562    /// dropped reply still carried its `conversation_id`, so the seat is asked
3563    /// to finish what it was doing rather than sent the whole task again. It
3564    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3565    /// node's - for the same reason a re-ranked judge does: restating finished
3566    /// work is not the work.
3567    ///
3568    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3569    /// same way until it resets, while an abandoned conversation is still
3570    /// there to be picked up.
3571    async fn resume_undelivered(
3572        &mut self,
3573        results: &mut [(usize, SeatState, AgentOutcome)],
3574        sent: &[SeatJob],
3575        prompts: &Prompts,
3576        run_id: &str,
3577    ) {
3578        for (wi, seat, out) in results.iter_mut() {
3579            let Some(dropped) = (match &*out {
3580                AgentOutcome::Dropped(o) => o.dropped.clone(),
3581                _ => None,
3582            }) else {
3583                continue;
3584            };
3585            let Some(job) = sent.get(*wi) else { continue };
3586            // Already on disk? Then only the closing message was lost.
3587            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3588                self.state.event(
3589                    "implement",
3590                    format!(
3591                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3592                         work is in the tree",
3593                        seat.key, dropped.output_tokens, dropped.why
3594                    ),
3595                );
3596                continue;
3597            }
3598            // The re-ask only makes sense as a resume: `resume_after_drop`
3599            // says nothing about the task, trusting the seat to still hold it.
3600            // Without a session to resume — sessions disabled, or this CLI's
3601            // drop shape happened not to carry a session id — that prompt
3602            // would open a brand-new conversation with no context at all,
3603            // which is worse than leaving this as the ordinary failure it
3604            // already is.
3605            if !has_context(&job.spec, seat, job.sessions) {
3606                self.state.event(
3607                    "implement",
3608                    format!(
3609                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3610                         is no session left to resume",
3611                        seat.key, dropped.output_tokens, dropped.why
3612                    ),
3613                );
3614                continue;
3615            }
3616            self.state.event(
3617                "implement",
3618                format!(
3619                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3620                     conversation",
3621                    seat.key, dropped.output_tokens, dropped.why
3622                ),
3623            );
3624            let mut retry = job.clone();
3625            retry.seat = seat.clone();
3626            retry.prompt = prompt::resume_after_drop(&dropped.why);
3627            retry.timeout = retry_budget(job.timeout, true);
3628            retry.stem = format!("{}-resume", job.stem);
3629            let cache = self.state.config.cache_dir();
3630            let ctx = WaveCtx {
3631                carry_seats: false,
3632                pauses: Some((&self.pause, &self.interrupt)),
3633                run: run_id,
3634                node: "implement",
3635                prompts,
3636                cache: cache.as_deref(),
3637                round: None,
3638            };
3639            let (resumed_seat, resumed) =
3640                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3641            *seat = resumed_seat;
3642            *out = resumed;
3643        }
3644    }
3645
3646    /// Fall an implement seat through to the next untried agent in the
3647    /// implementer roster when it lost to quota — or, since the handover was
3648    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3649    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3650    /// quota path itself being unchanged — instead of leaving the
3651    /// seat's loss final the moment one agent's account runs dry.
3652    ///
3653    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3654    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3655    /// truncates to the single slot rotation picked, so a solo task whose one
3656    /// implementer hits quota mid-run used to have nothing else to try. This
3657    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3658    /// unrotated roster — which is the only place the *other* candidates in
3659    /// the machine's roster still exist once `implementers` has been cut down
3660    /// to size.
3661    ///
3662    /// Walks forward from just past the seat's own original position in the
3663    /// roster, never wrapping back to the front: a later candidate slot (say
3664    /// `beta`, the roster's second entry) must fall through to the *next*
3665    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3666    /// almost certainly a different candidate's own agent already — and once
3667    /// the roster's tail is exhausted there is nothing left to fall through
3668    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3669    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3670    /// let this retry that id forever. The loop keeps falling through until
3671    /// an attempt lands something other than `Quota` or the roster's tail
3672    /// runs out of untried ids, at which point the seat is left exactly as
3673    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3674    /// `QuotaLoss` recorded, the candidate failed/empty.
3675    ///
3676    /// `sent` is taken mutably and updated with the fallback agent's spec:
3677    /// `resume_unconfirmed_commands`, which runs after this and also reads
3678    /// `sent`, must see whichever agent actually ended up answering the seat
3679    /// — reading the stale, original spec there would check session
3680    /// eligibility against the wrong CLI and could hand a fallback agent's
3681    /// session id to the agent that just lost the seat to quota.
3682    ///
3683    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3684    /// — `self.seat` only reuses state when the agent id is unchanged, so
3685    /// handing it a different id already gets this for free. Reusing the old
3686    /// seat would resume a different CLI's session as if it were a
3687    /// continuation of this one.
3688    ///
3689    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3690    /// a quota loss cuts an agent off mid-turn, so anything already in the
3691    /// tree is unfinished work, not a completed candidate a re-ask would pay
3692    /// for twice. A dirty tree is rescued into a commit first (the same
3693    /// neutral-identity rescue `implement`'s own outcome loop gives every
3694    /// candidate) so the next agent starts clean.
3695    ///
3696    /// The new agent gets the implementer's full prompt and full
3697    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3698    /// it has no session and no context, and is implementing the task from
3699    /// nothing, unlike a resumed drop which is only restating work already
3700    /// done.
3701    ///
3702    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3703    /// `implement` event, never into `self.state.quota` — that is what
3704    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3705    /// go unspent, and a seat that ultimately recovered on its second or
3706    /// third agent is not the stalled panel that check exists to catch. Only
3707    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3708    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3709    /// outcome loop already has — this helper never pushes to it itself.
3710    async fn resume_seat_handovers(
3711        &mut self,
3712        results: &mut [(usize, SeatState, AgentOutcome)],
3713        sent: &mut [SeatJob],
3714        prompts: &Prompts,
3715        run_id: &str,
3716    ) -> Result<()> {
3717        let instruction = seeded_instruction(&self.state);
3718        let language = self.state.config.graph.language.clone();
3719        let github_language = self.state.config.graph.github_language.clone();
3720        let brief = self
3721            .state
3722            .advice
3723            .as_ref()
3724            .and_then(|a| a.synthesis.as_deref())
3725            .map(str::to_owned);
3726        let attachments = self.state.attachments.clone();
3727        for (wi, seat, out) in results.iter_mut() {
3728            // Who holds the other candidate seats of this wave right now
3729            // (earlier handovers already written back to `sent`).
3730            let others: BTreeSet<String> = sent
3731                .iter()
3732                .enumerate()
3733                .filter(|(j, _)| j != wi)
3734                .map(|(_, j)| j.spec.id.clone())
3735                .collect();
3736            let Some(job) = sent.get_mut(*wi) else {
3737                continue;
3738            };
3739            // Where the seat's own original agent sits in the roster — the
3740            // fallback walk starts just past here, never at the front, so a
3741            // later candidate slot's quota loss does not fall back onto an
3742            // earlier slot's own agent.
3743            let start = self
3744                .roles
3745                .implementer_roster
3746                .iter()
3747                .position(|s| s.id == job.spec.id)
3748                .unwrap_or(0);
3749            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3750            let mut fallback_attempt = 0usize;
3751            let mut prev: Option<FailClass> = None;
3752            while let Some(cur) = FailClass::of(&*out) {
3753                if !should_hand_over(prev.as_ref(), &cur) {
3754                    break;
3755                }
3756                let Some(next) =
3757                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3758                        .cloned()
3759                else {
3760                    break;
3761                };
3762                tried.insert(next.id.clone());
3763                fallback_attempt += 1;
3764
3765                let coordination = self.coordinate(&job.cwd).await?;
3766                if let Ok(r) = git::rescue_commit(
3767                    &job.cwd,
3768                    &format!(
3769                        "magi: candidate {} (uncommitted work before {} fallback)",
3770                        seat.key,
3771                        if cur == FailClass::Quota {
3772                            "quota"
3773                        } else {
3774                            "handover"
3775                        }
3776                    ),
3777                )
3778                .await
3779                {
3780                    self.state.note_withheld("implement", &r.withheld);
3781                }
3782                drop(coordination);
3783
3784                record_handover(
3785                    &mut self.state,
3786                    "implement",
3787                    &seat.key,
3788                    &seat.agent,
3789                    &next.id,
3790                    &cur,
3791                    &fail_reason(&*out),
3792                );
3793                prev = Some(cur.clone());
3794
3795                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3796                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3797                // Kept in sync on `sent` itself, not just the local retry: a
3798                // later helper (`resume_unconfirmed_commands`) reads `sent`
3799                // after this one returns and must see whichever agent is now
3800                // occupying the seat, not the one that just quota'd out —
3801                // otherwise it would judge session/continuation eligibility
3802                // by the wrong CLI and could resend a fallback's session id
3803                // to the agent that lost it the seat in the first place.
3804                job.spec = next.clone();
3805                let mut retry = job.clone();
3806                retry.seat = new_seat;
3807                retry.prompt = prompt::implement_in(
3808                    &instruction,
3809                    &job.cwd.to_string_lossy(),
3810                    &language,
3811                    &github_language,
3812                    brief.as_deref(),
3813                    &attachments,
3814                );
3815                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3816                let cache = self.state.config.cache_dir();
3817                let ctx = WaveCtx {
3818                    carry_seats: false,
3819                    pauses: Some((&self.pause, &self.interrupt)),
3820                    run: run_id,
3821                    node: "implement",
3822                    prompts,
3823                    cache: cache.as_deref(),
3824                    round: None,
3825                };
3826                let (fallback_seat, fallback_out) = run_one(
3827                    retry,
3828                    Arc::clone(&self.sem),
3829                    &ctx,
3830                    &mut self.state,
3831                    fallback_attempt,
3832                )
3833                .await;
3834                *seat = fallback_seat;
3835                *out = fallback_out;
3836            }
3837        }
3838        Ok(())
3839    }
3840
3841    /// Ask an implement seat's own CLI to confirm what it started, once, when
3842    /// its reply reported a command whose completion status it never
3843    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3844    /// that does and does not mean.
3845    ///
3846    /// The completion contract this task asks for, extended to `implement`
3847    /// with the same signal `continue_fix_report` reads for the fixer,
3848    /// rather than a keyword search over the reply or a hard requirement on
3849    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3850    /// a candidate's CLI turn ended cleanly while a test run it had started
3851    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3852    /// named in it at all is untouched by this: `commands` is empty, so
3853    /// there is nothing to be unconfirmed.
3854    ///
3855    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3856    /// this is not about recovering edits that might already be on disk, it
3857    /// is about a result the seat itself never vouched for, which resuming
3858    /// asks for regardless of what the tree already holds. Bounded to one
3859    /// attempt for the same reason `resume_undelivered` is — this is the
3860    /// most expensive node in the graph — and a seat that still cannot
3861    /// confirm on that attempt is left as whatever its (possibly still
3862    /// unconfirmed) reply says; this does not invent a new "failed" reason
3863    /// for a candidate that otherwise produced a real, committed change.
3864    async fn resume_unconfirmed_commands(
3865        &mut self,
3866        results: &mut [(usize, SeatState, AgentOutcome)],
3867        sent: &[SeatJob],
3868        prompts: &Prompts,
3869        run_id: &str,
3870    ) {
3871        for (wi, seat, out) in results.iter_mut() {
3872            let AgentOutcome::Ok(o) = &*out else {
3873                continue;
3874            };
3875            if !has_unconfirmed_command(&o.commands) {
3876                continue;
3877            }
3878            let Some(job) = sent.get(*wi) else { continue };
3879            if !has_context(&job.spec, seat, job.sessions) {
3880                self.state.event(
3881                    "implement",
3882                    format!(
3883                        "{}: the reply named a command whose own CLI never confirmed the exit \
3884                         status of, but there is no session left to resume",
3885                        seat.key
3886                    ),
3887                );
3888                continue;
3889            }
3890            self.state.event(
3891                "implement",
3892                format!(
3893                    "{}: the reply named a command whose own CLI never confirmed the exit \
3894                     status of; resuming the conversation",
3895                    seat.key
3896                ),
3897            );
3898            let mut retry = job.clone();
3899            retry.seat = seat.clone();
3900            retry.prompt = prompt::resume_incomplete(
3901                "a command in your last reply had no confirmed exit status",
3902            );
3903            retry.timeout = retry_budget(job.timeout, true);
3904            retry.stem = format!("{}-confirm", job.stem);
3905            let cache = self.state.config.cache_dir();
3906            let ctx = WaveCtx {
3907                carry_seats: false,
3908                pauses: Some((&self.pause, &self.interrupt)),
3909                run: run_id,
3910                node: "implement",
3911                prompts,
3912                cache: cache.as_deref(),
3913                round: None,
3914            };
3915            let (resumed_seat, resumed) =
3916                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3917            *seat = resumed_seat;
3918            *out = resumed;
3919        }
3920    }
3921
3922    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3923    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3924    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3925    /// that motivated this.
3926    ///
3927    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3928    /// own nudge loop already covers for judge/review/vote seats, and not a
3929    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3930    /// implement seats: here the CLI turn genuinely finished while the node's
3931    /// own work — the fixer's account of what it did — had not. Gated purely
3932    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3933    /// reply, never on any wording in it, so a fixer whose valid, first-try
3934    /// `FixReport` happens to mention having waited on a background test is
3935    /// never resumed — the `Ok(report)` branch at the call site returns
3936    /// before this is ever invoked.
3937    ///
3938    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3939    /// attempt ([`retry_budget`]), nothing attempted once the session is
3940    /// gone, and a quota hit ends the loop immediately rather than retrying a
3941    /// rate limit that fails the same way again.
3942    async fn continue_fix_report(
3943        &mut self,
3944        mut seat: SeatState,
3945        parse_err: String,
3946        job: &SeatJob,
3947        prompts: &Prompts,
3948        run_id: &str,
3949        round: usize,
3950    ) -> (
3951        SeatState,
3952        Option<FixReport>,
3953        Option<String>,
3954        ContinuationRecord,
3955    ) {
3956        let mut last_err = parse_err;
3957        let mut cumulative_wait_ms = 0u64;
3958        let mut attempts = 0usize;
3959        loop {
3960            if !has_context(&job.spec, &seat, job.sessions) {
3961                self.state.event(
3962                    "fix",
3963                    format!(
3964                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3965                         session left to resume into"
3966                    ),
3967                );
3968                let outcome = if attempts == 0 {
3969                    ContinuationOutcome::NoSession
3970                } else {
3971                    ContinuationOutcome::Exhausted
3972                };
3973                return (
3974                    seat,
3975                    None,
3976                    Some(format!("unparsable fix report: {last_err}")),
3977                    ContinuationRecord {
3978                        attempts,
3979                        cumulative_wait_ms,
3980                        outcome,
3981                    },
3982                );
3983            }
3984            if attempts >= MAX_FIX_CONTINUATIONS {
3985                self.state.event(
3986                    "fix",
3987                    format!(
3988                        "round {round}: fixer's reply still had no adoption report after \
3989                         {attempts} continuation(s) ({last_err}); giving up"
3990                    ),
3991                );
3992                return (
3993                    seat,
3994                    None,
3995                    Some(format!(
3996                        "unparsable fix report after {attempts} continuation(s): {last_err}"
3997                    )),
3998                    ContinuationRecord {
3999                        attempts,
4000                        cumulative_wait_ms,
4001                        outcome: ContinuationOutcome::Exhausted,
4002                    },
4003                );
4004            }
4005            attempts += 1;
4006            self.state.event(
4007                "fix",
4008                format!(
4009                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4010                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4011                ),
4012            );
4013            let mut retry = job.clone();
4014            retry.seat = seat.clone();
4015            retry.prompt = prompt::resume_incomplete(&last_err);
4016            retry.timeout = retry_budget(job.timeout, true);
4017            retry.stem = format!("{}-continue{attempts}", job.stem);
4018            let cache = self.state.config.cache_dir();
4019            let ctx = WaveCtx {
4020                carry_seats: false,
4021                pauses: Some((&self.pause, &self.interrupt)),
4022                run: run_id,
4023                node: "fix",
4024                prompts,
4025                cache: cache.as_deref(),
4026                round: Some(round),
4027            };
4028            let (resumed_seat, resumed_out) = run_one(
4029                retry,
4030                Arc::clone(&self.sem),
4031                &ctx,
4032                &mut self.state,
4033                attempts,
4034            )
4035            .await;
4036            seat = resumed_seat;
4037            match resumed_out {
4038                AgentOutcome::Ok(o) => {
4039                    cumulative_wait_ms += o.duration_ms;
4040                    match verdict::extract_json::<FixReport>(&o.text) {
4041                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4042                            self.state.event(
4043                                "fix",
4044                                format!(
4045                                    "round {round}: fixer's adoption report recovered after \
4046                                     {attempts} continuation(s)"
4047                                ),
4048                            );
4049                            return (
4050                                seat,
4051                                Some(report),
4052                                None,
4053                                ContinuationRecord {
4054                                    attempts,
4055                                    cumulative_wait_ms,
4056                                    outcome: ContinuationOutcome::Resumed,
4057                                },
4058                            );
4059                        }
4060                        // The report parsed, but this same reply's own
4061                        // CommandEvidence — the identical record `state.jobs`
4062                        // renders — names a command whose CLI never
4063                        // confirmed an exit status. Read together, that is
4064                        // not a resolved answer: keep nudging rather than
4065                        // accept a report standing next to a command the
4066                        // seat's own CLI cannot vouch for.
4067                        Ok(_) => {
4068                            last_err = "the reply parsed, but it reported a command whose own CLI \
4069                                 never confirmed an exit status"
4070                                .to_owned();
4071                        }
4072                        Err(e) => last_err = e.to_string(),
4073                    }
4074                }
4075                AgentOutcome::Quota(o) => {
4076                    cumulative_wait_ms += o.duration_ms;
4077                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4078                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4079                    self.state.quota.push(loss);
4080                    self.state.event(
4081                        "fix",
4082                        format!(
4083                            "round {round}: continuation rate limited (quota); not retrying now"
4084                        ),
4085                    );
4086                    return (
4087                        seat,
4088                        None,
4089                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4090                        ContinuationRecord {
4091                            attempts,
4092                            cumulative_wait_ms,
4093                            outcome: ContinuationOutcome::QuotaLost,
4094                        },
4095                    );
4096                }
4097                AgentOutcome::Dropped(o) => {
4098                    cumulative_wait_ms += o.duration_ms;
4099                    let why = o
4100                        .dropped
4101                        .as_ref()
4102                        .map(|d| d.why.as_str())
4103                        .unwrap_or("the CLI ended the stream without delivering its answer");
4104                    last_err = format!("the CLI dropped the stream ({why})");
4105                }
4106                AgentOutcome::Failed(e) => last_err = e,
4107                // The continuation was never started; the report stays lost
4108                // and the caller records that, without any handover.
4109                AgentOutcome::ResourceBlocked(e) => {
4110                    return (
4111                        seat,
4112                        None,
4113                        Some(format!("the continuation was not started: {e}")),
4114                        ContinuationRecord {
4115                            attempts: attempts.saturating_sub(1),
4116                            cumulative_wait_ms,
4117                            outcome: ContinuationOutcome::NoSession,
4118                        },
4119                    );
4120                }
4121            }
4122        }
4123    }
4124
4125    fn after_implement(&mut self) -> Result<()> {
4126        if !self.state.candidate_preservation.is_empty() {
4127            bail!("candidate preservation incomplete; judging is unsafe");
4128        }
4129        // Scan every candidate patch once the set is complete.
4130        if self.state.leaks.is_empty() {
4131            let cfg = self.state.config.blind.clone();
4132            let mut leaks = Vec::new();
4133            for c in &self.state.candidates {
4134                let Some(patch) =
4135                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4136                else {
4137                    continue;
4138                };
4139                leaks.extend(blind::scan(
4140                    &format!("candidate {} patch", c.label),
4141                    &patch,
4142                    &cfg.vendor_tokens,
4143                ));
4144            }
4145            if !leaks.is_empty() {
4146                let summary = leaks
4147                    .iter()
4148                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4149                    .collect::<Vec<_>>()
4150                    .join(", ");
4151                match cfg.on_leak {
4152                    LeakPolicy::Fail => {
4153                        self.state.status = RunStatus::Failed;
4154                        self.state
4155                            .event("blind", format!("vendor text in a patch: {summary}"));
4156                        self.state.leaks = leaks;
4157                        self.state.save()?;
4158                        self.settle_questions();
4159                        bail!(
4160                            "blind.on_leak = \"fail\" and vendor text reached a \
4161                             judged patch: {summary}"
4162                        );
4163                    }
4164                    LeakPolicy::Redact => self.state.event(
4165                        "blind",
4166                        format!("redacting vendor text for judging: {summary}"),
4167                    ),
4168                    LeakPolicy::Warn => self.state.event(
4169                        "blind",
4170                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4171                    ),
4172                }
4173                self.state.leaks = leaks;
4174            }
4175        }
4176
4177        if self.state.viable().is_empty() {
4178            if self.state.all_candidates_verified_noop() {
4179                // Every candidate agreed, with evidence the adoption guard
4180                // accepted, that nothing belongs in this worktree. That is
4181                // not the same fact as a candidate that simply failed to
4182                // write anything, and settling it as an ordinary `Failed`
4183                // (see `SCHEMA`'s doc for schema 10) is what let two of
4184                // task 391f's attempts burn a retry each re-discovering the
4185                // same already-landed fix. Terminal either way, so `judge`
4186                // must never run over an empty candidate set — unlike the
4187                // `Failed` branch below this returns `Ok`, not an error:
4188                // nothing here failed.
4189                self.state.status = RunStatus::VerifiedNoop;
4190                self.state.save()?;
4191                self.settle_questions();
4192                return Ok(());
4193            }
4194            self.state.status = RunStatus::Failed;
4195            self.state.save()?;
4196            self.settle_questions();
4197            bail!("no candidate produced a change; nothing to judge");
4198        }
4199        self.state.status = RunStatus::Judging;
4200        self.state.save()?;
4201        Ok(())
4202    }
4203
4204    // --------------------------------------------------------------- judge
4205
4206    async fn judge(&mut self) -> Result<()> {
4207        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4208        // agent files with `magi task add` name the run that paid for it. The
4209        // prompt overlay is cloned alongside it because the waves borrow it
4210        // while `self` is mutably borrowed by the node's own bookkeeping.
4211        let run_id = self.state.id.clone();
4212        let prompts = self.state.config.prompts.clone();
4213        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4214            return Ok(());
4215        }
4216        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4217        if viable.len() == 1 {
4218            // Recorded so this is a one-time event: `judgements` stays empty
4219            // either way, which without this flag is indistinguishable from
4220            // "not yet judged" on the next reentry — and status is left
4221            // untouched, so a later node's conclusion (e.g. `Blocked` after
4222            // the review budget ran out) survives a resume instead of being
4223            // clobbered back to `Judging` by this node running again.
4224            self.state.judge_skipped = true;
4225            self.state.event(
4226                "judge",
4227                format!(
4228                    "only candidate {} produced a change; judging skipped",
4229                    viable[0].label
4230                ),
4231            );
4232            self.state.save()?;
4233            return Ok(());
4234        }
4235        self.state.status = RunStatus::Judging;
4236
4237        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4238        let language = self.state.config.graph.language.clone();
4239        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4240        let sessions = self.state.config.graph.sessions;
4241        let artifacts = agent::artifacts_dir(&self.state.dir());
4242        let root = self.state.worktree_root();
4243        let base_short = short(&self.state.base_commit);
4244
4245        let mut jobs = Vec::new();
4246        let mut orders = Vec::new();
4247        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4248            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4249            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4250            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4251            let seat_key = format!("judge-{}", j + 1);
4252            let seat = self.seat(&seat_key, &spec.id);
4253            jobs.push(SeatJob {
4254                prompt: prompt::judge(
4255                    &self.state.instruction,
4256                    &views,
4257                    self.roles.judges.len(),
4258                    &base_short,
4259                    &language,
4260                ),
4261                spec,
4262                seat,
4263                cwd: root.join(format!("judge-{}", j + 1)),
4264                timeout,
4265                allow_write: false,
4266                sessions,
4267                artifacts: artifacts.clone(),
4268                stem: format!("judge-{}", j + 1),
4269                handover: None,
4270            });
4271        }
4272
4273        self.state.event(
4274            "judge",
4275            format!(
4276                "{} judges ranking {} candidates blind",
4277                jobs.len(),
4278                viable.len()
4279            ),
4280        );
4281        let labels_for_check = labels.clone();
4282        let mut quota_losses = Vec::new();
4283        let cache = self.state.config.cache_dir();
4284        let ctx = WaveCtx {
4285            carry_seats: false,
4286            pauses: Some((&self.pause, &self.interrupt)),
4287            run: &run_id,
4288            node: "judge",
4289            prompts: &prompts,
4290            cache: cache.as_deref(),
4291            round: None,
4292        };
4293        let results = ask_json_wave::<Ranking>(
4294            jobs,
4295            Arc::clone(&self.sem),
4296            self.state.config.graph.retries,
4297            &self.roles.judge_roster,
4298            &ctx,
4299            &mut quota_losses,
4300            &mut self.state,
4301            &move |r: &Ranking| r.validate(&labels_for_check),
4302        )
4303        .await;
4304        if self.state.resource_block.is_some() {
4305            return self.stop_for_resource();
4306        }
4307        self.state.quota.extend(quota_losses);
4308
4309        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4310            let agent_id = seat.agent.clone();
4311            self.state.seats.insert(seat.key.clone(), seat);
4312            let mut record = Judgement {
4313                judge: j + 1,
4314                seat: format!("judge-{}", j + 1),
4315                agent: agent_id,
4316                ranking: Vec::new(),
4317                reasons: BTreeMap::new(),
4318                confidence: None,
4319                strengths: BTreeMap::new(),
4320                order: orders[j].clone(),
4321                failed: None,
4322                duration_ms: 0,
4323            };
4324            match res {
4325                Ok((ranking, out)) => {
4326                    record.ranking = ranking.normalized();
4327                    record.reasons = ranking.reasons;
4328                    record.strengths = ranking.strengths;
4329                    record.confidence = ranking.confidence;
4330                    record.duration_ms = out.duration_ms;
4331                    self.state.event(
4332                        "judge",
4333                        format!(
4334                            "judge {} ranked {}",
4335                            j + 1,
4336                            record.ranking.iter().collect::<String>()
4337                        ),
4338                    );
4339                }
4340                Err(e) => {
4341                    record.failed = Some(e.to_string());
4342                    self.state
4343                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4344                }
4345            }
4346            self.state.judgements.push(record);
4347            self.state.save()?;
4348        }
4349        Ok(())
4350    }
4351
4352    // ---------------------------------------------------------- deliberate
4353
4354    async fn deliberate(&mut self) -> Result<()> {
4355        if self.hold_base_sync().await? {
4356            return Ok(());
4357        }
4358        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4359        // agent files with `magi task add` name the run that paid for it. The
4360        // prompt overlay is cloned alongside it because the waves borrow it
4361        // while `self` is mutably borrowed by the node's own bookkeeping.
4362        let run_id = self.state.id.clone();
4363        let prompts = self.state.config.prompts.clone();
4364        let rounds = self.state.config.graph.deliberate_rounds;
4365        // Resume unfinished rounds after an outage, but never reopen a tally.
4366        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4367            return Ok(());
4368        }
4369        let tops: Vec<char> = self
4370            .state
4371            .judgements
4372            .iter()
4373            .filter_map(|j| j.ranking.first().copied())
4374            .collect();
4375        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4376            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4377                self.state.event(
4378                    "deliberate",
4379                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4380                );
4381            }
4382            self.state.status = RunStatus::Voting;
4383            self.state.save()?;
4384            return Ok(());
4385        }
4386
4387        self.state.status = RunStatus::Deliberating;
4388        self.state.event(
4389            "deliberate",
4390            format!(
4391                "split: first choices were {} — opening {rounds} round(s)",
4392                tops.iter().collect::<String>()
4393            ),
4394        );
4395
4396        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4397        let language = self.state.config.graph.language.clone();
4398        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4399        let sessions = self.state.config.graph.sessions;
4400        let artifacts = agent::artifacts_dir(&self.state.dir());
4401        let root = self.state.worktree_root();
4402        let base_short = short(&self.state.base_commit);
4403
4404        // Judges argue in sequence so that a turn can answer the one before it;
4405        // that is the difference between deliberation and three parallel
4406        // monologues.
4407        for round in self.state.deliberation.len() + 1..=rounds {
4408            let mut turns: Vec<DeliberationTurn> = Vec::new();
4409            let mut round_losses = Vec::new();
4410            let mut asked = 0;
4411            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4412                if self.state.judgements[j].failed.is_some() {
4413                    continue;
4414                }
4415                let seat_key = format!("judge-{}", j + 1);
4416                let spec = self.occupant(&seat_key, spec);
4417                let mut seat = self.seat(&seat_key, &spec.id);
4418                let transcript = self.transcript(&turns, j);
4419                let build = |context: Option<&str>| {
4420                    prompt::deliberate(
4421                        &self.state.instruction,
4422                        context,
4423                        &transcript,
4424                        round,
4425                        rounds,
4426                        &language,
4427                    )
4428                };
4429                let block = self.candidate_block(&viable, &base_short);
4430                let full = build(Some(&block));
4431                let text = if has_context(&spec, &seat, sessions) {
4432                    build(None)
4433                } else {
4434                    full.clone()
4435                };
4436                let job = SeatJob {
4437                    spec,
4438                    seat: seat.clone(),
4439                    prompt: text,
4440                    cwd: root.join(format!("judge-{}", j + 1)),
4441                    timeout,
4442                    allow_write: false,
4443                    sessions,
4444                    artifacts: artifacts.clone(),
4445                    stem: format!("delib-{round}-judge-{}", j + 1),
4446                    handover: Some(full),
4447                };
4448                let cache = self.state.config.cache_dir();
4449                let ctx = WaveCtx {
4450                    carry_seats: false,
4451                    pauses: Some((&self.pause, &self.interrupt)),
4452                    run: &run_id,
4453                    node: "deliberate",
4454                    prompts: &prompts,
4455                    cache: cache.as_deref(),
4456                    round: None,
4457                };
4458                // A turn is never nudged (`retries` 0): a failed seat is
4459                // handed to the next roster agent, which gets the full
4460                // context. An empty answer is a turn, not a failure.
4461                let mut losses = Vec::new();
4462                asked += 1;
4463                let mut results = ask_wave_with::<String>(
4464                    vec![job],
4465                    Arc::clone(&self.sem),
4466                    0,
4467                    &self.roles.judge_roster,
4468                    &ctx,
4469                    &mut losses,
4470                    &mut self.state,
4471                    &|text: &str| {
4472                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4473                    },
4474                )
4475                .await;
4476                if self.state.resource_block.is_some() {
4477                    return self.stop_for_resource();
4478                }
4479                round_losses.extend(losses.iter().cloned());
4480                self.state.quota.extend(losses);
4481                let (updated, res, _) = results.pop().expect("one job in, one result out");
4482                seat = updated;
4483                let agent_id = seat.agent.clone();
4484                self.state.seats.insert(seat.key.clone(), seat);
4485                let body = match res {
4486                    Ok((body, _)) => body,
4487                    // Skip the seat; a CLI's raw error JSON is never read as
4488                    // this judge's position.
4489                    Err(e) => {
4490                        self.state
4491                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4492                        continue;
4493                    }
4494                };
4495                let tentative = verdict::extract_json::<Position>(&body)
4496                    .ok()
4497                    .and_then(|p| p.tentative)
4498                    .and_then(|s| s.trim().chars().next())
4499                    .map(|c| c.to_ascii_uppercase());
4500                self.state.event(
4501                    "deliberate",
4502                    format!(
4503                        "round {round}: judge {} now favours {}",
4504                        j + 1,
4505                        tentative.map_or("—".to_owned(), |c| c.to_string())
4506                    ),
4507                );
4508                turns.push(DeliberationTurn {
4509                    judge: j + 1,
4510                    agent: agent_id,
4511                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4512                    tentative,
4513                });
4514            }
4515            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4516                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4517                return self.stop_for_resource();
4518            }
4519            self.state
4520                .deliberation
4521                .push(DeliberationRound { round, turns });
4522            self.state.save()?;
4523        }
4524
4525        self.state.status = RunStatus::Voting;
4526        self.state.save()?;
4527        Ok(())
4528    }
4529
4530    // ---------------------------------------------------------------- vote
4531
4532    async fn vote(&mut self) -> Result<()> {
4533        if self.hold_base_sync().await? {
4534            return Ok(());
4535        }
4536        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4537        // agent files with `magi task add` name the run that paid for it. The
4538        // prompt overlay is cloned alongside it because the waves borrow it
4539        // while `self` is mutably borrowed by the node's own bookkeeping.
4540        let run_id = self.state.id.clone();
4541        let prompts = self.state.config.prompts.clone();
4542        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4543            return Ok(());
4544        }
4545        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4546        if viable.len() == 1 {
4547            return Ok(());
4548        }
4549        self.state.status = RunStatus::Voting;
4550
4551        let language = self.state.config.graph.language.clone();
4552        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4553        let sessions = self.state.config.graph.sessions;
4554        let artifacts = agent::artifacts_dir(&self.state.dir());
4555        let root = self.state.worktree_root();
4556        let base_short = short(&self.state.base_commit);
4557        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4558
4559        let mut jobs = Vec::new();
4560        let mut seats_at = Vec::new();
4561        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4562            if self
4563                .state
4564                .judgements
4565                .get(j)
4566                .is_some_and(|r| r.failed.is_some())
4567            {
4568                continue;
4569            }
4570            let seat_key = format!("judge-{}", j + 1);
4571            let spec = self.occupant(&seat_key, spec);
4572            let seat = self.seat(&seat_key, &spec.id);
4573            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4574            let text = if has_context(&spec, &seat, sessions) {
4575                prompt::final_vote(&viable, &language)
4576            } else {
4577                full.clone()
4578            };
4579            jobs.push(SeatJob {
4580                spec,
4581                seat,
4582                prompt: text,
4583                cwd: root.join(format!("judge-{}", j + 1)),
4584                timeout,
4585                allow_write: false,
4586                sessions,
4587                artifacts: artifacts.clone(),
4588                stem: format!("vote-judge-{}", j + 1),
4589                handover: Some(full),
4590            });
4591            seats_at.push(j);
4592        }
4593
4594        self.state.event(
4595            "vote",
4596            format!(
4597                "collecting {} final votes one by one, privately",
4598                jobs.len()
4599            ),
4600        );
4601        let allowed = viable.clone();
4602        let mut quota_losses = Vec::new();
4603        let cache = self.state.config.cache_dir();
4604        let ctx = WaveCtx {
4605            carry_seats: false,
4606            pauses: Some((&self.pause, &self.interrupt)),
4607            run: &run_id,
4608            node: "vote",
4609            prompts: &prompts,
4610            cache: cache.as_deref(),
4611            round: None,
4612        };
4613        let results = ask_json_wave::<FinalVote>(
4614            jobs,
4615            Arc::clone(&self.sem),
4616            self.state.config.graph.retries,
4617            &self.roles.judge_roster,
4618            &ctx,
4619            &mut quota_losses,
4620            &mut self.state,
4621            &move |v: &FinalVote| match v.label() {
4622                Some(c) if allowed.contains(&c) => Ok(()),
4623                other => bail!("vote {other:?} is not one of {allowed:?}"),
4624            },
4625        )
4626        .await;
4627        if self.state.resource_block.is_some() {
4628            return self.stop_for_resource();
4629        }
4630        self.state.quota.extend(quota_losses);
4631
4632        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4633            let agent_id = seat.agent.clone();
4634            self.state.seats.insert(seat.key.clone(), seat);
4635            let initial = self
4636                .state
4637                .judgements
4638                .get(j)
4639                .and_then(|r| r.ranking.first().copied());
4640            let mut record = VoteRecord {
4641                judge: j + 1,
4642                agent: agent_id,
4643                vote: None,
4644                reason: String::new(),
4645                changed: false,
4646            };
4647            match res {
4648                Ok((v, _)) => {
4649                    record.vote = v.label();
4650                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4651                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4652                    self.state.event(
4653                        "vote",
4654                        format!(
4655                            "judge {} voted {}{}",
4656                            j + 1,
4657                            record.vote.unwrap_or('?'),
4658                            if record.changed { " (changed)" } else { "" }
4659                        ),
4660                    );
4661                }
4662                Err(e) => {
4663                    self.state
4664                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4665                }
4666            }
4667            self.state.votes.push(record);
4668            self.state.save()?;
4669        }
4670        Ok(())
4671    }
4672
4673    // --------------------------------------------------------------- tally
4674
4675    fn tally(&mut self) -> Result<()> {
4676        if self.state.tally.is_some() {
4677            return Ok(());
4678        }
4679        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4680        let tops: Vec<char> = self
4681            .state
4682            .judgements
4683            .iter()
4684            .filter_map(|j| j.ranking.first().copied())
4685            .collect();
4686        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4687
4688        // A judge whose private vote failed still counted once, in the initial
4689        // ranking; using it beats discarding a whole seat.
4690        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4691        let mut cast: Vec<char> = Vec::new();
4692        for (i, j) in self.state.judgements.iter().enumerate() {
4693            let vote = self
4694                .state
4695                .votes
4696                .iter()
4697                .find(|v| v.judge == i + 1)
4698                .and_then(|v| v.vote)
4699                .or_else(|| j.ranking.first().copied());
4700            if let Some(v) = vote {
4701                *first_choice.entry(v).or_insert(0) += 1;
4702                cast.push(v);
4703            }
4704        }
4705
4706        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4707        for j in &self.state.judgements {
4708            let n = j.ranking.len();
4709            for (pos, label) in j.ranking.iter().enumerate() {
4710                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4711            }
4712        }
4713
4714        let best = first_choice.values().copied().max().unwrap_or(0);
4715        let mut leaders: Vec<char> = first_choice
4716            .iter()
4717            .filter(|(_, v)| **v == best)
4718            .map(|(k, _)| *k)
4719            .collect();
4720        let mut tie_break = None;
4721        if leaders.len() > 1 {
4722            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4723            let borda_leaders: Vec<char> = leaders
4724                .iter()
4725                .copied()
4726                .filter(|l| borda[l] == top_borda)
4727                .collect();
4728            tie_break = Some(if borda_leaders.len() == 1 {
4729                format!(
4730                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4731                    leaders.len()
4732                )
4733            } else {
4734                format!(
4735                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4736                    leaders.len()
4737                )
4738            });
4739            leaders = borda_leaders;
4740            leaders.sort_unstable();
4741        }
4742        let winner = *leaders
4743            .first()
4744            .or(viable.first())
4745            .context("no candidate to declare a winner from")?;
4746
4747        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4748        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4749        let deliberated = !self.state.deliberation.is_empty();
4750
4751        // Whose verdict is this? A rate-limited seat is absent even if it
4752        // ranked before the limit hit, so presence is measured against the
4753        // recorded losses, not just "did a ranking ever appear".
4754        let quota_seats: std::collections::BTreeSet<&str> =
4755            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4756        let mut present = 0usize;
4757        for (i, j) in self.state.judgements.iter().enumerate() {
4758            if quota_seats.contains(j.seat.as_str()) {
4759                continue;
4760            }
4761            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4762            let voted = self
4763                .state
4764                .votes
4765                .iter()
4766                .any(|v| v.judge == i + 1 && v.vote.is_some());
4767            if ranked || voted {
4768                present += 1;
4769            }
4770        }
4771        // Strict majority of the configured panel. A bare majority is real
4772        // signal we can act on, while a minority verdict must never stand in
4773        // for a healthy one. A one-candidate run needs no panel at all, and
4774        // `judges` stays `0` rather than the roster size a panel that never
4775        // sat would otherwise be credited with.
4776        let needs_quorum = viable.len() > 1;
4777        let judges_total = if needs_quorum {
4778            self.roles.judges.len()
4779        } else {
4780            0
4781        };
4782        let quorum = if needs_quorum {
4783            judges_total / 2 + 1
4784        } else {
4785            0
4786        };
4787        let met_quorum = !needs_quorum || present >= quorum;
4788        let uncontested = (!needs_quorum).then(|| {
4789            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4790        });
4791
4792        self.state.event(
4793            "tally",
4794            match &uncontested {
4795                Some(reason) => format!("winner {winner} — {reason}"),
4796                None => format!(
4797                    "winner {winner} — votes {} | initial {} | {} changed | \
4798                     {present}/{judges_total} judges{}",
4799                    first_choice
4800                        .iter()
4801                        .map(|(k, v)| format!("{k}:{v}"))
4802                        .collect::<Vec<_>>()
4803                        .join(" "),
4804                    if unanimous_initial {
4805                        "unanimous"
4806                    } else {
4807                        "split"
4808                    },
4809                    changed_votes,
4810                    if met_quorum {
4811                        String::new()
4812                    } else {
4813                        format!(" — below quorum ({quorum} required)")
4814                    },
4815                ),
4816            },
4817        );
4818        if !met_quorum {
4819            self.state.event(
4820                "stall",
4821                format!(
4822                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4823                     the run stops here, resumable"
4824                ),
4825            );
4826        }
4827        self.state.tally = Some(Tally {
4828            first_choice,
4829            borda,
4830            winner,
4831            rankings: tops.len(),
4832            unanimous_initial,
4833            deliberated,
4834            changed_votes,
4835            unanimous_final,
4836            tie_break,
4837            judges: judges_total,
4838            present,
4839            quorum,
4840            met_quorum,
4841            uncontested,
4842        });
4843        self.state.status = if met_quorum {
4844            RunStatus::Reviewing
4845        } else {
4846            RunStatus::Stalled
4847        };
4848        self.state.save()?;
4849        Ok(())
4850    }
4851
4852    // ------------------------------------------------------------- recover
4853
4854    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4855    /// resumed toward completion once the transient cause clears.
4856    ///
4857    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4858    /// it toward the quorum, which is exactly the set of seats whose absence
4859    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4860    /// not depend on which node happened to hit the limit), or an ordinary
4861    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4862    /// seat is never disturbed.
4863    ///
4864    /// A seat that now answers with a usable ranking is "recovered": its
4865    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4866    /// `tally` counts it present again), and its vote re-collected. A seat that
4867    /// still fails keeps its loss and stays absent.
4868    ///
4869    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4870    /// to review/gate/merge), `false` when it is still below quorum (the run
4871    /// stays `Stalled`, still resumable for a later retry).
4872    #[allow(clippy::too_many_lines)]
4873    async fn recover_stall(&mut self) -> Result<bool> {
4874        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4875        // agent files with `magi task add` name the run that paid for it. The
4876        // prompt overlay is cloned alongside it because the waves borrow it
4877        // while `self` is mutably borrowed by the node's own bookkeeping.
4878        let run_id = self.state.id.clone();
4879        let prompts = self.state.config.prompts.clone();
4880        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4881        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4882        // is what keeps a non-quota collapse — or a quota loss recorded at the
4883        // deliberate node — from being a permanent dead-end on `--resume`.
4884        let quota_seats: BTreeSet<&str> =
4885            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4886        let absent: Vec<String> = self
4887            .state
4888            .judgements
4889            .iter()
4890            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4891            .map(|j| j.seat.clone())
4892            .collect();
4893        if absent.is_empty() {
4894            return Ok(false);
4895        }
4896        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4897        if viable.len() <= 1 {
4898            return Ok(false);
4899        }
4900        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4901        let language = self.state.config.graph.language.clone();
4902        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4903        let sessions = self.state.config.graph.sessions;
4904        let artifacts = agent::artifacts_dir(&self.state.dir());
4905        let root = self.state.worktree_root();
4906        let base_short = short(&self.state.base_commit);
4907        let candidates: Vec<Candidate> = viable.clone();
4908
4909        // Map each absent seat key to its 0-based position in `roles.judges`.
4910        let mut positions: Vec<usize> = absent
4911            .iter()
4912            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4913            .collect();
4914        if positions.is_empty() {
4915            return Ok(false);
4916        }
4917        positions.sort_unstable();
4918        positions.dedup();
4919
4920        // Re-rank the lost seats, one blind prompt each.
4921        let mut judge_jobs = Vec::new();
4922        for &j in &positions {
4923            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4924            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4925            let seat_key = format!("judge-{}", j + 1);
4926            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4927            let seat = self.seat(&seat_key, &spec.id);
4928            judge_jobs.push(SeatJob {
4929                spec,
4930                seat,
4931                prompt: prompt::judge(
4932                    &self.state.instruction,
4933                    &views,
4934                    self.roles.judges.len(),
4935                    &base_short,
4936                    &language,
4937                ),
4938                cwd: root.join(seat_key),
4939                timeout,
4940                allow_write: false,
4941                sessions,
4942                artifacts: artifacts.clone(),
4943                stem: format!("judge-{}-recover", j + 1),
4944                handover: None,
4945            });
4946        }
4947
4948        let labels_for_check = labels.clone();
4949        let mut judge_losses = Vec::new();
4950        let retries = self.state.config.graph.retries;
4951        let cache = self.state.config.cache_dir();
4952        let ctx = WaveCtx {
4953            carry_seats: false,
4954            pauses: Some((&self.pause, &self.interrupt)),
4955            run: &run_id,
4956            node: "judge",
4957            prompts: &prompts,
4958            cache: cache.as_deref(),
4959            round: None,
4960        };
4961        let results = ask_json_wave::<Ranking>(
4962            judge_jobs,
4963            Arc::clone(&self.sem),
4964            retries,
4965            &self.roles.judge_roster,
4966            &ctx,
4967            &mut judge_losses,
4968            &mut self.state,
4969            &move |r: &Ranking| r.validate(&labels_for_check),
4970        )
4971        .await;
4972        if self.state.resource_block.is_some() {
4973            self.stop_for_resource()?;
4974            return Ok(false);
4975        }
4976
4977        // Refresh the judgement of every seat that ranked again.
4978        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4979        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4980            let agent_id = seat.agent.clone();
4981            self.state.seats.insert(seat.key.clone(), seat);
4982            let record = &mut self.state.judgements[j];
4983            match res {
4984                Ok((ranking, out)) => {
4985                    record.agent = agent_id;
4986                    record.ranking = ranking.normalized();
4987                    record.reasons = ranking.reasons;
4988                    record.strengths = ranking.strengths;
4989                    record.confidence = ranking.confidence;
4990                    record.failed = None;
4991                    record.duration_ms = out.duration_ms;
4992                    recovered.insert(j);
4993                    self.state.event(
4994                        "recover",
4995                        format!("judge {} ranked again after the limit", j + 1),
4996                    );
4997                }
4998                Err(e) => {
4999                    self.state
5000                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5001                }
5002            }
5003        }
5004
5005        // Re-ask the votes of the seats that recovered a ranking.
5006        let mut vote_jobs = Vec::new();
5007        let mut vote_pos: Vec<usize> = Vec::new();
5008        for &j in &recovered {
5009            let seat_key = format!("judge-{}", j + 1);
5010            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5011            let seat = self.seat(&seat_key, &spec.id);
5012            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5013            let text = if has_context(&spec, &seat, sessions) {
5014                prompt::final_vote(&labels, &language)
5015            } else {
5016                full.clone()
5017            };
5018            vote_jobs.push(SeatJob {
5019                spec,
5020                seat,
5021                prompt: text,
5022                cwd: root.join(seat_key),
5023                timeout,
5024                allow_write: false,
5025                sessions,
5026                artifacts: artifacts.clone(),
5027                stem: format!("vote-judge-{}-recover", j + 1),
5028                handover: Some(full),
5029            });
5030            vote_pos.push(j);
5031        }
5032        let allowed = labels.clone();
5033        let mut vote_losses = Vec::new();
5034        let vote_retries = self.state.config.graph.retries;
5035        let vote_cache = self.state.config.cache_dir();
5036        let ctx = WaveCtx {
5037            carry_seats: false,
5038            pauses: Some((&self.pause, &self.interrupt)),
5039            run: &run_id,
5040            node: "vote",
5041            prompts: &prompts,
5042            cache: vote_cache.as_deref(),
5043            round: None,
5044        };
5045        let votes = ask_json_wave::<FinalVote>(
5046            vote_jobs,
5047            Arc::clone(&self.sem),
5048            vote_retries,
5049            &self.roles.judge_roster,
5050            &ctx,
5051            &mut vote_losses,
5052            &mut self.state,
5053            &move |v: &FinalVote| match v.label() {
5054                Some(c) if allowed.contains(&c) => Ok(()),
5055                other => bail!("vote {other:?} is not one of {allowed:?}"),
5056            },
5057        )
5058        .await;
5059        if self.state.resource_block.is_some() {
5060            self.stop_for_resource()?;
5061            return Ok(false);
5062        }
5063        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5064            let agent_id = seat.agent.clone();
5065            self.state.seats.insert(seat.key.clone(), seat);
5066            match res {
5067                Ok((v, _)) => {
5068                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5069                        rec.vote = v.label();
5070                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5071                    } else {
5072                        self.state.votes.push(VoteRecord {
5073                            judge: j + 1,
5074                            agent: agent_id,
5075                            vote: v.label(),
5076                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5077                            changed: false,
5078                        });
5079                    }
5080                    self.state.event(
5081                        "recover",
5082                        format!("judge {} voted again after the limit", j + 1),
5083                    );
5084                }
5085                Err(e) => {
5086                    self.state
5087                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5088                }
5089            }
5090        }
5091
5092        // A seat that ranked again is present even if its re-vote failed —
5093        // `tally` falls back to the initial ranking's first choice — so clear
5094        // its quota loss. Seats that still fail keep theirs and stay absent.
5095        let recovered_keys: BTreeSet<String> = recovered
5096            .iter()
5097            .map(|&j| format!("judge-{}", j + 1))
5098            .collect();
5099        self.state
5100            .quota
5101            .retain(|q| !recovered_keys.contains(&q.seat));
5102        // A seat that hit the limit again is a fresh loss, not the old one:
5103        // replace the stale entry so the history stays one-per-seat and the
5104        // daemon can tell this attempt's loss from a previous session's.
5105        for loss in judge_losses.into_iter().chain(vote_losses) {
5106            if recovered_keys.contains(&loss.seat) {
5107                continue;
5108            }
5109            self.state.quota.retain(|q| q.seat != loss.seat);
5110            self.state.quota.push(loss);
5111        }
5112
5113        // Recompute the verdict from the refreshed panel.
5114        self.state.tally = None;
5115        self.tally()?;
5116        Ok(self
5117            .state
5118            .tally
5119            .as_ref()
5120            .map(|t| t.met_quorum)
5121            .unwrap_or(false))
5122    }
5123
5124    // ---------------------------------------------------------------- graft
5125
5126    /// Port the strengths the judges attributed to the losing candidates onto
5127    /// the winner, once, between the tally and the review loop.
5128    ///
5129    /// Best-effort by construction: it returns nothing and fails nothing. A
5130    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5131    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5132    /// the run carries on as if the phase were off. See [`graft`] for the
5133    /// decisions and `AGENTS.md` for the invariants.
5134    ///
5135    /// The one exception is a rollback that could not be confirmed: the
5136    /// rejected commit may still be the winner's tip, so the run is blocked
5137    /// (resumable; the record stays `Running`, which makes a resume retry the
5138    /// restore) instead of reviewing, gating and merging it.
5139    async fn graft(&mut self) -> Result<()> {
5140        let Err(e) = self.graft_inner().await else {
5141            return Ok(());
5142        };
5143        if e.is::<crate::repo_lock::ResourceBlocked>() {
5144            return Err(e);
5145        }
5146        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5147            self.state.status = RunStatus::Blocked;
5148            self.state.event("graft", format!("blocked: {e:#}"));
5149            self.state.save()?;
5150            return Err(e);
5151        }
5152        // An error after the `Running` record was saved may have left the
5153        // fixer's work in the tree: the record must not stay unsettled
5154        // (a later resume would reset past the review fixes), so confirm the
5155        // restore now, or block.
5156        if let Some(rec) = self.state.graft.clone()
5157            && !rec.outcome.settled()
5158        {
5159            if let Some(winner) = self.state.winner().cloned() {
5160                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5161                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5162                        return Err(re);
5163                    }
5164                    self.state.status = RunStatus::Blocked;
5165                    self.state.event("graft", format!("blocked: {re:#}"));
5166                    self.state.save()?;
5167                    return Err(re);
5168                }
5169            }
5170            if let Some(g) = self.state.graft.as_mut() {
5171                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5172            }
5173        }
5174        self.state.event("graft", format!("skipped: {e:#}"));
5175        if let Err(e) = self.state.save() {
5176            tracing::warn!("save after graft: {e:#}");
5177        }
5178        Ok(())
5179    }
5180
5181    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5182    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5183    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5184        let _coordination = self.coordinate(wt).await?;
5185        crate::recovery::restore_repair(wt, pre)
5186            .await
5187            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5188    }
5189
5190    /// A skip is a run event, recorded once however often the node is re-entered.
5191    fn graft_skipped(&mut self, why: &str) {
5192        let message = format!("skipped: {why}");
5193        if !self
5194            .state
5195            .events
5196            .iter()
5197            .any(|e| e.node == "graft" && e.message == message)
5198        {
5199            self.state.event("graft", message);
5200        }
5201    }
5202
5203    async fn graft_inner(&mut self) -> Result<()> {
5204        // A round that was started and never finished (crash, kill): the
5205        // fixer may have left anything in the tree, so put the winner back.
5206        if let Some(rec) = self.state.graft.clone()
5207            && !rec.outcome.settled()
5208        {
5209            // Reviews exist only if the graft ended without its record being
5210            // settled (a swallowed error): the tree has moved on since, and
5211            // a reset to `pre` would discard the review fixes.
5212            if self.state.reviews.is_empty()
5213                && let Some(winner) = self.state.winner().cloned()
5214            {
5215                self.graft_restore(&winner.worktree, &rec.pre).await?;
5216            }
5217            if rec.outcome == GraftOutcome::WaitingForRestore {
5218                self.state.graft = None;
5219                self.state.save()?;
5220            } else {
5221                if let Some(g) = self.state.graft.as_mut() {
5222                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5223                }
5224                self.state.event(
5225                    "graft",
5226                    "rolled back: the previous round was interrupted; the winner is untouched",
5227                );
5228                self.state.save()?;
5229                return Ok(());
5230            }
5231        }
5232        let plan = match graft::plan(&self.state) {
5233            Ok(plan) => plan,
5234            Err(skip) => {
5235                if skip != graft::Skip::AlreadyDone {
5236                    self.graft_skipped(skip.reason());
5237                    self.state.save()?;
5238                }
5239                return Ok(());
5240            }
5241        };
5242        let Some(winner) = self.state.winner().cloned() else {
5243            return Ok(());
5244        };
5245        let wt = winner.worktree.clone();
5246        if !git::is_clean(&wt).await? {
5247            self.graft_skipped("the winner's worktree has uncommitted changes");
5248            self.state.save()?;
5249            return Ok(());
5250        }
5251        let pre = git::rev_parse(&wt, "HEAD").await?;
5252        // Saved before the fixer is called: a stop from here on is repaired
5253        // by the branch above on the next entry.
5254        self.state.graft = Some(GraftRecord {
5255            pre: pre.clone(),
5256            post: None,
5257            lines: None,
5258            limit: None,
5259            agent: None,
5260            outcome: GraftOutcome::Running,
5261            requested: graft::requested(&plan),
5262            adoption: None,
5263            adoption_error: None,
5264        });
5265        self.state.event(
5266            "graft",
5267            format!(
5268                "porting strengths of candidate(s) {} onto {}",
5269                plan.strengths
5270                    .iter()
5271                    .map(|(l, _, _)| l.to_string())
5272                    .collect::<Vec<_>>()
5273                    .join(", "),
5274                plan.winner
5275            ),
5276        );
5277        self.state.save()?;
5278
5279        let fix_prompt = prompt::graft(
5280            &self.state.instruction,
5281            plan.winner,
5282            &plan.strengths,
5283            &self.state.config.graph.language,
5284        );
5285        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5286        let sessions = self.state.config.graph.sessions;
5287        let artifacts = agent::artifacts_dir(&self.state.dir());
5288        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5289        let (_, seat, out) = self
5290            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5291                SeatJob {
5292                    prompt: fix_prompt.clone(),
5293                    spec,
5294                    seat,
5295                    cwd: wt.clone(),
5296                    timeout,
5297                    allow_write: true,
5298                    sessions,
5299                    artifacts: artifacts.clone(),
5300                    stem: "graft".to_owned(),
5301                    handover: None,
5302                }
5303            })
5304            .await;
5305        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5306            // Preserve the need to restore earlier fallback edits without
5307            // confusing an unstarted seat with an interrupted invocation.
5308            self.state.graft.as_mut().expect("graft record").outcome =
5309                GraftOutcome::WaitingForRestore;
5310            return self.stop_for_resource();
5311        }
5312        let mut why: Option<String> = None;
5313        match &out {
5314            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5315                why = Some("the fixer produced nothing usable".to_owned());
5316            }
5317            AgentOutcome::Ok(_) => {}
5318            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5319            AgentOutcome::Quota(o) => {
5320                self.state.quota.push(QuotaLoss::from_report(
5321                    seat.key.clone(),
5322                    "graft",
5323                    o.quota.as_ref(),
5324                ));
5325                why = Some("rate limited (quota)".to_owned());
5326            }
5327            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5328                why = Some(format!(
5329                    "the fixer failed: {}",
5330                    e.lines()
5331                        .next()
5332                        .unwrap_or("")
5333                        .chars()
5334                        .take(160)
5335                        .collect::<String>()
5336                ));
5337            }
5338        }
5339        let agent_id = seat.agent.clone();
5340        self.state.seats.insert(seat.key.clone(), seat);
5341
5342        let mut post = None;
5343        let mut lines = None;
5344        let _coordination = self.coordinate(&wt).await?;
5345        if why.is_none() {
5346            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5347            if let Ok(r) = &rescued {
5348                self.state.note_withheld("graft", &r.withheld);
5349            }
5350            let head = git::rev_parse(&wt, "HEAD").await?;
5351            // What is measured must be what gets reviewed and gated: a failed
5352            // rescue, or anything still uncommitted (withheld lockfiles
5353            // aside, which are never part of the tree), rejects the graft.
5354            let dirty = match &rescued {
5355                Ok(r) => git::status_porcelain(&wt)
5356                    .await
5357                    .map(|st| {
5358                        st.lines().any(|l| {
5359                            !r.withheld
5360                                .iter()
5361                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5362                        })
5363                    })
5364                    .unwrap_or(true),
5365                Err(_) => true,
5366            };
5367            if dirty {
5368                why = Some("the fixer left changes that could not be committed".to_owned());
5369            } else if head == pre {
5370                why = Some("the fixer changed nothing".to_owned());
5371            } else {
5372                lines = git::changed_lines(&wt, &pre, &head).await;
5373                post = Some(head);
5374            }
5375        }
5376        let (adoption, adoption_error) = match &out {
5377            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5378            _ => (None, None),
5379        };
5380        let requested = graft::requested(&plan);
5381        let outcome = match why {
5382            None => {
5383                self.state.event(
5384                    "graft",
5385                    format!(
5386                        "applied: {}",
5387                        lines.map_or_else(
5388                            || "changed lines unavailable".to_owned(),
5389                            |n| format!("{n} changed lines")
5390                        )
5391                    ),
5392                );
5393                GraftOutcome::Applied
5394            }
5395            Some(why) => {
5396                // Not settled until the restore is confirmed: the record
5397                // stays `Running`, so a resume retries it.
5398                crate::recovery::restore_repair(&wt, &pre)
5399                    .await
5400                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5401                self.state.event(
5402                    "graft",
5403                    format!("rolled back: {why}; the winner is untouched"),
5404                );
5405                GraftOutcome::RolledBack(why)
5406            }
5407        };
5408        self.state.graft = Some(GraftRecord {
5409            pre,
5410            post,
5411            lines,
5412            limit: None,
5413            agent: Some(agent_id),
5414            outcome,
5415            requested,
5416            adoption,
5417            adoption_error,
5418        });
5419        self.state.save()?;
5420        Ok(())
5421    }
5422
5423    // ----------------------------------------------------------------- fold
5424
5425    async fn fold_losers(&mut self) -> Result<()> {
5426        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5427            return Ok(());
5428        };
5429        if !self.state.candidate_preservation.is_empty() {
5430            bail!("candidate preservation incomplete; refusing cleanup");
5431        }
5432        let repo = self.state.repo.clone();
5433        let _coordination = self.coordinate(&repo).await?;
5434        let home = crate::run::home();
5435        let root = self.state.worktree_root();
5436        let isolated = crate::build_target::isolated(&self.state.config);
5437        let mut folded = Vec::new();
5438        for i in 0..self.state.candidates.len() {
5439            let c = &self.state.candidates[i];
5440            if c.label == winner || c.folded {
5441                continue;
5442            }
5443            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5444            let target = fold_target(&home, &root, &wt, isolated);
5445            remove_preserved_worktree(&repo, &wt).await?;
5446            reclaim_fold_target(&home, target);
5447            if git::branch_exists(&repo, &branch).await?
5448                && !git::branch_delete(&repo, &branch).await?
5449            {
5450                bail!("candidate branch removal refused");
5451            }
5452            self.state.candidates[i].folded = true;
5453            self.state.save()?;
5454            folded.push(label.to_string());
5455        }
5456        // The judges are finished; their checkouts are pure cost from here.
5457        for j in 1..=self.roles.judges.len() {
5458            let wt = root.join(format!("judge-{j}"));
5459            if wt.exists() {
5460                let target = fold_target(&home, &root, &wt, isolated);
5461                remove_read_seat_worktree(&mut self.state, &wt).await?;
5462                reclaim_fold_target(&home, target);
5463                self.state.save()?;
5464            }
5465        }
5466        // The design-deliberation stage is finished by the time a tally
5467        // exists — same reasoning as the judges above.
5468        if self.state.config.graph.advise {
5469            for k in 1..=self.state.config.graph.advisors {
5470                let wt = root.join(format!("advisor-{k}"));
5471                if wt.exists() {
5472                    let target = fold_target(&home, &root, &wt, isolated);
5473                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5474                    reclaim_fold_target(&home, target);
5475                    self.state.save()?;
5476                }
5477            }
5478        }
5479        if !folded.is_empty() {
5480            self.state
5481                .event("fold", format!("folded candidates {}", folded.join(", ")));
5482            self.state.save()?;
5483        }
5484        Ok(())
5485    }
5486
5487    // ------------------------------------------------------------ base sync
5488
5489    async fn hold_base_sync(&mut self) -> Result<bool> {
5490        self.hold_base_sync_as(None).await
5491    }
5492
5493    async fn hold_base_sync_kind(
5494        &mut self,
5495        kind: crate::base_sync_recovery::StopKind,
5496    ) -> Result<()> {
5497        self.hold_base_sync_as(Some(kind)).await?;
5498        Ok(())
5499    }
5500
5501    async fn hold_base_sync_as(
5502        &mut self,
5503        kind: Option<crate::base_sync_recovery::StopKind>,
5504    ) -> Result<bool> {
5505        if !self.state.base_sync_blocked() {
5506            self.state.base_sync_recovery.stop = None;
5507            return Ok(false);
5508        }
5509        let head = match self.state.winner() {
5510            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5511                .await
5512                .unwrap_or_default(),
5513            None => String::new(),
5514        };
5515        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5516            && !authorization.consumed
5517            && authorization.stop.head != head
5518        {
5519            authorization.refuse(format!(
5520                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5521                authorization.stop.head
5522            ));
5523        }
5524        self.state.record_base_sync_stop(&head);
5525        if let Some(kind) = kind {
5526            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5527            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5528                stop.kind = kind;
5529            }
5530        }
5531        self.state.save()?;
5532        Ok(true)
5533    }
5534
5535    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5536    /// anything verifies it.
5537    ///
5538    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5539    /// read whatever is checked out in the winner's worktree. Left alone that
5540    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5541    /// it when the run *branched* - and a run takes long enough that the base
5542    /// has usually moved by the time it gets here. A gate that ran there
5543    /// answers "green on the commit this run started from", not "green on
5544    /// what is about to land", and the difference showed up three times in
5545    /// one day as a green run whose merge would have reverted a file another
5546    /// pull request had already landed.
5547    ///
5548    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5549    /// `land::Step::Rebase` calls, rather than a second implementation of the
5550    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5551    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5552    /// doc warns about ("two answers to a question nobody notices until a
5553    /// diff is wrong").
5554    ///
5555    /// Foreign-checkout reviews instead merge the base into the owned shadow
5556    /// worktree, preserving the ancestry required for fast-forward delivery.
5557    /// A conflicting merge is aborted and held for operator resolution.
5558    ///
5559    /// A conflict is not the end of the road: the standing rebase is handed
5560    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5561    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5562    /// land). Once it finishes, review and the gate run as usual on the
5563    /// rebased tree, which is where a breakage the new base caused is caught
5564    /// by the ordinary gate-fix round. magi resolves nothing itself.
5565    ///
5566    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5567    /// the current durable recovery interval, bounds how often the base is
5568    /// synchronized during active recovery (lifetime attempts remain evidence).
5569    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5570    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5571    /// what was tried (rounds spent, paths still conflicted) and the branch
5572    /// and worktree stay exactly as they were - untouched, for a person to
5573    /// look at - which is also what makes re-entering this function
5574    /// afterwards a no-op instead of a second attempt at the same wall. A
5575    /// push failure ends the same way.
5576    async fn sync_to_base(&mut self) -> Result<()> {
5577        if self.state.status == RunStatus::AlreadyInBase {
5578            return Ok(());
5579        }
5580        self.hold_base_sync().await?;
5581        let conflicted = self
5582            .state
5583            .base_sync
5584            .as_ref()
5585            .is_some_and(|s| s.conflict.is_some());
5586        let Some(winner) = self.state.winner().cloned() else {
5587            return Ok(());
5588        };
5589
5590        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5591
5592        let repo = self.state.repo.clone();
5593        let remote = self.state.config.merge.remote.clone();
5594        let base_branch = self.state.base_branch.clone();
5595        let tracking = format!("{remote}/{base_branch}");
5596
5597        let fetched_base =
5598            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5599        // No network, or the remote never had this branch: the run already
5600        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5601        // otherwise), and one that got this far is not blocked by a fetch
5602        // that fails now. It just has no newer tip to compare against.
5603        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5604            return Ok(());
5605        };
5606
5607        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5608        self.state.ensure_base_episode();
5609        let mut pending = self
5610            .state
5611            .base_sync_recovery
5612            .operations
5613            .last()
5614            .filter(|o| !o.finished)
5615            .cloned();
5616        let scratch = self.state.dir().join("base-sync");
5617        if git::rebase_in_progress(&scratch).await {
5618            // Older resource stops predate operation reservations. Import the
5619            // standing Git operation, never retarget it to today's main.
5620            if pending.is_none()
5621                && self.state.base_sync_recovery.operations.is_empty()
5622                && !conflicted
5623                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5624                    .await
5625                    .ok()
5626                    .as_deref()
5627                    == Some(head.as_str())
5628                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5629                && git::is_clean(&winner.worktree).await?
5630            {
5631                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5632                if self.state.base_sync.is_none() {
5633                    self.state.base_sync = Some(BaseSync {
5634                        tip: saved_tip.clone(),
5635                        behind: 0,
5636                        attempts: 0,
5637                        conflict: None,
5638                        already_in: None,
5639                    });
5640                }
5641                self.state.reserve_base_operation(&head, &saved_tip);
5642                self.state.event(
5643                    "base-recovery",
5644                    "imported standing legacy rebase as a spent synchronization reservation",
5645                );
5646                self.state.save()?;
5647                pending = self.state.base_sync_recovery.operations.last().cloned();
5648            }
5649            let expected = pending.as_ref().map(|op| op.tip.as_str());
5650            if expected.is_none()
5651                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5652            {
5653                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5654                if self.state.base_sync.is_none() {
5655                    self.state.base_sync = Some(BaseSync {
5656                        tip: tip.clone(),
5657                        behind: 0,
5658                        attempts: 0,
5659                        conflict: None,
5660                        already_in: None,
5661                    });
5662                }
5663                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5664                self.state.event("land", why);
5665                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5666                    .await?;
5667                return Ok(());
5668            }
5669        }
5670        if let Some(op) = &pending {
5671            // A replay may add the pinned base's commits, never foreign work.
5672            let mut replay_proven =
5673                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5674            if !replay_proven && scratch.exists() && !git::rebase_in_progress(&scratch).await {
5675                let wait = repository_wait(&self.state, None);
5676                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5677                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5678                    Ok(true) => {
5679                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5680                        self.state.save()?;
5681                        git::worktree_remove(&repo, &scratch).await.ok();
5682                        replay_proven = true;
5683                    }
5684                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5685                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5686                }
5687            }
5688            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5689                if self.state.foreign_checkout.is_some() {
5690                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5691                        .await
5692                        .ok()
5693                        .as_deref()
5694                        == Some(op.head.as_str())
5695                        && git::rev_parse(&repo, &format!("{head}^2"))
5696                            .await
5697                            .ok()
5698                            .as_deref()
5699                            == Some(op.tip.as_str());
5700                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5701                    .await
5702                    .is_ok_and(|m| m.is_empty())
5703                    && let Ok(added) =
5704                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5705                {
5706                    replay_proven = true;
5707                    for commit in added {
5708                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5709                            replay_proven = false;
5710                            break;
5711                        }
5712                    }
5713                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5714                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5715                }
5716            }
5717            // Never retarget an operation across a crash, even if main moved.
5718            // sync_to_head resets and cleans with -x, so even ignored untracked
5719            // files must stop recovery independently of the old tracked tree.
5720            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5721                || (head != op.head
5722                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5723                        .await?
5724                        .is_empty())
5725                || (!git::is_clean(&winner.worktree).await?
5726                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5727                        .await
5728                        .is_ok_and(|o| o.ok()))
5729                || !replay_proven
5730            {
5731                let why = format!(
5732                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5733                    op.id
5734                );
5735                let sync = self
5736                    .state
5737                    .base_sync
5738                    .as_mut()
5739                    .context("reserved synchronization has no lifetime accounting")?;
5740                sync.conflict = Some(why.clone());
5741                self.state.event("land", why);
5742                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5743                    .await?;
5744                return Ok(());
5745            }
5746            if head != op.head {
5747                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5748            }
5749            tip = op.tip.clone();
5750        }
5751        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5752        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5753        if pending.is_none()
5754            && !conflicted
5755            && fetched_base
5756            && self
5757                .state
5758                .base_sync_recovery
5759                .episodes
5760                .last()
5761                .is_some_and(|e| e.boundary.is_some())
5762            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5763            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5764            && owner.execution_runs().last() == Some(&self.state.id)
5765            && owner.status != crate::queue::TaskStatus::Done
5766            && !owner.fresh_start
5767            && owner.review_branch.is_none()
5768            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5769            && let Some(approval) = owner.resumption.as_ref()
5770            && approval.instruction == owner.instruction
5771            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5772            && git::is_clean(&winner.worktree).await?
5773            && self.state.renew_base_episode(&task, approval, &head, &tip)
5774        {
5775            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5776            self.state.save()?;
5777        }
5778
5779        // Before any rebase, and before a recorded conflict is honoured: a
5780        // branch whose change reached the base under other commit ids has
5781        // nothing to rebase and nothing to conflict with, and a run that
5782        // already stopped on that phantom conflict recovers here on resume.
5783        // `behind == 0` with head == tip is a branch the base has since taken
5784        // in whole, whether or not a conflict was ever recorded: the ancestry
5785        // proof must still run (`classify` ignores a head still on the start
5786        // commit).
5787        if (behind > 0 || conflicted || head == tip)
5788            && self
5789                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5790                .await?
5791        {
5792            return Ok(());
5793        }
5794        if conflicted && self.state.base_recovery_pending() {
5795            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5796            let owner =
5797                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5798            let owner_valid = owner.as_ref().is_ok_and(|t| {
5799                t.execution_runs().last() == Some(&self.state.id)
5800                    && t.status != crate::queue::TaskStatus::Done
5801                    && !t.fresh_start
5802                    && t.review_branch.is_none()
5803            });
5804            let invalidation = if !owner_valid {
5805                Some("latest task ownership changed")
5806            } else if !owner.as_ref().is_ok_and(|t| {
5807                authorization
5808                    .generation
5809                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5810            }) {
5811                Some("owner approval generation changed")
5812            } else if authorization.question.as_ref().is_some_and(|question| {
5813                !crate::base_recovery_control::decision_current(
5814                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5815                    &self.state,
5816                    &authorization.task,
5817                    question,
5818                )
5819            }) {
5820                Some("recovery decision ownership, routing or stop evidence changed")
5821            } else if authorization.request.is_some()
5822                && !owner
5823                    .as_ref()
5824                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5825            {
5826                Some("owner decision changed")
5827            } else if let Some(scope) = &authorization.scope {
5828                if scope.tip != tip {
5829                    Some("fetched base changed")
5830                } else if !self
5831                    .state
5832                    .base_sync_recovery
5833                    .episodes
5834                    .last()
5835                    .is_some_and(|e| e.id == scope.episode)
5836                {
5837                    Some("active synchronization interval changed")
5838                } else if !owner
5839                    .as_ref()
5840                    .is_ok_and(|t| t.instruction == scope.instruction)
5841                {
5842                    Some("task instruction changed")
5843                } else {
5844                    None
5845                }
5846            } else {
5847                None
5848            };
5849            if let Some(reason) = invalidation {
5850                let authorization = self
5851                    .state
5852                    .base_sync_recovery
5853                    .authorizations
5854                    .last_mut()
5855                    .unwrap();
5856                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5857                self.state.save()?;
5858                return Ok(());
5859            }
5860            if !fetched_base
5861                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5862                || !git::is_clean(&winner.worktree).await?
5863                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5864            {
5865                return Ok(());
5866            }
5867        }
5868        let recovery = conflicted && self.state.consume_base_recovery(&head);
5869        if conflicted {
5870            // Consumption (including a refused changed HEAD) is durable before Git.
5871            self.state.save()?;
5872            if !recovery {
5873                return Ok(());
5874            }
5875        }
5876
5877        if behind == 0 {
5878            // A fixer-finished rebase moves the branch ref before the
5879            // winner's worktree is told (`sync_to_head` below). A run that
5880            // died in between resumes here with `behind == 0` and a tree still
5881            // holding the pre-rebase files, which review and the gate would
5882            // then read. That state is exactly: HEAD moved off the tip the
5883            // rebase started from, yet the tree is still identical to that
5884            // tip. A tree with edits of its own differs from it, so nothing
5885            // is thrown away.
5886            if let Some(from) = self
5887                .state
5888                .rebase_fixes
5889                .iter()
5890                .rev()
5891                .find_map(|r| r.from.clone())
5892                && from != head
5893                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
5894                    .await
5895                    .is_ok_and(|o| o.ok())
5896            {
5897                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5898            }
5899            // An earlier attempt may have rebased the branch locally and died
5900            // before pushing it (only the fresh-rebase arm below pushes).
5901            // Publish it now, so the plain push at PR time is not refused as
5902            // a non-fast-forward. A run already holding a recorded conflict
5903            // never reaches here; that case is out of scope.
5904            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
5905            if let Some(why) = &conflict {
5906                self.state.status = RunStatus::Blocked;
5907                self.state.event("land", why.clone());
5908            }
5909            self.state.base_sync = Some(BaseSync {
5910                tip,
5911                behind: 0,
5912                attempts,
5913                conflict,
5914                already_in: None,
5915            });
5916            if pending.is_some() {
5917                self.state.finish_base_operation(Some(&head));
5918            }
5919            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
5920                .await?;
5921            self.state.save()?;
5922            return Ok(());
5923        }
5924
5925        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
5926            let why = format!(
5927                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
5928                 synchronization(s); synchronizing again would only race it",
5929                winner.branch
5930            );
5931            self.state.status = RunStatus::Blocked;
5932            self.state.base_sync = Some(BaseSync {
5933                tip,
5934                behind,
5935                attempts,
5936                conflict: Some(why.clone()),
5937                already_in: None,
5938            });
5939            self.state.event("land", why);
5940            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
5941                .await?;
5942            self.state.save()?;
5943            return Ok(());
5944        }
5945
5946        if self.state.foreign_checkout.is_some() {
5947            // Delivery to the operator's checkout is fast-forward only. A
5948            // rebase here would discard its saved head from our ancestry.
5949            let wait = repository_wait(&self.state, None);
5950            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5951            if self.state.base_sync.is_none() {
5952                self.state.base_sync = Some(BaseSync {
5953                    tip: tip.clone(),
5954                    behind,
5955                    attempts: 0,
5956                    conflict: None,
5957                    already_in: None,
5958                });
5959            }
5960            self.state.reserve_base_operation(&head, &tip);
5961            self.state.save()?;
5962            let merged = git::git_raw(
5963                &winner.worktree,
5964                &[
5965                    "-c",
5966                    "core.hooksPath=/dev/null",
5967                    "merge",
5968                    "--no-ff",
5969                    "--no-autostash",
5970                    "--no-edit",
5971                    "-m",
5972                    &format!("Merge {tracking} before verifying"),
5973                    &tip,
5974                ],
5975            )
5976            .await?;
5977            let conflict = if merged.ok() {
5978                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5979                self.state.event(
5980                    "land",
5981                    format!("merged {tracking} into {} before verifying", winner.branch),
5982                );
5983                None
5984            } else {
5985                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
5986                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
5987                }
5988                let why = format!(
5989                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
5990                    winner.branch,
5991                    merged.stderr.chars().take(600).collect::<String>()
5992                );
5993                self.state.status = RunStatus::Blocked;
5994                self.state.event("land", &why);
5995                Some(why)
5996            };
5997            let synced = conflict.is_none();
5998            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
5999            self.state
6000                .finish_base_operation(synced.then_some(fresh.as_str()));
6001            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6002            self.state.base_sync = Some(BaseSync {
6003                tip,
6004                behind: if synced { 0 } else { behind },
6005                attempts,
6006                conflict,
6007                already_in: None,
6008            });
6009            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6010                .await?;
6011            self.state.save()?;
6012            return Ok(());
6013        }
6014
6015        self.state.event(
6016            "land",
6017            format!(
6018                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6019                winner.branch
6020            ),
6021        );
6022        self.state.save()?;
6023
6024        // The remote's copy of the branch, read now and only if the fetch
6025        // really succeeded (a stale tracking ref must never pin a lease). It is
6026        // pushed over after a rebase only when it is a commit this branch
6027        // already contains, by ancestry or by patch (an earlier rebase of ours
6028        // that never reached the remote): anything else is somebody else's work.
6029        let branch_tracking = format!("{remote}/{}", winner.branch);
6030        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6031        let remote_tip = if self.state.task_pr_branch().is_none()
6032            && matches!(&fetched_branch, Ok(o) if o.ok())
6033        {
6034            git::rev_parse(&repo, &branch_tracking).await.ok()
6035        } else {
6036            None
6037        };
6038        // A remote tip this branch does not contain is somebody else's work:
6039        // rebasing would leave a local tip that can never be pushed. Stop
6040        // before touching anything and say so.
6041        if let Some(theirs) = &remote_tip
6042            && !git::is_ancestor(&repo, theirs, &head).await
6043            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6044                .await
6045                .is_ok_and(|missing| missing.is_empty())
6046        {
6047            let why = format!(
6048                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6049                 them",
6050                short(theirs),
6051                winner.branch
6052            );
6053            self.state.status = RunStatus::Blocked;
6054            self.state.base_sync = Some(BaseSync {
6055                tip,
6056                behind,
6057                attempts,
6058                conflict: Some(why.clone()),
6059                already_in: None,
6060            });
6061            self.state.event("land", why);
6062            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6063                .await?;
6064            self.state.save()?;
6065            return Ok(());
6066        }
6067
6068        if self.state.base_sync.is_none() {
6069            self.state.base_sync = Some(BaseSync {
6070                tip: tip.clone(),
6071                behind,
6072                attempts: 0,
6073                conflict: None,
6074                already_in: None,
6075            });
6076        }
6077        let scratch = self.state.dir().join("base-sync");
6078        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6079        {
6080            if error.is::<crate::repo_lock::ResourceBlocked>() {
6081                return Ok(());
6082            }
6083            return Err(error);
6084        }
6085        self.state.reserve_base_operation(&head, &tip);
6086        self.state.save()?;
6087        let rebased =
6088            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6089                .await
6090            {
6091                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6092                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6093                Err(e) => Err(e),
6094            };
6095        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6096        let stop_kind = match &rebased {
6097            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6098            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6099            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6100        };
6101        match rebased {
6102            Ok(None) => {
6103                // The branch ref moved, but a worktree that already had it
6104                // checked out (the winner's) was not told; sync its index and
6105                // files before anything reads them.
6106                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6107                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6108                self.state.finish_base_operation(Some(&fresh));
6109                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6110                let mut conflict = None;
6111                if let Some(pinned) = &remote_tip {
6112                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6113                    match pushed {
6114                        Ok(o) if o.ok() => self.state.event(
6115                            "land",
6116                            format!("pushed rebased {} to {remote}", winner.branch),
6117                        ),
6118                        Ok(o) => {
6119                            conflict = Some(format!(
6120                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6121                                winner.branch,
6122                                short(pinned),
6123                                o.stderr.chars().take(600).collect::<String>()
6124                            ));
6125                        }
6126                        Err(e) => {
6127                            conflict = Some(format!(
6128                                "rebased {} locally but could not push it: {e:#}",
6129                                winner.branch
6130                            ));
6131                        }
6132                    }
6133                }
6134                if let Some(why) = &conflict {
6135                    self.state.status = RunStatus::Blocked;
6136                    self.state.event("land", why.clone());
6137                }
6138                self.state.base_sync = Some(BaseSync {
6139                    tip: tip.clone(),
6140                    behind: 0,
6141                    attempts,
6142                    conflict,
6143                    already_in: None,
6144                });
6145                self.state
6146                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6147            }
6148            Ok(Some(conflict)) => {
6149                self.state.finish_base_operation(None);
6150                let why = format!(
6151                    "{} conflicts with {tracking} and did not rebase: {}",
6152                    winner.branch,
6153                    conflict.chars().take(600).collect::<String>()
6154                );
6155                self.state.status = RunStatus::Blocked;
6156                self.state.base_sync = Some(BaseSync {
6157                    tip,
6158                    behind,
6159                    attempts,
6160                    conflict: Some(why.clone()),
6161                    already_in: None,
6162                });
6163                self.state.event("land", why);
6164            }
6165            // A refused Git write or a busy repository: nothing is wrong with
6166            // the branch. The scratch rebase stays standing and the run
6167            // resumes into it (`base_sync` must not claim a conflict).
6168            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6169                self.state.save()?;
6170                return Ok(());
6171            }
6172            Err(e) => {
6173                self.state.finish_base_operation(None);
6174                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6175                self.state.status = RunStatus::Blocked;
6176                self.state.base_sync = Some(BaseSync {
6177                    tip,
6178                    behind,
6179                    attempts,
6180                    conflict: Some(why.clone()),
6181                    already_in: None,
6182                });
6183                self.state.event("land", why);
6184            }
6185        }
6186        if !self.state.base_sync_blocked() {
6187            self.state.base_sync_recovery.stop = None;
6188        }
6189        self.hold_base_sync_kind(stop_kind).await?;
6190        self.state.save()?;
6191        Ok(())
6192    }
6193
6194    /// Push a branch an earlier attempt rebased locally but never published,
6195    /// pinned to the remote tip read right after a successful fetch. Returns
6196    /// the reason when the run must stop; `None` when there was nothing to do
6197    /// (no remote copy, the same tip, or a remote copy this branch already
6198    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6199    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6200        // Task competitions publish only after the PR text gate, to their
6201        // public head; never resurrect a candidate branch on the remote.
6202        if self.state.task_pr_branch().is_some() {
6203            return None;
6204        }
6205        let repo = self.state.repo.clone();
6206        let remote = self.state.config.merge.remote.clone();
6207        let fetched = git::fetch(&repo, &remote, branch).await;
6208        if !matches!(&fetched, Ok(o) if o.ok()) {
6209            return None;
6210        }
6211        let branch_tracking = format!("{remote}/{branch}");
6212        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6213        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6214            return None;
6215        }
6216        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6217            .await
6218            .is_ok_and(|missing| missing.is_empty())
6219        {
6220            return Some(format!(
6221                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6222                 them",
6223                short(&theirs)
6224            ));
6225        }
6226        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6227            Ok(o) if o.ok() => {
6228                self.state
6229                    .event("land", format!("pushed rebased {branch} to {remote}"));
6230                None
6231            }
6232            Ok(o) => Some(format!(
6233                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6234                 someone may have pushed): {}",
6235                short(&theirs),
6236                o.stderr.chars().take(600).collect::<String>()
6237            )),
6238            Err(e) => Some(format!(
6239                "{branch} is rebased locally but could not be pushed: {e:#}"
6240            )),
6241        }
6242    }
6243
6244    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6245    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6246    /// whether it did.
6247    ///
6248    /// Checked only when the base is ahead of the branch. A failing check is
6249    /// "not proven" - the ordinary rebase path then decides - never a reason to
6250    /// stop the run.
6251    ///
6252    /// The remote copy of the branch is held to the same standard as the local
6253    /// one: if it carries a tip this worktree does not, that tip must itself be
6254    /// proven in the base, or nothing is settled (a pull request would
6255    /// otherwise be closed over commits nobody checked). The pull request is
6256    /// closed *before* the terminal status is saved; if that fails for a
6257    /// reason other than a refusal (no network, a `gh` error) the run is left
6258    /// `Blocked` with the reason as its conflict, which a resume retries -
6259    /// the same recovery a phantom conflict gets.
6260    async fn settle_already_in(
6261        &mut self,
6262        branch: &str,
6263        tip: &str,
6264        head: &str,
6265        attempts: usize,
6266        behind: usize,
6267    ) -> Result<bool> {
6268        let repo = self.state.repo.clone();
6269        let remote = self.state.config.merge.remote.clone();
6270        let start = self.state.base_commit.clone();
6271        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6272            Ok(Some(e)) => e,
6273            Ok(None) => return Ok(false),
6274            Err(e) => {
6275                tracing::warn!("already-in-base check for {branch}: {e:#}");
6276                return Ok(false);
6277            }
6278        };
6279        let mut verified = vec![head.to_owned()];
6280        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6281        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6282        if matches!(&fetched, Ok(o) if o.ok())
6283            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await
6284            && theirs != head
6285        {
6286            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6287                Ok(Some(_)) => verified.push(theirs),
6288                _ => return Ok(false),
6289            }
6290        }
6291        let base_branch = self.state.base_branch.clone();
6292        let message = format!(
6293            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6294             land",
6295            evidence.names(),
6296            evidence.proof.as_str()
6297        );
6298        let closed =
6299            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6300                .await;
6301        match closed {
6302            Ok(Ok(url)) => self
6303                .state
6304                .event("land", format!("closed {url}: superseded on {base_branch}")),
6305            Ok(Err(why)) => self
6306                .state
6307                .event("land", format!("did not close a pull request: {why}")),
6308            Err(e) => {
6309                let why = format!(
6310                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6311                     not be closed ({e:#}); resume to retry"
6312                );
6313                self.state.status = RunStatus::Blocked;
6314                self.state.base_sync = Some(BaseSync {
6315                    tip: tip.to_owned(),
6316                    behind,
6317                    attempts,
6318                    conflict: Some(why.clone()),
6319                    already_in: None,
6320                });
6321                self.state.event("land", why);
6322                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6323                    .await?;
6324                self.state.save()?;
6325                return Ok(true);
6326            }
6327        }
6328        self.state.status = RunStatus::AlreadyInBase;
6329        self.state.base_sync_recovery.stop = None;
6330        self.state.base_sync = Some(BaseSync {
6331            tip: tip.to_owned(),
6332            behind,
6333            attempts,
6334            conflict: None,
6335            already_in: Some(evidence),
6336        });
6337        self.state.event("land", message);
6338        self.state.save()?;
6339        self.settle_questions();
6340        Ok(true)
6341    }
6342
6343    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6344    /// last landed the winner on, once it has run, else the commit the run
6345    /// branched from.
6346    ///
6347    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6348    /// and `vote` all happen before there is a winner to rebase, so they
6349    /// compare every candidate against the branch point on purpose, and a
6350    /// base that moves after they are already done cannot change an answer
6351    /// they already gave.
6352    fn landing_base(&self) -> String {
6353        self.state
6354            .base_sync
6355            .as_ref()
6356            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6357    }
6358
6359    // ------------------------------------------------------- operator fix
6360
6361    /// Route specific, already-recorded review findings to a fixer for a
6362    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6363    /// entry point.
6364    ///
6365    /// Distinct from `review_loop`'s own fix step in three ways: it never
6366    /// runs a reviewer wave, it never spends review-round budget, and what
6367    /// happened is recorded as an [`OperatorFixRequest`] appended to
6368    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6369    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6370    /// and vote must never be rewritten to look like a manufactured blocking
6371    /// verdict.
6372    ///
6373    /// Only meaningful once review has actually concluded: `Ready` (handed
6374    /// off with findings still open, or simply concluded clean while minor
6375    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6376    /// gate failed). Everything else is refused: a run still in progress
6377    /// should simply be resumed, and a `Merged` run's branch has already
6378    /// landed — reopening *this* run's own record cannot change that, so the
6379    /// answer there is a fresh `magi review <branch>`.
6380    ///
6381    /// A real commit here re-verifies through a fresh, ordinary review-only
6382    /// run on the same branch ([`Self::review`]) rather than reopening this
6383    /// run's own `review_loop`: once any round in this run's history went
6384    /// clean, `review_conclusion` treats that as permanent by design (the
6385    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6386    /// way to force one more genuine reviewer wave out of *this* run without
6387    /// either rewriting history or weakening that guarantee for every other
6388    /// caller. A review-only run costs nothing extra — no implementation, no
6389    /// judging, no vote — and exercises the exact same review → verify →
6390    /// gate → (human) merge path, unmodified.
6391    pub async fn fix_selected(
6392        &mut self,
6393        ids: &[String],
6394        reason: &str,
6395        allow_stale: bool,
6396    ) -> Result<()> {
6397        let reason = reason.trim();
6398        if reason.is_empty() {
6399            bail!("a fix request needs a reason — that is the operator's own record of why");
6400        }
6401        if ids.is_empty() {
6402            bail!("no finding id given");
6403        }
6404        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6405            bail!(
6406                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6407                 has already concluded — can be given a targeted fix. A run still \
6408                 in progress should simply be resumed; a `merged` run's branch has \
6409                 already landed, so its answer is a fresh `magi review <branch>`, \
6410                 not reopening this run's own record",
6411                self.state.id,
6412                self.state.status.as_str()
6413            );
6414        }
6415        // Reassignment shares this claim through its atomic task save. Check
6416        // the canonical run identity inside it, before preflight or any await.
6417        let _claim = FixClaim::acquire(&self.state.dir())?;
6418        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6419        let home = crate::run::home();
6420        // The ordinary driver takes these same locks at admission. Keep the
6421        // execution lease through the fix, but never the owner lock across Git
6422        // or agent awaits.
6423        let execution = {
6424            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6425            let disk = RunState::load(&self.state.id)?;
6426            crate::pr_head::ensure_owner(&disk)?;
6427            anyhow::ensure!(
6428                disk.status == self.state.status && disk.released_to.is_none(),
6429                "run changed since it was loaded; reload before fixing"
6430            );
6431            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6432            anyhow::ensure!(
6433                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6434                "run {} is currently being worked on or its ownership is unknown",
6435                disk.id
6436            );
6437            let lease = crate::driver::maintenance(&home, &disk.id).context(
6438                "run is currently being worked on or its execution lease is unavailable",
6439            )?;
6440            self.state = disk;
6441            lease
6442        };
6443        let Some(winner) = self.state.winner().cloned() else {
6444            bail!("run {} has no winning candidate to fix", self.state.id);
6445        };
6446        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6447            bail!(
6448                "branch `{}` no longer exists; this run cannot be extended",
6449                winner.branch
6450            );
6451        }
6452        // Resolve every id before spending anything — an unknown id refuses
6453        // the whole request rather than silently dropping it — and dedup
6454        // while keeping the operator's own order.
6455        let mut seen = BTreeSet::new();
6456        let mut findings = Vec::new();
6457        let mut missing = Vec::new();
6458        for id in ids {
6459            if !seen.insert(id.clone()) {
6460                continue;
6461            }
6462            match self.state.finding(id) {
6463                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6464                    id: f.id.clone(),
6465                    severity: f.severity,
6466                    reviewer_vote: rec.vote,
6467                    round: round.round,
6468                    round_head: round.head.clone(),
6469                    reviewer: rec.reviewer,
6470                    agent: rec.agent.clone(),
6471                    file: f.file.clone(),
6472                    line: f.line,
6473                    title: f.title.clone(),
6474                    detail: f.detail.clone(),
6475                    outcome: OperatorFixOutcome::Pending,
6476                }),
6477                None => missing.push(id.clone()),
6478            }
6479        }
6480        if !missing.is_empty() {
6481            bail!(
6482                "unknown finding id(s): {}; nothing was changed",
6483                missing.join(", ")
6484            );
6485        }
6486
6487        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6488        let stale_details: Vec<(String, String)> = findings
6489            .iter()
6490            .filter(|f| f.round_head != head_at_request)
6491            .map(|f| (f.id.clone(), f.round_head.clone()))
6492            .collect();
6493        let stale = !stale_details.is_empty();
6494        if stale && !allow_stale {
6495            bail!(
6496                "the branch has moved since some finding(s) were raised — {} — now \
6497                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6498                stale_details
6499                    .iter()
6500                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6501                    .collect::<Vec<_>>()
6502                    .join(", "),
6503                short(&head_at_request)
6504            );
6505        }
6506
6507        let request = OperatorFixRequest {
6508            requested_at: Timestamp::now(),
6509            reason: reason.to_owned(),
6510            findings,
6511            head_at_request: head_at_request.clone(),
6512            allow_stale,
6513            stale,
6514            fix: None,
6515            result_head: None,
6516            follow_up_review_run: None,
6517        };
6518        self.state.event(
6519            "fix",
6520            format!(
6521                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6522                request.findings.len(),
6523                request
6524                    .findings
6525                    .iter()
6526                    .map(|f| f.id.as_str())
6527                    .collect::<Vec<_>>()
6528                    .join(", "),
6529            ),
6530        );
6531        // Recorded now, before any worktree work or the fixer call itself —
6532        // and re-saved at each checkpoint below: a crash at any point after
6533        // this (mid fixer call, mid follow-up review) must not lose the fact
6534        // that this was requested, for which findings, and why. Everything
6535        // past this point reads and writes through `request_index` rather
6536        // than a local variable, since `request` itself is moved here.
6537        self.state.operator_fixes.push(request);
6538        self.state.save()?;
6539        let request_index = self.state.operator_fixes.len() - 1;
6540
6541        // A fresh, dedicated worktree for this one call, never the winner's
6542        // own worktree in place: that one may already be gone (folded away),
6543        // and reusing it in place would leave the branch checked out there
6544        // when the follow-up review below tries to check it out again. Freed
6545        // immediately after, either way — but only once confirmed clean:
6546        // `worktree_remove` is a `git worktree remove --force`, which would
6547        // otherwise discard uncommitted work left there by the operator or
6548        // another process before this had a chance to even look at it.
6549        let repo = self.state.repo.clone();
6550        let coordination = self.coordinate(&repo).await?;
6551        if winner.worktree.exists() {
6552            // Lockfiles a rescue commit withheld stay untracked on purpose and
6553            // are already recorded; they are not the operator's work to protect.
6554            let dirty = git::git(
6555                &winner.worktree,
6556                &["status", "--porcelain", "--untracked-files=all"],
6557            )
6558            .await?;
6559            let only_withheld = dirty.lines().all(|l| {
6560                l.strip_prefix("?? ")
6561                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6562            });
6563            if !only_withheld {
6564                bail!(
6565                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6566                     discard them first",
6567                    winner.worktree.display()
6568                );
6569            }
6570            git::worktree_remove(&self.state.repo, &winner.worktree)
6571                .await
6572                .ok();
6573        }
6574        let fix_worktree = self.state.worktree_root().join("operator-fix");
6575        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6576        git::git(
6577            &self.state.repo,
6578            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6579        )
6580        .await
6581        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6582        if !git::is_clean(&fix_worktree).await? {
6583            git::worktree_remove(&self.state.repo, &fix_worktree)
6584                .await
6585                .ok();
6586            bail!(
6587                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6588                winner.branch
6589            );
6590        }
6591        let repo_for_setup = self.state.repo.clone();
6592        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6593            Ok(()) => {
6594                worktree_setup::prepare_with(
6595                    &self.state.config,
6596                    &repo_for_setup,
6597                    &fix_worktree,
6598                    crate::build_target::Coordination::Held(coordination.as_ref()),
6599                )
6600                .await
6601            }
6602            Err(e) => Err(e),
6603        };
6604        if let Err(e) = setup {
6605            git::worktree_remove(&self.state.repo, &fix_worktree)
6606                .await
6607                .ok();
6608            return Err(e);
6609        }
6610
6611        // This explicit operator request retries availability independently
6612        // of execute(); the previous call has already saved and cleaned up.
6613        self.state.resource_block = None;
6614
6615        let run_id = self.state.id.clone();
6616        let prompts = self.state.config.prompts.clone();
6617        let language = self.state.config.graph.language.clone();
6618        let sessions = self.state.config.graph.sessions;
6619        let artifacts = agent::artifacts_dir(&self.state.dir());
6620        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6621            .findings
6622            .iter()
6623            .map(|f| Finding {
6624                id: f.id.clone(),
6625                severity: f.severity,
6626                file: f.file.clone(),
6627                line: f.line,
6628                title: f.title.clone(),
6629                detail: f.detail.clone(),
6630            })
6631            .collect();
6632        let fix_prompt = prompt::operator_fix_in(
6633            &self.state.instruction,
6634            &finding_list,
6635            reason,
6636            &stale_details,
6637            &head_at_request,
6638            &language,
6639            &self.state.config.graph.github_language,
6640        );
6641        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6642        drop(coordination);
6643        let (job, seat, out) = self
6644            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6645                prompt: fix_prompt.clone(),
6646                spec,
6647                seat,
6648                cwd: fix_worktree.clone(),
6649                timeout,
6650                allow_write: true,
6651                sessions,
6652                artifacts: artifacts.clone(),
6653                stem: "operator-fix".to_owned(),
6654                handover: None,
6655            })
6656            .await;
6657        let agent_id = seat.agent.clone();
6658
6659        let mut fix = FixRecord {
6660            agent: agent_id,
6661            addressed: Vec::new(),
6662            rejected: Vec::new(),
6663            notes: String::new(),
6664            committed: false,
6665            failed: None,
6666            duration_ms: 0,
6667            continuation: None,
6668        };
6669        let mut final_seat = seat.clone();
6670        match out {
6671            AgentOutcome::Ok(o) => {
6672                fix.duration_ms = o.duration_ms;
6673                let parsed = verdict::extract_json::<FixReport>(&o.text);
6674                let incomplete_reason = match &parsed {
6675                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6676                        "the reply parsed, but it reported a command whose own CLI \
6677                         never confirmed an exit status"
6678                            .to_owned(),
6679                    ),
6680                    Ok(_) => None,
6681                    Err(e) => Some(e.to_string()),
6682                };
6683                match incomplete_reason {
6684                    None => {
6685                        let report = parsed.expect("checked Ok above");
6686                        fix.addressed = report.addressed;
6687                        fix.rejected = report.rejected;
6688                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6689                    }
6690                    Some(reason) => {
6691                        let (resumed_seat, resolved, failure, cont) = self
6692                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6693                            .await;
6694                        fix.duration_ms += cont.cumulative_wait_ms;
6695                        fix.continuation = Some(cont);
6696                        final_seat = resumed_seat;
6697                        match resolved {
6698                            Some(report) => {
6699                                fix.addressed = report.addressed;
6700                                fix.rejected = report.rejected;
6701                                fix.notes =
6702                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6703                            }
6704                            None => fix.failed = failure,
6705                        }
6706                    }
6707                }
6708            }
6709            AgentOutcome::Dropped(o) => {
6710                fix.duration_ms = o.duration_ms;
6711                let why = o
6712                    .dropped
6713                    .as_ref()
6714                    .map(|d| d.why.as_str())
6715                    .unwrap_or("the CLI ended the stream without delivering its answer");
6716                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6717            }
6718            AgentOutcome::Quota(o) => {
6719                self.state.quota.push(QuotaLoss::from_report(
6720                    final_seat.key.clone(),
6721                    "fix",
6722                    o.quota.as_ref(),
6723                ));
6724                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6725            }
6726            AgentOutcome::Failed(e) => fix.failed = Some(e),
6727            AgentOutcome::ResourceBlocked(e) => {
6728                fix.failed = Some(format!("the fixer was not started: {e}"));
6729            }
6730        }
6731        // Even a deferred call must rescue edits, release the worktree and
6732        // finalize its record below so an explicit `magi fix` can retry.
6733        if fix.continuation.is_none() {
6734            fix.continuation = Some(ContinuationRecord::not_needed());
6735        }
6736        self.state.seats.insert(final_seat.key.clone(), final_seat);
6737
6738        let rescue_message = format!(
6739            "magi: operator-selected fix ({}) (uncommitted work)",
6740            self.state.operator_fixes[request_index]
6741                .findings
6742                .iter()
6743                .map(|f| f.id.as_str())
6744                .collect::<Vec<_>>()
6745                .join(", ")
6746        );
6747        let repo = self.state.repo.clone();
6748        let coordination = self.coordinate(&repo).await?;
6749        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6750            self.state.note_withheld("fix", &r.withheld);
6751        }
6752        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6753        fix.committed = after != head_at_request;
6754        git::worktree_remove(&self.state.repo, &fix_worktree)
6755            .await
6756            .ok();
6757        drop(coordination);
6758
6759        self.state.event(
6760            "fix",
6761            match &fix.failed {
6762                Some(reason) => format!(
6763                    "operator fix: adoption report was lost ({reason}); {}",
6764                    if fix.committed {
6765                        "committed"
6766                    } else {
6767                        "NO new commit"
6768                    }
6769                ),
6770                None => format!(
6771                    "operator fix: {} addressed, {} rejected, {}",
6772                    fix.addressed.len(),
6773                    fix.rejected.len(),
6774                    if fix.committed {
6775                        "committed"
6776                    } else {
6777                        "NO new commit"
6778                    }
6779                ),
6780            },
6781        );
6782
6783        // Every selected finding gets an outcome — never left `Pending` once
6784        // the fixer's own turn is over. A report that never came back at all
6785        // marks every one of them `Unreported`, not silently "not addressed":
6786        // quota, a dropped stream, or an exhausted continuation are gaps in
6787        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6788        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6789        for f in &mut self.state.operator_fixes[request_index].findings {
6790            f.outcome = if fix.failed.is_some() {
6791                OperatorFixOutcome::Unreported
6792            } else if fix.addressed.contains(&f.id) {
6793                OperatorFixOutcome::Addressed
6794            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6795                OperatorFixOutcome::Rejected { why: r.why.clone() }
6796            } else {
6797                OperatorFixOutcome::Unreported
6798            };
6799        }
6800
6801        let committed = fix.committed;
6802        if committed {
6803            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6804        }
6805        self.state.operator_fixes[request_index].fix = Some(fix);
6806        // Saved again now that the fixer's own outcome is final, on top of
6807        // the save right after the request was first pushed above.
6808        self.state.save()?;
6809        if self.state.resource_block.is_some() {
6810            return self.stop_for_resource();
6811        }
6812
6813        if committed {
6814            self.state.event(
6815                "fix",
6816                format!(
6817                    "operator fix committed {}; opening a follow-up review-only run",
6818                    short(&after)
6819                ),
6820            );
6821            self.state.save()?;
6822            drop(execution);
6823            // The new review owns its own execution. Update only its audit link
6824            // afterwards, since publication may have changed the old record.
6825            let event_count = self.state.events.len();
6826            let save_follow_up = |state: &mut RunState| -> Result<()> {
6827                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
6828                let _execution = crate::driver::maintenance(&home, &state.id)?;
6829                let mut disk = RunState::load(&state.id)?;
6830                disk.events.extend(state.events.drain(event_count..));
6831                let follow_up = state.operator_fixes[request_index]
6832                    .follow_up_review_run
6833                    .clone();
6834                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
6835                disk.save()?;
6836                *state = disk;
6837                Ok(())
6838            };
6839            // The operator asked for the fix, and the follow-up serves whatever
6840            // task the run it follows served.
6841            let origin =
6842                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6843            match Self::review(
6844                &self.state.repo,
6845                &winner.branch,
6846                self.state.config.clone(),
6847                origin,
6848            )
6849            .await
6850            {
6851                Ok(mut follow_up) => {
6852                    follow_up.state.event(
6853                        "start",
6854                        format!(
6855                            "requested by an operator fix on run {} for finding(s) {}",
6856                            self.state.id,
6857                            self.state.operator_fixes[request_index]
6858                                .findings
6859                                .iter()
6860                                .map(|f| f.id.as_str())
6861                                .collect::<Vec<_>>()
6862                                .join(", "),
6863                        ),
6864                    );
6865                    follow_up.state.save()?;
6866                    let follow_up_id = follow_up.state.id.clone();
6867                    // The follow-up is a run like any other: it belongs to the
6868                    // task of the run it follows, or to one filed for it.
6869                    let adopted = match crate::direct::adopt(
6870                        &follow_up.state,
6871                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
6872                    ) {
6873                        Ok(a) => a,
6874                        Err(e) => {
6875                            // An ownerless run must not spend agent calls; it
6876                            // stays saved, and `magi run --resume` adopts it.
6877                            self.state.event(
6878                                "fix",
6879                                format!(
6880                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
6881                                ),
6882                            );
6883                            save_follow_up(&mut self.state)?;
6884                            return Ok(());
6885                        }
6886                    };
6887                    let executed = follow_up.execute().await;
6888                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
6889                    if let Some(a) = adopted {
6890                        a.finish(&follow_up.state, executed);
6891                    }
6892                    if let Some(e) = failure {
6893                        self.state.event(
6894                            "fix",
6895                            format!(
6896                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
6897                            ),
6898                        );
6899                    }
6900                    self.state.operator_fixes[request_index].follow_up_review_run =
6901                        Some(follow_up_id);
6902                }
6903                Err(e) => {
6904                    self.state.event(
6905                        "fix",
6906                        format!("committed the fix but could not open a follow-up review: {e:#}"),
6907                    );
6908                }
6909            }
6910            save_follow_up(&mut self.state)?;
6911        }
6912
6913        Ok(())
6914    }
6915
6916    // --------------------------------------------------------------- review
6917
6918    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
6919    /// names, in order, each at most once, moving on only when the call
6920    /// advances (an error, a quota hit or nothing usable - the same decision
6921    /// point `agent::chain_advances` is for the other chained roles).
6922    ///
6923    /// Each agent gets its own seat from `Runner::seat`: the same agent
6924    /// continues its conversation (the winner's own implementer seat when it
6925    /// is the winner's author, now that the competition is over), another
6926    /// takes a fresh one so the full prompt is sent again. A handover is
6927    /// recorded under `node`, which is what makes the fallback stick for the
6928    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
6929    /// is returned, so an exhausted chain reads exactly like a single failed
6930    /// fixer: one quota loss, the same wording, the same refund. An earlier
6931    /// attempt's edits are left in the tree and judged, with the final
6932    /// attempt's, by what git says afterwards.
6933    ///
6934    /// Returns the job that produced the outcome, for `continue_fix_report`.
6935    async fn ask_fixer(
6936        &mut self,
6937        winner: &Candidate,
6938        node: &'static str,
6939        round: Option<usize>,
6940        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6941    ) -> (SeatJob, SeatState, AgentOutcome) {
6942        let attempts = fixer::attempts(&self.state, &self.roles, winner);
6943        self.ask_fixer_among(attempts, node, round, None, build)
6944            .await
6945    }
6946
6947    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
6948    /// worktree and a commit: before the next agent is asked after one that
6949    /// did not satisfy the call, the worktree is put back on that commit, so
6950    /// a failed agent's partial edits are not carried into the next one.
6951    async fn ask_fixer_among(
6952        &mut self,
6953        attempts: Vec<(AgentSpec, String)>,
6954        node: &'static str,
6955        round: Option<usize>,
6956        restore: Option<(&Path, &str)>,
6957        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6958    ) -> (SeatJob, SeatState, AgentOutcome) {
6959        let run_id = self.state.id.clone();
6960        let prompts = self.state.config.prompts.clone();
6961        let cache = self.state.config.cache_dir();
6962        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6963        let mut last = None;
6964        for (i, (spec, key)) in attempts.into_iter().enumerate() {
6965            let seat = self.seat(&key, &spec.id);
6966            let mut job = build(spec.clone(), seat);
6967            if i > 0 {
6968                job.stem = format!("{}-{}", job.stem, spec.id);
6969            }
6970            let ctx = WaveCtx {
6971                carry_seats: false,
6972                pauses: Some((&self.pause, &self.interrupt)),
6973                run: &run_id,
6974                node,
6975                prompts: &prompts,
6976                cache: cache.as_deref(),
6977                round,
6978            };
6979            let (seat, out) =
6980                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
6981            // A resource block never advances the chain: the chosen agent
6982            // was not asked, so it must be the one asked again on resume.
6983            let advances = match &out {
6984                AgentOutcome::Ok(o) => agent::output_advances(o),
6985                AgentOutcome::ResourceBlocked(_) => false,
6986                _ => true,
6987            };
6988            if let Some(next) = ids.get(i + 1)
6989                && advances
6990            {
6991                self.state.seats.insert(seat.key.clone(), seat.clone());
6992                let class =
6993                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
6994                let reason = match &out {
6995                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
6996                    other => fail_reason(other),
6997                };
6998                // A failed agent's edits must not reach the next one, and a
6999                // restore that did not work ends the chain: the call fails
7000                // and the caller's own (confirmed) restore decides.
7001                if let Some((wt, rev)) = restore
7002                    && let Err(e) = self.graft_restore(wt, rev).await
7003                {
7004                    let why =
7005                        format!("could not restore the worktree before the next fixer: {e:#}");
7006                    tracing::warn!("{why}");
7007                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7008                        AgentOutcome::ResourceBlocked(why)
7009                    } else {
7010                        AgentOutcome::Failed(why)
7011                    };
7012                    last = Some((job, seat, out));
7013                    break;
7014                }
7015                record_handover(
7016                    &mut self.state,
7017                    node,
7018                    &seat.key,
7019                    &spec.id,
7020                    next,
7021                    &class,
7022                    &reason,
7023                );
7024                continue;
7025            }
7026            last = Some((job, seat, out));
7027            break;
7028        }
7029        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7030        if let AgentOutcome::Quota(output) = &out
7031            && node != "graft"
7032        {
7033            // Graft is best effort: its caller records the loss and restores
7034            // the pre-graft tree, then proceeds to review and gate.
7035            // Every fallback was tried. Machine outages cannot be repaired by
7036            // spending a fix round; use each caller's resumable resource path.
7037            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7038            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7039            self.state.quota.push(loss);
7040            self.state.seats.insert(seat.key.clone(), seat.clone());
7041            self.state.status = RunStatus::Blocked;
7042            return (
7043                job,
7044                seat,
7045                AgentOutcome::ResourceBlocked(
7046                    "fixer unavailable; restore agent availability and resume".into(),
7047                ),
7048            );
7049        }
7050        (job, seat, out)
7051    }
7052
7053    /// The one repair a verification-only failure earns (see
7054    /// [`crate::recovery`]), before the first review round of a run that took
7055    /// a branch over.
7056    ///
7057    /// Saved as started *before* the fixer is called, so a resume never
7058    /// repairs twice; a start found on re-entry is rolled back to the commit
7059    /// it began from. A failed or unusable fixer leaves the tree as it was and
7060    /// the review goes on over it, so the first round's own verification
7061    /// reports the failure again. The failure is never carried into a round as
7062    /// a result: verification is re-run on whatever commit this leaves.
7063    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7064        use crate::recovery::{Mode, Repair};
7065        if !self.state.reviews.is_empty() {
7066            return Ok(());
7067        }
7068        let Some(mut rec) = self.state.recovery.clone() else {
7069            return Ok(());
7070        };
7071        if rec.mode != Mode::VerifyRepair {
7072            return Ok(());
7073        }
7074        let wt = winner.worktree.clone();
7075        let mut head = git::rev_parse(&wt, "HEAD").await?;
7076        match rec.repair.clone() {
7077            Repair::Done { .. } => return Ok(()),
7078            Repair::WaitingForRestore { before } => {
7079                self.graft_restore(&wt, &before).await?;
7080                head = before;
7081                rec.repair = Repair::NotStarted;
7082                self.state.recovery = Some(rec.clone());
7083                self.state.save()?;
7084            }
7085            Repair::Started { before } => {
7086                // Interrupted: the unfinished edits are not trusted.
7087                // An unconfirmed rollback blocks the run with `Started` kept,
7088                // so a resume retries it; the tree is never reviewed as is.
7089                if let Err(e) = self.graft_restore(&wt, &before).await {
7090                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7091                        return Err(e);
7092                    }
7093                    return self
7094                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7095                        .await;
7096                }
7097                rec.repair = Repair::Done {
7098                    before: before.clone(),
7099                    after: before,
7100                    committed: false,
7101                    failed: Some("interrupted; rolled back".to_owned()),
7102                };
7103                self.state
7104                    .event("recovery", "the repair was interrupted and rolled back");
7105                self.state.recovery = Some(rec);
7106                self.state.save()?;
7107                return Ok(());
7108            }
7109            Repair::NotStarted => {}
7110        }
7111        if crate::recovery::recheck(&mut rec, &head) {
7112            self.state.event("recovery", rec.summary());
7113            self.state.recovery = Some(rec);
7114            self.state.save()?;
7115            return Ok(());
7116        }
7117        rec.repair = Repair::Started {
7118            before: head.clone(),
7119        };
7120        self.state.recovery = Some(rec.clone());
7121        self.state.save()?;
7122
7123        let language = self.state.config.graph.language.clone();
7124        let sessions = self.state.config.graph.sessions;
7125        let artifacts = agent::artifacts_dir(&self.state.dir());
7126        let fix_prompt = prompt::recovery_fix(
7127            &self.state.instruction,
7128            &rec,
7129            self.state.config.graph.review_rounds,
7130            &language,
7131        );
7132        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7133        self.state.event(
7134            "recovery",
7135            format!(
7136                "repair: the fixer starts from the failed verification on {}",
7137                short(&head)
7138            ),
7139        );
7140        let (_job, seat, out) = self
7141            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7142                prompt: fix_prompt.clone(),
7143                spec,
7144                seat,
7145                cwd: wt.clone(),
7146                timeout,
7147                allow_write: true,
7148                sessions,
7149                artifacts: artifacts.clone(),
7150                stem: "fix-recovery".to_owned(),
7151                handover: None,
7152            })
7153            .await;
7154        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7155            rec.repair = Repair::WaitingForRestore { before: head };
7156            self.state.recovery = Some(rec);
7157            return self.stop_for_resource();
7158        }
7159        let failed = match &out {
7160            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7161            AgentOutcome::Quota(o) => {
7162                self.state.quota.push(QuotaLoss::from_report(
7163                    seat.key.clone(),
7164                    "fix",
7165                    o.quota.as_ref(),
7166                ));
7167                Some("rate limited (quota); the fixer could not run".to_owned())
7168            }
7169            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7170            AgentOutcome::Failed(e) => Some(e.clone()),
7171        };
7172        self.state.seats.insert(seat.key.clone(), seat);
7173        let coordination = self.coordinate(&wt).await?;
7174        let failed = match failed {
7175            // The agent's partial edits are not kept.
7176            Some(why) => {
7177                if let Err(e) = git::restore_to(&wt, &head).await {
7178                    return self
7179                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7180                        .await;
7181                }
7182                Some(why)
7183            }
7184            None => {
7185                if let Ok(r) = git::rescue_commit(
7186                    &wt,
7187                    "magi: recovery repair of the failed verification (uncommitted work)",
7188                )
7189                .await
7190                {
7191                    self.state.note_withheld("fix", &r.withheld);
7192                }
7193                None
7194            }
7195        };
7196        let after = git::rev_parse(&wt, "HEAD").await?;
7197        drop(coordination);
7198        self.state.event(
7199            "recovery",
7200            match &failed {
7201                Some(why) => format!("repair: nothing kept ({why})"),
7202                None if after != head => {
7203                    format!("repair: committed {}", short(&after))
7204                }
7205                None => "repair: the fixer made no commit".to_owned(),
7206            },
7207        );
7208        rec.repair = Repair::Done {
7209            before: head.clone(),
7210            committed: after != head,
7211            after,
7212            failed,
7213        };
7214        self.state.recovery = Some(rec);
7215        self.state.save()?;
7216        Ok(())
7217    }
7218
7219    /// A repair whose rollback could not be confirmed: the run is blocked and
7220    /// resumable, and the unconfirmed state is never reviewed.
7221    async fn stop_recovery(
7222        &mut self,
7223        mut rec: crate::recovery::RecoveryRecord,
7224        head: &str,
7225        why: String,
7226    ) -> Result<()> {
7227        // `Started` stays recorded: a resume retries the restore.
7228        rec.repair = crate::recovery::Repair::Started {
7229            before: head.to_owned(),
7230        };
7231        self.state.recovery = Some(rec);
7232        self.state
7233            .event("recovery", format!("repair could not be undone: {why}"));
7234        self.state.status = RunStatus::Blocked;
7235        self.state.save()?;
7236        bail!("recovery repair could not be rolled back: {why}")
7237    }
7238
7239    async fn review_loop(&mut self) -> Result<()> {
7240        if self.hold_base_sync().await? {
7241            return Ok(());
7242        }
7243        loop {
7244            if self
7245                .state
7246                .base_sync
7247                .as_ref()
7248                .is_some_and(|s| s.conflict.is_some())
7249            {
7250                return Ok(());
7251            }
7252            if self.catchup_repairable() {
7253                let record = self.state.reviews.last().expect("repairable round").clone();
7254                let winner = self
7255                    .state
7256                    .winner()
7257                    .cloned()
7258                    .context("catch-up repair has no winner")?;
7259                if !self.fix_review_round(&winner, record).await? {
7260                    return Ok(());
7261                }
7262            }
7263            self.review_loop_pass().await?;
7264            if !self.catchup_repairable() {
7265                return Ok(());
7266            }
7267        }
7268    }
7269
7270    /// Derive an owed catch-up repair from durable round evidence, including
7271    /// reentry after a crash before the fixer was dispatched.
7272    fn catchup_repairable(&self) -> bool {
7273        self.state.reviews.len() < self.state.config.graph.review_rounds
7274            && self.state.reviews.last().is_some_and(|r| {
7275                !r.clean
7276                    && r.blocking == 0
7277                    && r.fix.is_none()
7278                    && r.e2e_status() == E2eStatus::Failed
7279            })
7280    }
7281
7282    async fn review_loop_pass(&mut self) -> Result<()> {
7283        // A base that would not rebase is a person's decision, not a review
7284        // round: nothing here would change the answer, and reviewers and a
7285        // fixer would be spending real budget on a tree that cannot land
7286        // regardless of what they find.
7287        if self
7288            .state
7289            .base_sync
7290            .as_ref()
7291            .is_some_and(|s| s.conflict.is_some())
7292        {
7293            return Ok(());
7294        }
7295        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7296        // agent files with `magi task add` name the run that paid for it. The
7297        // prompt overlay is cloned alongside it because the waves borrow it
7298        // while `self` is mutably borrowed by the node's own bookkeeping.
7299        let run_id = self.state.id.clone();
7300        let prompts = self.state.config.prompts.clone();
7301        let Some(winner) = self.state.winner().cloned() else {
7302            return Ok(());
7303        };
7304        let granted_review = self
7305            .state
7306            .repair_grants
7307            .last()
7308            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7309            .cloned();
7310        let fresh_review = granted_review
7311            .as_ref()
7312            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7313        let max_rounds = granted_review
7314            .as_ref()
7315            .map_or(self.state.config.graph.review_rounds, |g| {
7316                g.review_start.saturating_add(1)
7317            });
7318        // A clean round, an exhausted round budget, or a stalled tree (see
7319        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7320        // they are recorded — recomputed here, not read off `status`, so a
7321        // reentry into a run that already stopped restates the identical
7322        // verdict instead of silently handing back whatever an earlier node
7323        // in this same walk clobbered `status` to (a solo-candidate
7324        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7325        // below runs an empty range once the budget is spent, and would
7326        // otherwise fall through without touching `status` at all.
7327        if let Some(status) =
7328            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7329        {
7330            // A reentry after a crash between the last round's save and
7331            // `stop_reviewing` reaches the hand-off here, not there.
7332            if status == RunStatus::Gating {
7333                self.record_contested_handoff();
7334            }
7335            self.state.status = status;
7336            self.state.save()?;
7337            return Ok(());
7338        }
7339        self.state.status = RunStatus::Reviewing;
7340        // A last recorded round whose own verification never resolved
7341        // (`ResourceBlocked` — the shared build cache, not the patch) is
7342        // never a concluded round, whatever the round budget says: starting
7343        // a fresh round on top of it would spend a whole new reviewer wave
7344        // re-reading an unchanged patch instead of just retrying the one
7345        // check that actually needs it, and once the budget is spent the
7346        // loop below has nothing left to do at all (its range is empty).
7347        // Retry that check directly instead, exactly the same retry
7348        // `stop_reviewing` already does for its own catch-up case.
7349        if !fresh_review
7350            && self.state.reviews.last().is_some_and(|r| {
7351                r.e2e_status() == E2eStatus::ResourceBlocked
7352                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7353            })
7354        {
7355            let shell = self.state.config.shell();
7356            return self
7357                .stop_unresolved_review(
7358                    "the last round's own verification never resolved",
7359                    &shell,
7360                    &winner.worktree,
7361                )
7362                .await;
7363        }
7364
7365        if granted_review.is_none() {
7366            self.recovery_repair(&winner).await?;
7367        }
7368        if self.resource_halt()? {
7369            return Ok(());
7370        }
7371
7372        let repo = self.state.repo.clone();
7373        let root = self.state.worktree_root();
7374        let language = self.state.config.graph.language.clone();
7375        let sessions = self.state.config.graph.sessions;
7376        let artifacts = self.merge_repair_artifacts();
7377        let base = self.landing_base();
7378        let base_short = short(&base);
7379        let reviewers = self.roles.reviewers.clone();
7380        let shell = self.state.config.shell();
7381
7382        for round in (self.state.reviews.len() + 1)..=max_rounds {
7383            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7384            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7385            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7386            // The prior round's own record, already persisted — never a
7387            // hand-carried variable of just its failing output: that is
7388            // exactly what let a round's e2e result drift out of sync with
7389            // which commit it was actually about (see `SCHEMA`'s doc for
7390            // schema 8). Judged against `head`, the commit reviewers are
7391            // about to look at now, so the summary always reads as "an
7392            // earlier head" here — this round's own patch has not been
7393            // checked yet.
7394            let prev_verification = self
7395                .state
7396                .reviews
7397                .last()
7398                .and_then(|r| r.verification_summary(&head));
7399            // Only the first round of a run that took a branch over: later
7400            // rounds have this run's own history.
7401            let prior_section = match (&self.state.recovery, round) {
7402                (Some(rec), 1) if self.state.reviews.is_empty() => {
7403                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7404                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7405                            Some(crate::recovery::head_of(
7406                                &git::diff(&winner.worktree, reviewed, "HEAD")
7407                                    .await
7408                                    .unwrap_or_default(),
7409                                crate::recovery::SINCE_DIFF_MAX,
7410                            ))
7411                        }
7412                        _ => None,
7413                    };
7414                    Some(prompt::recovery_review(rec, since.as_deref()))
7415                }
7416                _ => None,
7417            };
7418
7419            // Each reviewer gets its own detached checkout of exactly this
7420            // commit: nobody can perturb the winner's tree, and the fixer can
7421            // keep working without racing a reviewer.
7422            let mut jobs = Vec::new();
7423            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7424                self.coordinate(&repo).await?
7425            } else {
7426                None
7427            };
7428            for (r, spec) in reviewers.iter().cloned().enumerate() {
7429                let wt = root.join(format!("review-{}", r + 1));
7430                // `clean -fdx` in a reset wipes setup's products, so every
7431                // round sets the seat up again.
7432                if wt.exists() {
7433                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7434                } else {
7435                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7436                        None
7437                    } else {
7438                        self.coordinate(&repo).await?
7439                    };
7440                    git::worktree_add_detached(&repo, &wt, &head).await?;
7441                }
7442                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7443                    None
7444                } else {
7445                    self.coordinate(&repo).await?
7446                };
7447                self.setup_seat_worktree(
7448                    &repo,
7449                    &wt,
7450                    false,
7451                    coordination.as_ref().or(_setup_lease.as_ref()),
7452                )
7453                .await?;
7454                let seat_key = format!("review-{}", r + 1);
7455                // The seat starts the round on whoever answered it last, not
7456                // on the agent the spec names, so a failure is not re-paid.
7457                let spec = pick_start_spec(
7458                    &self.roles.reviewer_roster,
7459                    spec,
7460                    self.state.seat_history.get(&seat_key),
7461                );
7462                let seat = self.seat(&seat_key, &spec.id);
7463                jobs.push(SeatJob {
7464                    prompt: prompt::review(&prompt::ReviewCtx {
7465                        instruction: &self.state.instruction,
7466                        branch: &winner.branch,
7467                        base_short: &base_short,
7468                        stat: &stat,
7469                        patch: &patch,
7470                        verification: prev_verification.as_ref(),
7471                        prior: prior_section.as_deref(),
7472                        reviewers: reviewers.len(),
7473                        round,
7474                        rounds: max_rounds,
7475                        // A review-only run has no rankings, so nothing
7476                        // competed for this patch and the reviewer is told so.
7477                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7478                        lens: Lens::for_seat(r),
7479                        language: &language,
7480                        github_language: &self.state.config.graph.github_language,
7481                    }),
7482                    spec,
7483                    seat,
7484                    cwd: wt,
7485                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7486                    allow_write: false,
7487                    sessions,
7488                    artifacts: artifacts.clone(),
7489                    stem: format!("review-{round}-{}", r + 1),
7490                    handover: None,
7491                });
7492            }
7493
7494            drop(coordination);
7495            self.state.event(
7496                "review",
7497                format!(
7498                    "round {round}: {} reviewers on {}",
7499                    jobs.len(),
7500                    short(&head)
7501                ),
7502            );
7503            let mut quota_losses = Vec::new();
7504            let review_retries = self.state.config.graph.retries;
7505            let review_cache = self.state.config.cache_dir();
7506            let ctx = WaveCtx {
7507                carry_seats: true,
7508                pauses: Some((&self.pause, &self.interrupt)),
7509                run: &run_id,
7510                node: "review",
7511                prompts: &prompts,
7512                cache: review_cache.as_deref(),
7513                round: Some(round),
7514            };
7515            let results = ask_json_wave::<Review>(
7516                jobs,
7517                Arc::clone(&self.sem),
7518                review_retries,
7519                &self.roles.reviewer_roster,
7520                &ctx,
7521                &mut quota_losses,
7522                &mut self.state,
7523                &|_: &Review| Ok(()),
7524            )
7525            .await;
7526            if self.state.resource_block.is_some() {
7527                return self.stop_for_resource();
7528            }
7529            // Counted before the move below: how many of *this* round's
7530            // reviewer seats were lost to their own rate limit, as opposed to
7531            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7532            let round_quota_missing = quota_losses.len();
7533            self.state.quota.extend(quota_losses);
7534
7535            let mut records = Vec::new();
7536            let mut all_findings = Vec::new();
7537            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7538                let agent_id = seat.agent.clone();
7539                self.state.seats.insert(seat.key.clone(), seat);
7540                let mut record = ReviewRecord {
7541                    reviewer: r + 1,
7542                    agent: agent_id,
7543                    summary: String::new(),
7544                    findings: Vec::new(),
7545                    vote: None,
7546                    failed: None,
7547                    duration_ms: 0,
7548                    // Set for both outcomes: `failed: Some(_)` with
7549                    // `attempts > 0` is a seat every retry still lost, not a
7550                    // recovered one — only `failed: None` with `attempts > 0`
7551                    // reads as "answered after a nudge" (see this field's own
7552                    // doc).
7553                    attempts,
7554                };
7555                match res {
7556                    Ok((review, out)) => {
7557                        // Sanitized here, at the point every other piece of
7558                        // agent prose in this file is (candidate summaries,
7559                        // deliberation turns, vote reasons): a reviewer's own
7560                        // words are the one thing about it that could name
7561                        // it, and reconsideration below broadcasts this same
7562                        // summary and these same findings to every other
7563                        // seat on the panel.
7564                        record.summary =
7565                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7566                        record.vote = Some(review.vote);
7567                        record.duration_ms = out.duration_ms;
7568                        for (n, mut f) in review.findings.into_iter().enumerate() {
7569                            // ids are magi's, never the agent's: the fixer's
7570                            // adoption report is keyed by them.
7571                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7572                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7573                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7574                            // `file` is agent-supplied prose too, never
7575                            // checked against the real tree — the same
7576                            // exposure `title`/`detail` above have, just in
7577                            // a field easy to forget because it looks like a
7578                            // path rather than free text.
7579                            f.file = f
7580                                .file
7581                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7582                            all_findings.push(f.clone());
7583                            record.findings.push(f);
7584                        }
7585                        self.state.event(
7586                            "review",
7587                            format!(
7588                                "round {round}: reviewer {} voted {} with {} finding(s)",
7589                                r + 1,
7590                                review.vote.label(),
7591                                record.findings.len()
7592                            ),
7593                        );
7594                    }
7595                    Err(e) => {
7596                        record.failed = Some(e.to_string());
7597                        self.state.event(
7598                            "review",
7599                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7600                        );
7601                    }
7602                }
7603                records.push(record);
7604            }
7605
7606            // Tally the round's votes and, if they split, spend the one
7607            // round of reconsideration the split -> deliberate -> revote
7608            // shape `judge`/`vote` use for the panel, sized down to what a
7609            // read-only review round can afford: one round, and a revote
7610            // rather than an argument, because the panel already wrote its
7611            // reasoning down as findings the first time around.
7612            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7613            let vote_split =
7614                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7615            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7616            if vote_split {
7617                self.state.event(
7618                    "review",
7619                    format!(
7620                        "round {round}: votes split ({}) — one round of reconsideration",
7621                        initial_votes
7622                            .iter()
7623                            .map(|v| v.label())
7624                            .collect::<Vec<_>>()
7625                            .join(", ")
7626                    ),
7627                );
7628                // Seats read every seat's findings and votes, still numbered
7629                // and never named — the same anonymity `review` itself keeps.
7630                let panel: Vec<ReviewSeatReport<'_>> = records
7631                    .iter()
7632                    .filter_map(|r| {
7633                        r.vote.map(|vote| ReviewSeatReport {
7634                            reviewer: r.reviewer,
7635                            vote,
7636                            summary: &r.summary,
7637                            findings: &r.findings,
7638                        })
7639                    })
7640                    .collect();
7641
7642                let mut jobs = Vec::new();
7643                let mut seats_at = Vec::new();
7644                for (r, spec) in reviewers.iter().cloned().enumerate() {
7645                    // A seat with no initial vote has nothing to reconsider
7646                    // from and stays absent, the same as it stayed absent
7647                    // from `panel` above.
7648                    if records[r].vote.is_none() {
7649                        continue;
7650                    }
7651                    let wt = root.join(format!("review-{}", r + 1));
7652                    let seat_key = format!("review-{}", r + 1);
7653                    let spec = self.occupant(&seat_key, spec);
7654                    let seat = self.seat(&seat_key, &spec.id);
7655                    // A seat with no live session has already forgotten the
7656                    // initial review's prompt — restate the patch it is
7657                    // voting on, the same as `deliberate`/`vote` do for a
7658                    // judge in the same position.
7659                    // The panel already carries this seat's own review and
7660                    // vote, so restating the patch makes the prompt whole for
7661                    // a seat handed to another agent.
7662                    let build = |with_patch: bool| {
7663                        prompt::review_reconsider(&ReviewReconsiderCtx {
7664                            instruction: &self.state.instruction,
7665                            reviewer: r + 1,
7666                            lens: Lens::for_seat(r),
7667                            panel: &panel,
7668                            patch: with_patch.then_some(ReviewPatch {
7669                                branch: &winner.branch,
7670                                base_short: &base_short,
7671                                stat: &stat,
7672                                patch: &patch,
7673                            }),
7674                            round,
7675                            rounds: max_rounds,
7676                            language: &language,
7677                        })
7678                    };
7679                    let full = build(true);
7680                    let prompt = if has_context(&spec, &seat, sessions) {
7681                        build(false)
7682                    } else {
7683                        full.clone()
7684                    };
7685                    jobs.push(SeatJob {
7686                        prompt,
7687                        spec,
7688                        seat,
7689                        cwd: wt,
7690                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7691                        allow_write: false,
7692                        sessions,
7693                        artifacts: artifacts.clone(),
7694                        stem: format!("review-{round}-reconsider-{}", r + 1),
7695                        handover: Some(full),
7696                    });
7697                    seats_at.push(r);
7698                }
7699
7700                let mut recon_quota_losses = Vec::new();
7701                let recon_cache = self.state.config.cache_dir();
7702                let recon_ctx = WaveCtx {
7703                    carry_seats: true,
7704                    pauses: Some((&self.pause, &self.interrupt)),
7705                    run: &run_id,
7706                    node: "review",
7707                    prompts: &prompts,
7708                    cache: recon_cache.as_deref(),
7709                    round: Some(round),
7710                };
7711                let recon_results = ask_json_wave::<ReviewRevote>(
7712                    jobs,
7713                    Arc::clone(&self.sem),
7714                    review_retries,
7715                    &self.roles.reviewer_roster,
7716                    &recon_ctx,
7717                    &mut recon_quota_losses,
7718                    &mut self.state,
7719                    &|_: &ReviewRevote| Ok(()),
7720                )
7721                .await;
7722                if self.state.resource_block.is_some() {
7723                    return self.stop_for_resource();
7724                }
7725                self.state.quota.extend(recon_quota_losses);
7726
7727                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7728                    let agent_id = seat.agent.clone();
7729                    self.state.seats.insert(seat.key.clone(), seat);
7730                    let mut rec = ReviewRevoteRecord {
7731                        reviewer: r + 1,
7732                        agent: agent_id,
7733                        vote: None,
7734                        reason: String::new(),
7735                        failed: None,
7736                    };
7737                    match res {
7738                        Ok((rv, _)) => {
7739                            rec.vote = Some(rv.vote);
7740                            rec.reason =
7741                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7742                            self.state.event(
7743                                "review",
7744                                format!(
7745                                    "round {round}: reviewer {} revoted {}",
7746                                    r + 1,
7747                                    rv.vote.label()
7748                                ),
7749                            );
7750                        }
7751                        Err(e) => {
7752                            rec.failed = Some(e.to_string());
7753                            self.state.event(
7754                                "review",
7755                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7756                            );
7757                        }
7758                    }
7759                    reconsideration.push(rec);
7760                }
7761            } else if initial_votes.len() > 1 {
7762                self.state.event(
7763                    "review",
7764                    format!(
7765                        "round {round}: votes agreed ({}) — no reconsideration",
7766                        initial_votes[0].label()
7767                    ),
7768                );
7769            }
7770
7771            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7772            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7773            // A round that already has a blocking finding and a round left to
7774            // try is going back to the fixer no matter what `verify.e2e`
7775            // says, so running it first only spends the loop's slowest step
7776            // (minutes, for a Rust repo's full test suite) on a head about
7777            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7778            // runs once a round has no blocking findings left (see
7779            // `round_is_clean`, which a deferred — empty — `e2e` can never
7780            // satisfy since `blocking` is nonzero whenever this branch is
7781            // taken), and `stop_reviewing` forces a real run before it will
7782            // ever read a deferred round as green.
7783            let defer_e2e =
7784                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7785            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7786                let reason =
7787                    format!("{blocking} blocking finding(s) already required a fix this round");
7788                self.state.event(
7789                    "verify",
7790                    format!(
7791                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7792                         {}); it will run once a round has none left",
7793                        short(&head)
7794                    ),
7795                );
7796                (Vec::new(), false, true, Some(reason))
7797            } else {
7798                let e2e_commands = self.state.config.verify.e2e.clone();
7799                let cache_dir = self.state.config.cache_dir();
7800                let context = format!("round {round}");
7801                let wait = self.repository_wait();
7802                let (e2e, verify_retried) = with_cache_lease(
7803                    &mut self.state,
7804                    cache_dir.as_deref(),
7805                    "e2e",
7806                    "e2e",
7807                    &winner.worktree,
7808                    &head,
7809                    verify_timeout,
7810                    &context,
7811                    &wait,
7812                    |state, budget| {
7813                        let shell = shell.clone();
7814                        let e2e_commands = e2e_commands.clone();
7815                        let worktree = winner.worktree.clone();
7816                        let context = context.clone();
7817                        let winner = winner.clone();
7818                        async move {
7819                            if !e2e_commands.is_empty() {
7820                                // The suite certifies one SHA. Format before it
7821                                // runs, or the commit `pre_gate` makes at the
7822                                // gate owes the whole suite again.
7823                                Self::run_pre_gate(state, &winner).await;
7824                            }
7825                            run_e2e_with_retry(
7826                                state,
7827                                &shell,
7828                                &e2e_commands,
7829                                &worktree,
7830                                budget,
7831                                &context,
7832                                Some(round),
7833                            )
7834                            .await
7835                        }
7836                    },
7837                )
7838                .await?;
7839                (e2e, verify_retried, false, None)
7840            };
7841
7842            let expected = records.len();
7843            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7844            let incomplete = answered < expected;
7845            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7846            let policy = self.state.config.graph.incomplete_review;
7847            let clean = round_is_clean(
7848                blocking,
7849                e2e_ok,
7850                answered,
7851                expected,
7852                round_quota_missing,
7853                policy,
7854            );
7855
7856            let mut round_record = ReviewRound {
7857                round,
7858                head: head.clone(),
7859                verified_head: None,
7860                verified_at: None,
7861                reviews: records,
7862                e2e,
7863                verify_retried,
7864                e2e_deferred,
7865                e2e_defer_reason,
7866                fix: None,
7867                blocking,
7868                answered,
7869                expected,
7870                clean,
7871                progressed: false,
7872                vote_split,
7873                reconsideration,
7874                verdict: None,
7875            };
7876            // The final vote per seat is its revote where reconsideration
7877            // ran and answered, its initial vote otherwise — the same
7878            // fallback `tally` uses for a judge whose private vote failed.
7879            round_record.verdict = ReviewVote::worst(
7880                round_record
7881                    .final_votes()
7882                    .into_iter()
7883                    .map(|(_, _, vote)| vote),
7884            );
7885            // Which commit and when magi actually attempted to check —
7886            // known the moment a command was dispatched against `head`,
7887            // whether or not it finished: a resource-blocked attempt still
7888            // targeted a specific commit at a specific time, and leaving
7889            // that unrecorded is exactly what made `verification_summary`
7890            // report a fresh attempt as "commit unknown ... recorded before
7891            // this was tracked", indistinguishable from a genuinely old,
7892            // untracked record. Only a deferred or unconfigured round never
7893            // ran at all and has nothing to record — see
7894            // `ReviewRound::verified_head`'s own doc.
7895            if !matches!(
7896                round_record.e2e_status(),
7897                E2eStatus::Deferred | E2eStatus::NotConfigured
7898            ) {
7899                // HEAD, not the reviewed `head`: `pre_gate` may have committed
7900                // mechanical fixes before the commands ran.
7901                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
7902                round_record.verified_at = Some(Timestamp::now());
7903            }
7904
7905            if incomplete {
7906                let missing: Vec<String> = round_record
7907                    .reviews
7908                    .iter()
7909                    .filter(|r| r.failed.is_some())
7910                    .map(|r| format!("review-{}", r.reviewer))
7911                    .collect();
7912                self.state.event(
7913                    "review",
7914                    format!(
7915                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
7916                        missing.join(", ")
7917                    ),
7918                );
7919            }
7920
7921            if clean {
7922                self.state.event(
7923                    "review",
7924                    if incomplete && policy == IncompleteReviewPolicy::Warn {
7925                        format!(
7926                            "round {round}: clean (warn policy, incomplete panel) — no \
7927                             blocking findings from the seats that answered, verification green"
7928                        )
7929                    } else if incomplete {
7930                        format!(
7931                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
7932                             quorum) — no blocking findings from the seats that answered, \
7933                             verification green",
7934                            expected - answered
7935                        )
7936                    } else {
7937                        format!("round {round}: clean — no blocking findings, verification green")
7938                    },
7939                );
7940                self.state.reviews.push(round_record);
7941                self.state.status = RunStatus::Gating;
7942                self.state.save()?;
7943                return Ok(());
7944            }
7945
7946            // Nothing was raised and verification passed, but not every seat
7947            // answered and `round_is_clean` still refused to call it clean —
7948            // either a seat is missing for a reason other than its own quota
7949            // (a crash, a timeout, unparsable output — worth another try), or
7950            // every seat that could have answered lost its quota and nobody
7951            // is left to decide on: re-review rather than send the fixer
7952            // after a round with nothing to fix.
7953            if incomplete && blocking == 0 && e2e_ok {
7954                self.state.reviews.push(round_record);
7955                self.state.save()?;
7956                if round == max_rounds {
7957                    self.state.status = RunStatus::Blocked;
7958                    self.state.event(
7959                        "review",
7960                        format!(
7961                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
7962                             refusing to call it clean",
7963                            expected - answered
7964                        ),
7965                    );
7966                    return Ok(());
7967                }
7968                continue;
7969            }
7970
7971            // Nothing for the fixer to act on (`blocking == 0`) and the only
7972            // reason this round is not clean is that magi itself never got
7973            // a command to run — the shared build cache, not the patch (see
7974            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
7975            // the fixer would invite a change to appease contention that has
7976            // nothing to do with the diff, and would leave this attempt
7977            // sitting in the next round's prompt as if it were about an
7978            // earlier, superseded commit rather than what it actually is:
7979            // the same head, still waiting to be checked. Wait for it the
7980            // same way the final round's own contention is already handled,
7981            // whatever round this happens to be.
7982            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
7983                self.state.reviews.push(round_record);
7984                return self
7985                    .stop_unresolved_review(
7986                        "the round's own verification could not run",
7987                        &shell,
7988                        &winner.worktree,
7989                    )
7990                    .await;
7991            }
7992
7993            if round == max_rounds {
7994                self.state.reviews.push(round_record);
7995                return self
7996                    .stop_reviewing(
7997                        &format!(
7998                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
7999                        ),
8000                        &shell,
8001                        &winner.worktree,
8002                    )
8003                    .await;
8004            }
8005
8006            if !self.fix_review_round(&winner, round_record).await? {
8007                return Ok(());
8008            }
8009        }
8010        Ok(())
8011    }
8012
8013    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8014    /// False means admission or continuation policy stopped the review loop.
8015    async fn fix_review_round(
8016        &mut self,
8017        winner: &Candidate,
8018        mut round_record: ReviewRound,
8019    ) -> Result<bool> {
8020        let round = round_record.round;
8021        let shell = self.state.config.shell();
8022        let step = self.run_fix_round(winner, &mut round_record).await?;
8023        if matches!(step, FixStep::Resource) {
8024            self.stop_for_resource()?;
8025            return Ok(false);
8026        }
8027        if self.state.reviews.len() < round {
8028            self.state.reviews.push(round_record);
8029        } else {
8030            self.state.reviews[round - 1] = round_record;
8031        }
8032        self.state.save()?;
8033
8034        // The fixer's own report never came back this round, even after
8035        // `continue_fix_report`'s own budget was spent on it — not an
8036        // ordinary "no report" (dropped stream, quota, plain failure),
8037        // which already reads that way and is left to the existing round
8038        // budget. Stopping here, rather than opening another round, is
8039        // what keeps a next reviewer/fixer wave from ever being
8040        // dispatched onto `winner.worktree` while whatever the seat's
8041        // last call may still have running there is unaccounted for: no
8042        // process liveness check exists (and none is being added — see
8043        // AGENTS.md/this task's own scope), so the only way to honour
8044        // "nothing starts before a valid report returns" is to not start
8045        // anything further on this worktree from this run at all.
8046        if matches!(step, FixStep::Recorded { report_lost: true }) {
8047            self.stop_reviewing(
8048                "the fixer's adoption report never came back, even after resuming its \
8049                         own seat; refusing to start another round against the same worktree \
8050                         while that is unresolved",
8051                &shell,
8052                &winner.worktree,
8053            )
8054            .await?;
8055            return Ok(false);
8056        }
8057
8058        let streak = self
8059            .state
8060            .reviews
8061            .iter()
8062            .rev()
8063            .take_while(|r| !r.progressed)
8064            .count();
8065        if streak >= STAGNANT_LIMIT {
8066            self.stop_reviewing(
8067                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8068                &shell,
8069                &winner.worktree,
8070            )
8071            .await?;
8072            return Ok(false);
8073        }
8074        Ok(true)
8075    }
8076
8077    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8078    async fn run_fix_round(
8079        &mut self,
8080        winner: &Candidate,
8081        round_record: &mut ReviewRound,
8082    ) -> Result<FixStep> {
8083        let round = round_record.round;
8084        let max_rounds = self.state.config.graph.review_rounds;
8085        let run_id = self.state.id.clone();
8086        let prompts = self.state.config.prompts.clone();
8087        let language = self.state.config.graph.language.clone();
8088        let sessions = self.state.config.graph.sessions;
8089        let artifacts = self.merge_repair_artifacts();
8090        let base = self.landing_base();
8091        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8092        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8093        let this_round_verification = round_record.verification_summary(&head);
8094        let all_findings: Vec<_> = round_record
8095            .reviews
8096            .iter()
8097            .flat_map(|r| r.findings.iter().cloned())
8098            .collect();
8099        // Fix. The winner's own implementer seat continues its conversation:
8100        // the competition is over, so context is pure benefit now.
8101        let blocking_findings: Vec<_> = all_findings
8102            .iter()
8103            .filter(|f| f.severity.blocks())
8104            .cloned()
8105            .collect();
8106        let fix_prompt = prompt::fix_in(
8107            &self.state.instruction,
8108            &blocking_findings,
8109            this_round_verification.as_ref(),
8110            round,
8111            max_rounds,
8112            &language,
8113            &self.state.config.graph.github_language,
8114        );
8115        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8116        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8117        let (job, seat, out) = self
8118            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8119                prompt: fix_prompt.clone(),
8120                spec,
8121                seat,
8122                cwd: winner.worktree.clone(),
8123                timeout,
8124                allow_write: true,
8125                sessions,
8126                artifacts: artifacts.clone(),
8127                stem: format!("fix-{round}"),
8128                handover: None,
8129            })
8130            .await;
8131        // Not asked: the round is not recorded (so a resume repeats it),
8132        // no fixer was handed over to, and the seat is left as it was.
8133        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8134            return Ok(FixStep::Resource);
8135        }
8136        let agent_id = seat.agent.clone();
8137
8138        let mut fix = FixRecord {
8139            agent: agent_id,
8140            addressed: Vec::new(),
8141            rejected: Vec::new(),
8142            notes: String::new(),
8143            committed: false,
8144            failed: None,
8145            duration_ms: 0,
8146            continuation: None,
8147        };
8148        let mut continuation = ContinuationRecord::not_needed();
8149        let mut final_seat = seat.clone();
8150        match out {
8151            AgentOutcome::Ok(o) => {
8152                fix.duration_ms = o.duration_ms;
8153                let parsed = verdict::extract_json::<FixReport>(&o.text);
8154                // A parsed report standing next to a command this same
8155                // reply's own CLI never confirmed the exit status of is
8156                // not a resolved answer — the identical `CommandEvidence`
8157                // `state.jobs` renders, read here instead of only on
8158                // display, per the completion judgment and the shown
8159                // record needing to agree.
8160                let incomplete_reason = match &parsed {
8161                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8162                        "the reply parsed, but it reported a command whose own CLI never \
8163                             confirmed an exit status"
8164                            .to_owned(),
8165                    ),
8166                    Ok(_) => None,
8167                    Err(e) => Some(e.to_string()),
8168                };
8169                match incomplete_reason {
8170                    None => {
8171                        let report = parsed.expect("checked Ok above");
8172                        fix.addressed = report.addressed;
8173                        fix.rejected = report.rejected;
8174                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8175                    }
8176                    Some(reason) => {
8177                        let (resumed_seat, resolved, failure, cont) = self
8178                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8179                            .await;
8180                        fix.duration_ms += cont.cumulative_wait_ms;
8181                        continuation = cont;
8182                        final_seat = resumed_seat;
8183                        match resolved {
8184                            Some(report) => {
8185                                fix.addressed = report.addressed;
8186                                fix.rejected = report.rejected;
8187                                fix.notes =
8188                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8189                            }
8190                            None => fix.failed = failure,
8191                        }
8192                    }
8193                }
8194            }
8195            // The CLI's raw error JSON is not a fix report to parse.
8196            AgentOutcome::Dropped(o) => {
8197                fix.duration_ms = o.duration_ms;
8198                let why = o
8199                    .dropped
8200                    .as_ref()
8201                    .map(|d| d.why.as_str())
8202                    .unwrap_or("the CLI ended the stream without delivering its answer");
8203                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8204            }
8205            AgentOutcome::Quota(o) => {
8206                self.state.quota.push(QuotaLoss::from_report(
8207                    final_seat.key.clone(),
8208                    "fix",
8209                    o.quota.as_ref(),
8210                ));
8211                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8212            }
8213            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8214        }
8215        if self.state.resource_block.is_some() {
8216            self.state.seats.insert(final_seat.key.clone(), final_seat);
8217            return Ok(FixStep::Resource);
8218        }
8219        fix.continuation = Some(continuation);
8220        self.state.seats.insert(final_seat.key.clone(), final_seat);
8221        let coordination = self.coordinate(&winner.worktree).await?;
8222        if let Ok(r) = git::rescue_commit(
8223            &winner.worktree,
8224            &format!("magi: review round {round} fixes (uncommitted work)"),
8225        )
8226        .await
8227        {
8228            self.state.note_withheld("fix", &r.withheld);
8229        }
8230        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8231        fix.committed = after != before;
8232        // Judged by what `git` says moved against base, never by the
8233        // fixer's own `addressed`/`rejected` count — see
8234        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8235        // `patch` snapshot above: swallowing this error would default
8236        // `diff_after` to empty, which almost always differs from a
8237        // non-empty `patch` and reads as "progressed" — exactly backwards
8238        // for a `git` failure the stagnation check cannot see through.
8239        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8240        drop(coordination);
8241        let progressed = diff_after != patch;
8242        let commit_note = if fix.committed {
8243            "committed"
8244        } else {
8245            "NO new commit"
8246        };
8247        let tree_note = if progressed {
8248            "changed vs base"
8249        } else {
8250            "unchanged vs base"
8251        };
8252        self.state.event(
8253            "fix",
8254            match &fix.failed {
8255                // Distinct on purpose from "0 addressed, 0 rejected": the
8256                // fixer's own diff still landed (blocking counts do keep
8257                // falling round over round), only its adoption report did
8258                // not come back, so this must never read like every
8259                // finding was reviewed and declined.
8260                Some(reason) => {
8261                    format!(
8262                        "round {round}: fixer's adoption report was lost ({reason}); \
8263                             {commit_note}, tree {tree_note}"
8264                    )
8265                }
8266                None => format!(
8267                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8268                         {tree_note}{}",
8269                    fix.addressed.len(),
8270                    fix.rejected.len(),
8271                    if continuation.outcome == ContinuationOutcome::Resumed {
8272                        format!(
8273                            " (adoption report recovered after {} continuation(s))",
8274                            continuation.attempts
8275                        )
8276                    } else {
8277                        String::new()
8278                    },
8279                ),
8280            },
8281        );
8282        round_record.fix = Some(fix);
8283        round_record.progressed = progressed;
8284        Ok(FixStep::Recorded {
8285            report_lost: matches!(
8286                continuation.outcome,
8287                ContinuationOutcome::Exhausted
8288                    | ContinuationOutcome::QuotaLost
8289                    | ContinuationOutcome::NoSession
8290            ),
8291        })
8292    }
8293
8294    /// Decide, from the last recorded round's own verification, whether
8295    /// stopping the review loop is a hand-off or a genuine block.
8296    ///
8297    /// Called once the loop has given up trying — the round budget is spent,
8298    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8299    /// findings still open, never while a round is still clean or the
8300    /// incomplete-panel case handled inline above. Gate and e2e are facts
8301    /// about the tree; a lingering review finding is an opinion, and this
8302    /// workload's own `magi stats` puts reviewer precision low enough
8303    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8304    /// must not by itself stand between a green, verified change and the
8305    /// human who decides what to do with it. A red e2e is not an opinion, so
8306    /// that case still blocks, with the failing command and a tail of its
8307    /// output recorded here rather than left in `run.json` for someone to go
8308    /// find.
8309    ///
8310    /// A round that deferred its own e2e (see [`Config::graph`]'s
8311    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8312    /// only because nothing ran, and treating an empty list as a passing one
8313    /// here is exactly the "deferred painted green" bug this function exists
8314    /// to not have. When the last round's own verification never resolved —
8315    /// deferred on purpose, or a real attempt the shared build cache blocked
8316    /// — this makes (or retries) the real run, on the actual worktree this
8317    /// loop is about to stop touching, before deciding anything. A
8318    /// resource-blocked attempt is likewise never read as either green or
8319    /// red: it is evidence about the machine, not the patch (see
8320    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8321    /// blocked cache leaves this call without deciding rather than guessing
8322    /// — the caller retries on a later reentry.
8323    /// Record, once, that the review loop handed off over a blocking finding
8324    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8325    /// `land` asks the owner even with `land_approval` off. Called from every
8326    /// path that concludes `Gating`; a reentry keeps the first record.
8327    fn record_contested_handoff(&mut self) {
8328        if self.state.contested_handoff.is_some() {
8329            return;
8330        }
8331        let Some(contested) = self
8332            .state
8333            .reviews
8334            .last()
8335            .and_then(ReviewRound::contested_handoff)
8336        else {
8337            return;
8338        };
8339        self.state.event(
8340            "review",
8341            format!(
8342                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8343                 wait for the owner's approval",
8344                contested.findings.len(),
8345                contested.rejecters.len()
8346            ),
8347        );
8348        self.state.contested_handoff = Some(contested);
8349    }
8350
8351    async fn stop_unresolved_review(
8352        &mut self,
8353        why: &str,
8354        shell: &[String],
8355        worktree: &Path,
8356    ) -> Result<()> {
8357        self.stop_reviewing_inner(why, shell, worktree, true).await
8358    }
8359
8360    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8361        self.stop_reviewing_inner(why, shell, worktree, false).await
8362    }
8363
8364    async fn stop_reviewing_inner(
8365        &mut self,
8366        why: &str,
8367        shell: &[String],
8368        worktree: &Path,
8369        repairable: bool,
8370    ) -> Result<()> {
8371        let round_idx = self.state.reviews.len() - 1;
8372        // A deferred round and a resource-blocked one are the same shape
8373        // here: neither has a real result yet, and both get one more
8374        // attempt. Read off `e2e_status` — the single source for this —
8375        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8376        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8377        // still retries instead of being read as a settled result the
8378        // instant it stops being empty.
8379        let needs_catchup_run = matches!(
8380            self.state.reviews[round_idx].e2e_status(),
8381            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8382        );
8383        if needs_catchup_run {
8384            let round = self.state.reviews[round_idx].round;
8385            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8386            let commands = self.state.config.verify.e2e.clone();
8387            let before_head = git::rev_parse(worktree, "HEAD").await?;
8388            let winner = self.state.winner().cloned();
8389            let cache_dir = self.state.config.cache_dir();
8390            let context = format!(
8391                "round {round}: verification unresolved, catching up before the final decision"
8392            );
8393            let wait = self.repository_wait();
8394            let (outcomes, verify_retried) = with_cache_lease(
8395                &mut self.state,
8396                cache_dir.as_deref(),
8397                "e2e",
8398                "e2e",
8399                worktree,
8400                &before_head,
8401                timeout,
8402                &context,
8403                &wait,
8404                |state, budget| {
8405                    let shell = shell.to_vec();
8406                    let commands = commands.clone();
8407                    let context = context.clone();
8408                    async move {
8409                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8410                            // Same reason as in the round itself: format before
8411                            // the suite, not after it.
8412                            Self::run_pre_gate(state, &winner).await;
8413                        }
8414                        run_e2e_with_retry(
8415                            state,
8416                            &shell,
8417                            &commands,
8418                            worktree,
8419                            budget,
8420                            &context,
8421                            Some(round),
8422                        )
8423                        .await
8424                    }
8425                },
8426            )
8427            .await?;
8428            // After `pre_gate`: the commit the commands actually ran against.
8429            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8430            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8431                self.state.record_base_progress(&attempted_head);
8432            }
8433            let last = &mut self.state.reviews[round_idx];
8434            last.e2e = outcomes;
8435            last.verify_retried = verify_retried;
8436            // Always the commit and time this attempt actually targeted,
8437            // whether or not it happens to equal the reviewed `head` and
8438            // whether or not a command finished — see
8439            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8440            // attempt is recorded too, so a later reader sees "attempted
8441            // again at T2" rather than silence.
8442            last.verified_head = Some(attempted_head);
8443            last.verified_at = Some(Timestamp::now());
8444            if verify_inconclusive(&last.e2e) {
8445                // Still not a real result: `e2e_deferred` is left exactly
8446                // as it was, so `needs_catchup_run` above reads
8447                // `ResourceBlocked` (via `e2e_status`, which checks
8448                // `resource_blocked` before `e2e_deferred`) and retries
8449                // again on the next reentry, rather than recording
8450                // contention as a red e2e and blocking the run on it.
8451                self.state.save()?;
8452                return Ok(());
8453            }
8454            last.e2e_deferred = false;
8455            // A complete panel may have been saved as unclean solely because
8456            // verification could not run. Refresh that verdict with the new
8457            // outcomes before a granted repair consumes the round's result.
8458            // Incomplete panels retain their original policy/quota decision.
8459            if last.answered == last.expected {
8460                last.clean = round_is_clean(
8461                    last.blocking,
8462                    last.e2e.iter().all(CommandOutcome::ok),
8463                    last.answered,
8464                    last.expected,
8465                    0,
8466                    self.state.config.graph.incomplete_review,
8467                );
8468            }
8469        }
8470        let last = &self.state.reviews[round_idx];
8471        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8472
8473        match last.e2e_status() {
8474            E2eStatus::Failed => {
8475                let red: Vec<String> = last
8476                    .e2e
8477                    .iter()
8478                    .filter(|o| !o.ok())
8479                    .map(|o| {
8480                        format!(
8481                            "`{}` -> {:?}\n{}",
8482                            o.command,
8483                            o.code,
8484                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8485                        )
8486                    })
8487                    .collect();
8488                let can_repair = last.blocking == 0 && last.fix.is_none();
8489                self.state.reviews[round_idx].clean = false;
8490                self.state
8491                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8492                self.state.status = RunStatus::Blocked;
8493                if repairable
8494                    && can_repair
8495                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8496                {
8497                    self.state.status = RunStatus::Reviewing;
8498                }
8499            }
8500            // `needs_catchup_run` above already retried once this call; if
8501            // it is still blocked, this is magi's own admission it could
8502            // not get a command to run, never a verdict on the patch — the
8503            // run is left exactly where a later reentry can retry again.
8504            E2eStatus::ResourceBlocked => {
8505                self.state.event(
8506                    "review",
8507                    format!(
8508                        "{why}; e2e could not run (resource unavailable); not \
8509                         deciding yet"
8510                    ),
8511                );
8512            }
8513            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8514                self.state.event(
8515                    "review",
8516                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8517                );
8518                self.record_contested_handoff();
8519                self.state.status = RunStatus::Gating;
8520            }
8521        }
8522        self.state.save()?;
8523        Ok(())
8524    }
8525
8526    // ----------------------------------------------------------------- gate
8527
8528    async fn gate(&mut self) -> Result<()> {
8529        if self.hold_base_sync().await? {
8530            return Ok(());
8531        }
8532        // Judged by the review record itself, not by `status`: a solo
8533        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8534        // reentry (see `judge`), and trusting it here is exactly how a run
8535        // that exhausted its review budget got gated and merged a second
8536        // time around. `review_conclusion` recomputes the review loop's own
8537        // verdict from the round records themselves — `Gating` for a clean
8538        // round or a hand-off (see `stop_reviewing`), anything else means the
8539        // loop is still going or genuinely blocked.
8540        // A base the winner could not be replayed onto is a decision, not a
8541        // round: there is no landing tree to gate. Read as its own record for
8542        // the same reason the review verdict is.
8543        if self.state.status == RunStatus::Failed
8544            || self
8545                .state
8546                .base_sync
8547                .as_ref()
8548                .is_some_and(|s| s.conflict.is_some())
8549            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8550                != Some(RunStatus::Gating)
8551        {
8552            return Ok(());
8553        }
8554        let Some(winner) = self.state.winner().cloned() else {
8555            return Ok(());
8556        };
8557        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8558        self.state.reconcile_verification_head(&head);
8559        self.state.save()?;
8560        let wait = self.repository_wait();
8561        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8562            return Ok(());
8563        }
8564        if self.state.gate_ran {
8565            // `review_loop` derives its conclusion from the clean review
8566            // record on every reentry and therefore puts a completed run back
8567            // in `Gating`. A recorded gate is a stronger, terminal fact:
8568            // retain its original command output (or lack of any, for a repo
8569            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8570            // doc) and restore `Blocked` on a real failure rather than
8571            // pretending the command is still running or running it a second
8572            // time. `gate_ran == false` remains the only shape — unattempted,
8573            // or a resource-blocked retry — that may still need to execute a
8574            // command.
8575            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8576                self.state.status = RunStatus::Blocked;
8577                self.state.save()?;
8578            }
8579            return Ok(());
8580        }
8581        self.state.status = RunStatus::Gating;
8582        let mut outcomes = self.run_gate(&winner).await?;
8583        let mut attempted_head = self.state.gate_head.clone();
8584        loop {
8585            // A resource-blocked outcome means the gate command never actually
8586            // ran - the shared build cache could not be acquired or confirmed
8587            // fresh in time - which is evidence about the machine, not about
8588            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8589            // Recording it as a red gate would mark a run `Blocked` on nothing
8590            // but contention magi has already logged; leaving `self.state.gate`
8591            // empty and `self.state.gate_ran` false instead keeps the shape
8592            // this function already treats as "still needs to run" (see the
8593            // early-return above), so the next call retries the command
8594            // rather than concluding anything.
8595            if verify_inconclusive(&outcomes) {
8596                self.state.save()?;
8597                return Ok(());
8598            }
8599            if outcomes.iter().all(CommandOutcome::ok) {
8600                break;
8601            }
8602            let fixes_before = self.state.gate_fixes.len();
8603            match self.gate_fix_round(&winner, &outcomes).await? {
8604                GateFix::Retry => {
8605                    outcomes = self.run_gate(&winner).await?;
8606                    attempted_head = self.state.gate_head.clone();
8607                }
8608                GateFix::Stop => {
8609                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8610                    if self.state.gate_fixes.len() > fixes_before
8611                        && attempted_head.as_deref() != Some(current.as_str())
8612                        && verify_current_head(&mut self.state, &winner, &wait).await?
8613                    {
8614                        // A new SHA owes a gate even when a spent fixer changed only
8615                        // commit metadata. This does not grant another repair round.
8616                        outcomes = self.run_gate(&winner).await?;
8617                        attempted_head = self.state.gate_head.clone();
8618                    } else {
8619                        break;
8620                    }
8621                }
8622                GateFix::Defer => {
8623                    self.state.save()?;
8624                    return Ok(());
8625                }
8626            }
8627        }
8628        let passed = outcomes.iter().all(CommandOutcome::ok);
8629        self.state.gate = outcomes;
8630        self.state.gate_ran = true;
8631        self.state.gate_head = attempted_head;
8632        if !self.state.gate.is_empty()
8633            && !verify_inconclusive(&self.state.gate)
8634            && let Some(head) = self.state.gate_head.clone()
8635        {
8636            self.state.record_base_progress(&head);
8637        }
8638        self.state.save()?;
8639        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8640            return Ok(());
8641        }
8642        if !passed {
8643            self.state.status = RunStatus::Blocked;
8644            let spent = self.state.gate_fixes.len();
8645            self.state.event(
8646                "gate",
8647                if spent == 0 {
8648                    "gate failed; not merging".to_owned()
8649                } else {
8650                    format!("gate failed after {spent} gate-fix round(s); not merging")
8651                },
8652            );
8653        }
8654        self.state.save()?;
8655        Ok(())
8656    }
8657
8658    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8659    /// changed into one commit. Runs before `verify.e2e` in the review loop
8660    /// and again before the gate commands, always on the winner and never on
8661    /// a candidate awaiting judging.
8662    ///
8663    /// Before e2e as well as before the gate because command evidence belongs
8664    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8665    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8666    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8667    /// own call then finds nothing left to change. The commands must be
8668    /// idempotent; one that is not makes a commit per call.
8669    ///
8670    /// Never fails the run: a non-zero exit or timeout is a warning and a
8671    /// recorded outcome, and the gate remains the single arbiter. Nothing
8672    /// configured means nothing happens - no event, no commit. `commit_all`
8673    /// commits any leftover change under the neutral identity and returns
8674    /// `false` when the tree is clean, so no empty commit is ever made.
8675    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8676        let commands = state.config.verify.pre_gate.clone();
8677        if commands.is_empty() {
8678            return;
8679        }
8680        let shell = state.config.shell();
8681        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8682        let (outcomes, _) = run_commands(
8683            state,
8684            "pre_gate",
8685            "pre_gate",
8686            0,
8687            &shell,
8688            &commands,
8689            &winner.worktree,
8690            timeout,
8691        )
8692        .await;
8693        for o in &outcomes {
8694            if !o.ok() {
8695                tracing::warn!(
8696                    "pre_gate `{}` failed ({:?}); the gate decides",
8697                    o.command,
8698                    o.code
8699                );
8700            }
8701            state.event(
8702                "pre_gate",
8703                format!(
8704                    "`{}` -> {}",
8705                    o.command,
8706                    if o.ok() {
8707                        "pass".to_owned()
8708                    } else {
8709                        format!(
8710                            "FAIL ({:?})\n{}",
8711                            o.code,
8712                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8713                        )
8714                    }
8715                ),
8716            );
8717        }
8718        state.pre_gate = outcomes;
8719        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8720            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8721                Ok(head) => {
8722                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8723                    state.pre_gate_commit = Some(head);
8724                }
8725                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8726            },
8727            Ok(false) => {}
8728            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8729        }
8730        if let Err(e) = state.save() {
8731            tracing::warn!("could not persist the pre_gate record: {e:#}");
8732        }
8733    }
8734
8735    /// Run `verify.gate` once against the winner's current tree, logging one
8736    /// event per command. Empty when nothing is configured.
8737    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8738        let wait = self.repository_wait();
8739        run_landing_gate(&mut self.state, winner, &wait).await
8740    }
8741
8742    /// One bounded fix round for a failing gate.
8743    ///
8744    /// The fixer is told the failure came from the gate itself, not from a
8745    /// reviewer, and is shown the failed commands, their exit codes and a tail
8746    /// of their output - whatever `[verify].gate` holds, nothing here knows
8747    /// what those commands run. Only a normal non-zero exit that printed
8748    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8749    /// command or a full disk says nothing about the code, and a fixer sent
8750    /// after it can only appease the machine. The round is judged by what git
8751    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8752    /// again before the gate does, so a fix cannot trade a green gate for a
8753    /// red e2e unnoticed.
8754    async fn gate_fix_round(
8755        &mut self,
8756        winner: &Candidate,
8757        outcomes: &[CommandOutcome],
8758    ) -> Result<GateFix> {
8759        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8760            g.phase == crate::repair_budget::Phase::Fixing
8761                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8762        }) {
8763            self.state.gate_fixes.len().saturating_add(1)
8764        } else {
8765            self.state.config.graph.gate_fix_rounds
8766        };
8767        let spent = self.state.gate_fixes.len();
8768        if spent >= cap {
8769            if cap > 0 {
8770                self.state.event(
8771                    "gate",
8772                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8773                );
8774            }
8775            return Ok(GateFix::Stop);
8776        }
8777        if !gate_fixable(outcomes) {
8778            self.state.event(
8779                "gate",
8780                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8781                 command or similar); not spending a fix round on it",
8782            );
8783            return Ok(GateFix::Stop);
8784        }
8785        let min_free = self.state.config.disk.min_free_bytes;
8786        if min_free > 0 {
8787            match crate::disk::free_bytes(&winner.worktree) {
8788                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8789                Ok(free) => {
8790                    self.state.event(
8791                        "gate",
8792                        format!(
8793                            "only {free} bytes free ({min_free} required by `[disk] \
8794                             min_free_bytes`); not spending a fix round on a failure the disk \
8795                             may explain"
8796                        ),
8797                    );
8798                    return Ok(GateFix::Stop);
8799                }
8800                Err(e) => {
8801                    self.state.event(
8802                        "gate",
8803                        format!("free disk space could not be measured ({e:#}); no fix round"),
8804                    );
8805                    return Ok(GateFix::Stop);
8806                }
8807            }
8808        }
8809
8810        let attempt = spent + 1;
8811        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8812        let base = self.landing_base();
8813        let fix_prompt = prompt::gate_fix_in(
8814            &self.state.instruction,
8815            &failed,
8816            attempt,
8817            cap,
8818            &self.state.config.graph.language,
8819            &self.state.config.graph.github_language,
8820        );
8821        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8822        let sessions = self.state.config.graph.sessions;
8823        let artifacts = self.merge_repair_artifacts();
8824        self.state.event(
8825            "gate",
8826            format!("gate failed; gate-fix round {attempt} of {cap}"),
8827        );
8828        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8829        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8830        // Persist before invoking the fixer: it may commit and then be
8831        // interrupted before its result (or the following e2e) is saved.
8832        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8833            head: before.clone(),
8834            passed: false,
8835            outcomes: Vec::new(),
8836        });
8837        self.state.save()?;
8838        let (_, seat, out) = self
8839            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8840                prompt: fix_prompt.clone(),
8841                spec,
8842                seat,
8843                cwd: winner.worktree.clone(),
8844                timeout,
8845                allow_write: true,
8846                sessions,
8847                artifacts: artifacts.clone(),
8848                stem: format!("gate-fix-{attempt}"),
8849                handover: None,
8850            })
8851            .await;
8852        // The fixer was never asked: no round is spent (nothing is recorded)
8853        // and a later reentry asks the same agent again.
8854        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8855            return Ok(GateFix::Defer);
8856        }
8857        let mut record = GateFixRecord {
8858            agent: seat.agent.clone(),
8859            failed,
8860            notes: String::new(),
8861            committed: false,
8862            error: None,
8863        };
8864        match out {
8865            AgentOutcome::Ok(o) => {
8866                // A missing report is not a failed fix: the round is judged
8867                // by the tree below, and the report only carries prose.
8868                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
8869                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8870                }
8871            }
8872            AgentOutcome::Dropped(_) => {
8873                record.error = Some("the CLI dropped the stream".to_owned());
8874            }
8875            AgentOutcome::Quota(o) => {
8876                self.state.quota.push(QuotaLoss::from_report(
8877                    seat.key.clone(),
8878                    "gate-fix",
8879                    o.quota.as_ref(),
8880                ));
8881                record.error = Some("rate limited (quota); fixer could not run".to_owned());
8882            }
8883            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
8884        }
8885        self.state.seats.insert(seat.key.clone(), seat);
8886        let coordination = self.coordinate(&winner.worktree).await?;
8887        if let Ok(r) = git::rescue_commit(
8888            &winner.worktree,
8889            &format!("magi: gate fix {attempt} (uncommitted work)"),
8890        )
8891        .await
8892        {
8893            self.state.note_withheld("gate-fix", &r.withheld);
8894        }
8895        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8896        record.committed = after != before;
8897        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
8898        let note = record.error.clone();
8899        self.state.gate_fixes.push(record);
8900        self.state.save()?;
8901        if !changed {
8902            self.state.event(
8903                "gate",
8904                match note {
8905                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
8906                    None => format!("gate-fix round {attempt}: the tree did not change"),
8907                },
8908            );
8909            return Ok(GateFix::Stop);
8910        }
8911        self.state.event(
8912            "gate",
8913            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
8914        );
8915
8916        drop(coordination);
8917        let wait = self.repository_wait();
8918        check_gate_repair_e2e(&mut self.state, winner, &wait).await
8919    }
8920
8921    // ---------------------------------------------------------------- merge
8922
8923    /// One read-only rewrite by the summary's author; a text the gate still
8924    /// withholds goes to the owner (see `github_text`) and the fixed fallback
8925    /// applies on their word or on silence. `None` means the run is parked on
8926    /// that question and nothing may be pushed or opened yet.
8927    async fn guarded_pr_message(
8928        &mut self,
8929        winner: &Candidate,
8930        facts: Option<&BranchFacts>,
8931        posting: bool,
8932    ) -> Result<Option<PrMessage>> {
8933        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
8934        let head = match final_head.as_deref() {
8935            Some(h) => crate::pr_outcome::FinalHead::At(h),
8936            None => crate::pr_outcome::FinalHead::Unknown,
8937        };
8938        // Only a pull request that is about to be posted pays for a summary.
8939        let summarized = if posting {
8940            Some(self.summarize_change(winner, final_head.as_deref()).await)
8941        } else {
8942            None
8943        };
8944        // A busy shared resource is not a permanent cause: publishing an
8945        // "unavailable" description would stick (a later head move never
8946        // edits the body). Stop before anything is pushed or opened; the
8947        // run is `Blocked` and a resume asks the summary again.
8948        if self.state.resource_block.is_some() {
8949            self.state.event(
8950                "pr-summary",
8951                "a shared resource was busy; nothing was published, resume to summarize again",
8952            );
8953            return Ok(None);
8954        }
8955        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
8956            anyhow::bail!(
8957                "the final commit moved during public description generation; retry before publishing"
8958            );
8959        }
8960        let note = match (&summarized, &self.state.change_summary) {
8961            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
8962            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
8963            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
8964            (None, _) => ChangeNote::NotAsked,
8965        };
8966        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
8967        if !posting {
8968            let identity = crate::scrub::Identity::current();
8969            return Ok(Some(PrMessage {
8970                title: crate::scrub::scrub(&pr.title, &identity),
8971                body: crate::scrub::scrub(&pr.body, &identity),
8972            }));
8973        }
8974        // This very text was already rejected and asked about: no second
8975        // judge call, rewrite or question, just carry the record on.
8976        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
8977        if let Some(known) = self
8978            .state
8979            .github_text
8980            .clone()
8981            .filter(|g| g.fingerprint == raw_fp)
8982        {
8983            return self.settle_withheld(winner, &pr, known).await;
8984        }
8985        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
8986        let mut violations =
8987            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
8988        let identity = crate::scrub::Identity::current();
8989        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
8990            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
8991            && !violations.contains(&crate::github_text::Violation::SensitiveData)
8992        {
8993            violations.push(crate::github_text::Violation::SensitiveData);
8994        }
8995        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
8996        // only a language violation starts one; sensitive data alone goes
8997        // straight to the owner, with the redacted text as the fallback.
8998        let has_language = violations
8999            .iter()
9000            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9001        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9002            self.state.event(
9003                "github-text",
9004                if has_language {
9005                    format!("description rejected: {violations:?}; requesting one rewrite")
9006                } else {
9007                    format!("description rejected: {violations:?}; asking the owner")
9008                },
9009            );
9010            let mut rewritten = false;
9011            let mut rejected_rewrite = None;
9012            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9013            {
9014                let output = text;
9015                if let Some(title) = summary_title(&output) {
9016                    // Judge the redacted candidate that will actually be posted.
9017                    // Sensitive data alone must not discard a useful rewrite.
9018                    let raw_body = summary_without_title(&output);
9019                    let clean_title = crate::scrub::scrub(&title, &identity);
9020                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9021                    let redacted = clean_title != title || body != raw_body;
9022                    let title = clean_title;
9023                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9024                    if !complete {
9025                        self.state.event(
9026                            "github-text",
9027                            "description rewrite omitted required findings",
9028                        );
9029                    }
9030                    if !body.trim().is_empty() {
9031                        body.push_str("\n\n");
9032                        body.push_str(&public_pr_evidence(&self.state, head));
9033                    }
9034                    let marker = format!("magi:run/{}", self.state.id);
9035                    if !body.trim().is_empty() && !body.contains(&marker) {
9036                        body.push_str(&format!("\n\n{marker}"));
9037                    }
9038                    let rewrite = PrMessage {
9039                        title: title.clone(),
9040                        body: body.clone(),
9041                    };
9042                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9043                    let mut failed = crate::github_text::check_for(
9044                        &self.state.config.graph,
9045                        &title,
9046                        &body,
9047                        redecision,
9048                    );
9049                    if (!crate::github_text::shareable(&title)
9050                        || !crate::github_text::shareable(&body))
9051                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9052                    {
9053                        failed.push(crate::github_text::Violation::SensitiveData);
9054                    }
9055                    if complete
9056                        && !title.trim().is_empty()
9057                        && !body.trim().is_empty()
9058                        && !failed.is_empty()
9059                    {
9060                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9061                            title: title.clone(),
9062                            body: body.clone(),
9063                            failed: failed
9064                                .iter()
9065                                .map(|v| crate::github_text::category(*v).to_owned())
9066                                .collect(),
9067                        });
9068                    }
9069                    if complete
9070                        && !title.trim().is_empty()
9071                        && !raw_body.trim().is_empty()
9072                        && failed.is_empty()
9073                    {
9074                        decision = redecision;
9075                        pr = PrMessage { title, body };
9076                        rewritten = true;
9077                        self.state
9078                            .event("github-text", "description rewrite passed");
9079                        if redacted {
9080                            self.state.event(
9081                                "github-text",
9082                                "sensitive data removed from description rewrite",
9083                            );
9084                        }
9085                    }
9086                }
9087            }
9088            if !rewritten {
9089                self.state.event(
9090                    "github-text",
9091                    "description rewrite unavailable or rejected; asking the owner",
9092                );
9093                if let Some(w) =
9094                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9095                {
9096                    // A different text than the one asked about before: that
9097                    // question no longer describes anything.
9098                    self.retire_github_text_question("the withheld text changed");
9099                    let record = crate::run::GithubTextAsk {
9100                        rewrite: rejected_rewrite,
9101                        fingerprint: raw_fp,
9102                        title: w.title,
9103                        body: w.body,
9104                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9105                        question: None,
9106                        asks: 0,
9107                        resolved: false,
9108                        chosen_title: None,
9109                        choice: None,
9110                        publication: None,
9111                    };
9112                    return self.settle_withheld(winner, &pr, record).await;
9113                }
9114            }
9115        }
9116        let (title, body) =
9117            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9118        Ok(Some(PrMessage { title, body }))
9119    }
9120
9121    /// Describe the whole change from its final diff in either run mode.
9122    ///
9123    /// The summary is tied to the final commit and to the merge base of the
9124    /// resolved remote base; a record for any other pair is dropped and the
9125    /// agent asked again, so a description never outlives the diff it was
9126    /// written from. The seat is read-only and the prompt tells it to read the
9127    /// diff and the code around it. `[roles] synthesizer` selects the agents
9128    /// (unset: the default pick), each asked at most once, advancing on an
9129    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9130    /// carries the reason it is unavailable; nothing is invented then.
9131    async fn summarize_change(
9132        &mut self,
9133        winner: &Candidate,
9134        head: Option<&str>,
9135    ) -> std::result::Result<(), String> {
9136        let Some(head) = head else {
9137            return Err("the final commit could not be read".to_owned());
9138        };
9139        let remote = self.state.config.merge.remote.clone();
9140        let tracking = format!("{remote}/{}", self.state.base_branch);
9141        if !git::rev_exists(&winner.worktree, &tracking).await {
9142            return Err(format!("the remote base `{tracking}` could not be read"));
9143        }
9144        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9145            Ok(b) if !b.is_empty() => b,
9146            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9147        };
9148        let evidence = crate::pr_outcome::summary_evidence(
9149            &self.state,
9150            crate::pr_outcome::FinalHead::At(head),
9151        );
9152        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9153        if self
9154            .state
9155            .change_summary
9156            .as_ref()
9157            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9158        {
9159            return Ok(());
9160        }
9161        if self.state.change_summary.take().is_some() {
9162            self.state.event(
9163                "pr-summary",
9164                "the final diff or evidence changed; the earlier change summary was discarded",
9165            );
9166        }
9167        // Save the source snapshot even if no generation agent is available.
9168        if let Err(e) = write_artifact(
9169            &self.state,
9170            &format!("public-description-{fingerprint}.md"),
9171            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9172        ) {
9173            tracing::warn!("could not save public description evidence: {e:#}");
9174        }
9175        let chain = match agent::pick_chain(
9176            &self.state.config.agents,
9177            self.state.config.roles.synthesizer.as_ref(),
9178            &agent::installed,
9179            "synthesizer",
9180        ) {
9181            Ok(chain) => chain,
9182            Err(e) => {
9183                tracing::warn!("no agent for the change summary: {e:#}");
9184                self.state.event("pr-summary", "no summary agent available");
9185                return Err("no agent was available to summarize it".to_owned());
9186            }
9187        };
9188        let subjects = git::subjects(&winner.worktree, &base, head)
9189            .await
9190            .unwrap_or_default();
9191        let stat = git::diff_stat(&winner.worktree, &base, head)
9192            .await
9193            .unwrap_or_default();
9194        let stat: String = stat.chars().take(6_000).collect();
9195        let mut prompt = crate::prompt::change_summary_in(
9196            &base,
9197            head,
9198            &subjects,
9199            stat.trim(),
9200            &self.state.config.graph.github_language,
9201        );
9202        prompt.push_str(&format!("\n\n# Final-state evidence\n{evidence}\n\nUse these records as evidence, not public text to copy. Paraphrase every open or declined finding and its reason in the requested GitHub language, retaining its exact ID and severity when available. Do not translate or quote internal operator reports. Explain unresolved risks for a reviewer without the task conversation. Historical sandbox or commit failures are not the final state. Verification is appended from these records; do not make additional validation claims."));
9203        let sessions = self.state.config.graph.sessions;
9204        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9205        let prompts = self.state.config.prompts.clone();
9206        let cache = self.state.config.cache_dir();
9207        let run = self.state.id.clone();
9208        for (i, spec) in chain.into_iter().enumerate() {
9209            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9210            let github_spec = match agent::for_github_text(
9211                &spec,
9212                &self.state.config.graph.github_language,
9213                &winner.worktree,
9214            ) {
9215                Ok(spec) => spec,
9216                Err(e) => {
9217                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9218                    continue;
9219                }
9220            };
9221            let job = SeatJob {
9222                spec: github_spec,
9223                seat,
9224                cwd: winner.worktree.clone(),
9225                prompt: prompt.clone(),
9226                timeout,
9227                allow_write: false,
9228                sessions,
9229                artifacts: agent::artifacts_dir(&self.state.dir()),
9230                stem: if i == 0 {
9231                    "change-summary".to_owned()
9232                } else {
9233                    format!("change-summary-{}", spec.id)
9234                },
9235                handover: None,
9236            };
9237            let ctx = WaveCtx {
9238                run: &run,
9239                node: "pr-summary",
9240                prompts: &prompts,
9241                cache: cache.as_deref(),
9242                round: None,
9243                carry_seats: false,
9244                pauses: Some((&self.pause, &self.interrupt)),
9245            };
9246            let (seat, outcome) =
9247                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9248            self.state.seats.insert(seat.key.clone(), seat);
9249            let text = match outcome {
9250                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9251                AgentOutcome::ResourceBlocked(why) => {
9252                    // No agent was asked: the run stops resumably before
9253                    // anything is published (see `guarded_pr_message`).
9254                    if self.state.resource_block.is_none() {
9255                        self.state.resource_block = Some(crate::run::ResourceBlock {
9256                            cause: crate::run::ResourceBlockCause::Other,
9257                            node: "pr-summary".to_owned(),
9258                            kind: "shared resource".to_owned(),
9259                            detail: why,
9260                            at: Timestamp::now(),
9261                        });
9262                    }
9263                    return Err("a shared resource was busy".to_owned());
9264                }
9265                _ => continue,
9266            };
9267            let blind = &self.state.config.blind;
9268            let Some(title) = summary_title(&text) else {
9269                continue;
9270            };
9271            let body: String = summary_without_title(&text)
9272                .lines()
9273                .filter(|l| !l.contains("magi:run/"))
9274                .collect::<Vec<_>>()
9275                .join("\n");
9276            let body = blind::sanitize_prose(body.trim(), blind);
9277            let title = blind::sanitize_prose(&title, blind);
9278            if body.trim().is_empty() || title.trim().is_empty() {
9279                continue;
9280            }
9281            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9282                continue;
9283            }
9284            // The branch must still be the one the agent was shown.
9285            if git::rev_parse(&winner.worktree, "HEAD")
9286                .await
9287                .ok()
9288                .as_deref()
9289                != Some(head)
9290            {
9291                return Err("the branch moved while the summary was written".to_owned());
9292            }
9293            if git::merge_base(&winner.worktree, &tracking, head)
9294                .await
9295                .ok()
9296                .as_deref()
9297                != Some(base.as_str())
9298                || crate::pr_outcome::summary_evidence(
9299                    &self.state,
9300                    crate::pr_outcome::FinalHead::At(head),
9301                ) != evidence
9302            {
9303                return Err("the summary evidence changed while it was written".to_owned());
9304            }
9305            self.state.change_summary = Some(crate::run::ChangeSummary {
9306                head: head.to_owned(),
9307                base,
9308                evidence: fingerprint,
9309                title,
9310                body,
9311            });
9312            self.state.event(
9313                "pr-summary",
9314                format!("change summary written by {} for the final diff", spec.id),
9315            );
9316            if let Err(e) = self.state.save() {
9317                tracing::warn!("could not save the change summary: {e:#}");
9318            }
9319            return Ok(());
9320        }
9321        self.state
9322            .event("pr-summary", "no agent produced a change summary");
9323        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9324    }
9325
9326    /// One read-only rewrite request for a withheld description. The
9327    /// implementer's own conversation is tried first when it exists and can be
9328    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9329    /// writes it in a separate conversation, skipping the implementer's agent.
9330    /// The prompt carries the whole text, so no agent needs any memory. Each
9331    /// agent is asked at most once and the chain advances on an error, quota,
9332    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9333    /// that has run out of quota must not end the rewrite. Nothing is recorded
9334    /// as a handover.
9335    async fn rewrite_pr_text(
9336        &mut self,
9337        winner: &Candidate,
9338        pr: &PrMessage,
9339        violations: &[crate::github_text::Violation],
9340    ) -> Option<String> {
9341        let prompt = format!(
9342            "Rewrite only the following pull request description into English. The posting gate reported {violations:?}. Keep every substantive detail (file names, commands, numbers, findings, code blocks and <details> sections) and translate the prose. Remove all machine or operator identifying data and secrets. Do not edit files or run commands. Return TITLE: followed by the title, then the rewritten description. Include an explanation of every open or declined finding with its exact ID. Omit the generated Review rounds, Final verification and Open review findings sections, the Evidence line and run markers: magi appends those from its records.\n\nTITLE: {}\n{}",
9343            pr.title, pr.body
9344        );
9345        let sessions = self.state.config.graph.sessions;
9346        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9347        // (spec, the resumed implementer's seat). A fallback seat is created
9348        // only when its turn comes, so an unused fallback leaves no record.
9349        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9350        let key = format!("impl-{}", winner.label);
9351        if let Some(spec) = self
9352            .state
9353            .config
9354            .agents
9355            .iter()
9356            .find(|a| a.id == winner.agent)
9357            .cloned()
9358            && let Some(existing) = self.state.seats.get(&key)
9359            && existing.agent == spec.id
9360            && agent::has_session(spec.kind, existing, sessions)
9361        {
9362            attempts.push((spec, Some(existing.clone())));
9363        }
9364        match agent::pick_chain(
9365            &self.state.config.agents,
9366            self.state.config.roles.language_judge.as_ref(),
9367            &agent::installed,
9368            "language_judge",
9369        ) {
9370            Ok(chain) => {
9371                for spec in chain {
9372                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9373                        continue;
9374                    }
9375                    attempts.push((spec, None));
9376                }
9377            }
9378            Err(e) if attempts.is_empty() => {
9379                tracing::warn!("no agent for the description rewrite: {e:#}");
9380                self.state
9381                    .event("github-text", "no rewrite agent available");
9382                return None;
9383            }
9384            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9385        }
9386        let prompts = self.state.config.prompts.clone();
9387        let cache = self.state.config.cache_dir();
9388        let run = self.state.id.clone();
9389        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9390            let resumed = resumed_seat.is_some();
9391            let seat = resumed_seat.unwrap_or_else(|| {
9392                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9393            });
9394            let github_spec = match agent::for_github_text(
9395                &spec,
9396                &self.state.config.graph.github_language,
9397                &winner.worktree,
9398            ) {
9399                Ok(spec) => spec,
9400                Err(e) => {
9401                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9402                    continue;
9403                }
9404            };
9405            let job = SeatJob {
9406                spec: github_spec,
9407                seat,
9408                cwd: winner.worktree.clone(),
9409                prompt: prompt.clone(),
9410                timeout: retry_budget(timeout_full, resumed),
9411                allow_write: false,
9412                sessions,
9413                artifacts: agent::artifacts_dir(&self.state.dir()),
9414                stem: if i == 0 {
9415                    "github-text-rewrite".to_owned()
9416                } else {
9417                    format!("github-text-rewrite-{}", spec.id)
9418                },
9419                handover: None,
9420            };
9421            let ctx = WaveCtx {
9422                run: &run,
9423                node: "github-text",
9424                prompts: &prompts,
9425                cache: cache.as_deref(),
9426                round: None,
9427                carry_seats: false,
9428                pauses: Some((&self.pause, &self.interrupt)),
9429            };
9430            let (seat, outcome) =
9431                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9432            self.state.seats.insert(seat.key.clone(), seat);
9433            match outcome {
9434                AgentOutcome::Ok(o)
9435                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9436                {
9437                    return Some(o.text);
9438                }
9439                AgentOutcome::ResourceBlocked(_) => return None,
9440                _ => {}
9441            }
9442        }
9443        None
9444    }
9445
9446    /// Abandon the standing posting-gate question, if any.
9447    fn retire_github_text_question(&mut self, why: &str) {
9448        let Some(id) = self
9449            .state
9450            .github_text
9451            .as_ref()
9452            .and_then(|g| g.question.clone())
9453        else {
9454            return;
9455        };
9456        let _ = ask::Questions::open().update(&id, |q| {
9457            q.abandon(why);
9458            Ok(())
9459        });
9460    }
9461
9462    /// Carry a withheld text to its end: file the question, park while it is
9463    /// open, and on an answer, silence or timeout pick the text to post. The
9464    /// decision is saved before it is used, so it applies once.
9465    async fn settle_withheld(
9466        &mut self,
9467        winner: &Candidate,
9468        pr: &PrMessage,
9469        mut g: crate::run::GithubTextAsk,
9470    ) -> Result<Option<PrMessage>> {
9471        use crate::github_text as gt;
9472        let store = ask::Questions::open();
9473        let timeout = self.state.config.graph.answer_timeout;
9474        if !g.resolved {
9475            let mut standing = g
9476                .question
9477                .as_ref()
9478                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9479            if let Some(q) = standing.as_ref()
9480                && q.status.open()
9481                && !store.held_reply(&q.id)
9482                && gt::expired(q, timeout)
9483            {
9484                let why = format!("no answer within {}s of asking", timeout.max(1));
9485                standing = store
9486                    .update(&q.id, |q| {
9487                        q.abandon(&why);
9488                        Ok(())
9489                    })
9490                    .ok()
9491                    .map(|(q, ())| q);
9492            }
9493            let mut ask_again: Option<Option<Vec<String>>> = None;
9494            match standing {
9495                // Recorded but never written (a stop between the two saves),
9496                // or removed: ask again without spending the retry.
9497                None if g.asks <= 1 => {
9498                    g.asks = 0;
9499                    ask_again = Some(None);
9500                }
9501                None => {
9502                    g.resolved = true;
9503                    g.chosen_title = None;
9504                    g.choice = Some(GithubTextChoice::Fallback);
9505                }
9506                Some(q) if q.status.open() => {
9507                    self.park_on_github_text(&g)?;
9508                    return Ok(None);
9509                }
9510                Some(q) => match gt::read_reply(&q) {
9511                    gt::Reply::Fallback => {
9512                        g.resolved = true;
9513                        g.chosen_title = None;
9514                        g.choice = Some(GithubTextChoice::Fallback);
9515                    }
9516                    gt::Reply::Original => {
9517                        g.resolved = true;
9518                        g.chosen_title = None;
9519                        g.choice = Some(GithubTextChoice::Original);
9520                    }
9521                    gt::Reply::Rewrite => {
9522                        g.resolved = true;
9523                        g.chosen_title = None;
9524                        g.choice = Some(if g.rewrite.is_some() {
9525                            GithubTextChoice::Rewrite
9526                        } else {
9527                            GithubTextChoice::Fallback
9528                        });
9529                    }
9530                    gt::Reply::Title(text) => {
9531                        let first = text
9532                            .lines()
9533                            .map(str::trim)
9534                            .find(|l| !l.is_empty())
9535                            .unwrap_or("");
9536                        let decision = if first.is_empty() {
9537                            None
9538                        } else {
9539                            let candidate = PrMessage {
9540                                title: first.to_owned(),
9541                                body: String::new(),
9542                            };
9543                            self.judge_pr_language(&winner.worktree, &candidate).await
9544                        };
9545                        match gt::vet_title(
9546                            &text,
9547                            decision,
9548                            self.state.config.graph.github_english(),
9549                        ) {
9550                            Ok(title) => {
9551                                g.resolved = true;
9552                                g.chosen_title = Some(title);
9553                                g.choice = Some(GithubTextChoice::MyTitle);
9554                            }
9555                            Err(cats) if g.asks < 2 => {
9556                                ask_again = Some(Some(
9557                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9558                                ))
9559                            }
9560                            Err(_) => {
9561                                g.resolved = true;
9562                                g.chosen_title = None;
9563                                g.choice = Some(GithubTextChoice::Fallback);
9564                            }
9565                        }
9566                    }
9567                },
9568            }
9569            if let Some(rejected) = ask_again {
9570                // A retry (after a rejected replacement title) is still about
9571                // the original text: the same ORIGINAL / FALLBACK comparison.
9572                let w = gt::Withheld {
9573                    title: g.title,
9574                    body: g.body,
9575                    categories: g.categories.clone(),
9576                };
9577                // Named by the original text's fingerprint alone, so a resume
9578                // rewrites the same file and the detail stays identical.
9579                let artifact = match crate::run::write_artifact(
9580                    &self.state,
9581                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9582                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9583                ) {
9584                    Ok(p) => Some(p),
9585                    Err(e) => {
9586                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9587                        None
9588                    }
9589                };
9590                let (detail, comparison) = gt::question_content(
9591                    &w,
9592                    &pr.title,
9593                    &pr.body,
9594                    &self.state.id,
9595                    rejected.as_deref(),
9596                    artifact.as_deref(),
9597                    g.rewrite.as_ref(),
9598                );
9599                let mut q = ask::Question::new(
9600                    self.state.id.clone(),
9601                    gt::ASK_NODE.to_owned(),
9602                    gt::ASK_SEAT.to_owned(),
9603                    gt::question_summary(&self.state.config.graph.language, &w),
9604                    detail,
9605                    gt::question_choices(&w, g.rewrite.as_ref()),
9606                );
9607                q.posting_comparison = Some(comparison);
9608                q.answer_timeout = timeout;
9609                // Recorded before it is written: a stop in between leaves a
9610                // record naming a question the resume then files again.
9611                g.question = Some(q.id.clone());
9612                g.asks += 1;
9613                self.state.github_text = Some(g.clone());
9614                self.state.event(
9615                    "github-text",
9616                    format!("asking the owner about the withheld text ({})", q.short()),
9617                );
9618                self.state.save()?;
9619                store
9620                    .put_executable(&mut q)
9621                    .context("file the posting-gate question")?;
9622                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9623                    tracing::warn!(
9624                        "could not notify about posting-gate question {}: {e:#}",
9625                        q.short()
9626                    );
9627                }
9628                self.park_on_github_text(&g)?;
9629                return Ok(None);
9630            }
9631        }
9632        let resolved = g.chosen_title.clone();
9633        let original = g.choice == Some(GithubTextChoice::Original);
9634        // Field names only: the event log never records the text.
9635        self.state.event(
9636            "github-text",
9637            if original {
9638                format!(
9639                    "posting the original text for: {}",
9640                    match (g.title, g.body) {
9641                        (true, true) => "title, description",
9642                        (true, false) => "title",
9643                        _ => "description",
9644                    }
9645                )
9646            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9647                "posting the saved rewrite title and description".to_owned()
9648            } else if resolved.is_some() {
9649                "posting the owner's replacement title".to_owned()
9650            } else {
9651                "posting the neutral text for the withheld fields".to_owned()
9652            },
9653        );
9654        self.state.github_text = Some(g.clone());
9655        self.state.save()?;
9656        if g.choice == Some(GithubTextChoice::Rewrite)
9657            && let Some(r) = g.rewrite.as_ref()
9658        {
9659            return Ok(Some(PrMessage {
9660                title: r.title.clone(),
9661                body: r.body.clone(),
9662            }));
9663        }
9664        let w = gt::Withheld {
9665            title: g.title,
9666            body: g.body,
9667            categories: g.categories.clone(),
9668        };
9669        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9670        if let Some(t) = resolved {
9671            title = t;
9672        }
9673        // Every withheld field is now neutral or vetted English.
9674        let english = gt::LanguageDecision {
9675            title_english: true,
9676            body_english: true,
9677            body_complete: true,
9678        };
9679        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9680        if original {
9681            // The owner's explicit choice overrides the gate for the fields it
9682            // was made for; the others keep what the gate produced.
9683            if g.title {
9684                title = pr.title.clone();
9685            }
9686            if g.body {
9687                body = pr.body.clone();
9688            }
9689        }
9690        Ok(Some(PrMessage { title, body }))
9691    }
9692
9693    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9694        self.state.github_text = Some(g.clone());
9695        self.state.end_pass_parked(ParkCause::Question);
9696        self.state.parked = true;
9697        self.state.event(
9698            "github-text",
9699            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9700        );
9701        self.state.save()
9702    }
9703
9704    /// Ask `[roles] language_judge` about this text and record which source
9705    /// decided; the text itself is never recorded.
9706    async fn judge_pr_language(
9707        &mut self,
9708        cwd: &Path,
9709        pr: &PrMessage,
9710    ) -> Option<crate::github_text::LanguageDecision> {
9711        self.state.config.roles.language_judge.as_ref()?;
9712        if !self.state.config.graph.language_gate() {
9713            return None;
9714        }
9715        let decision =
9716            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9717        self.state.event(
9718            "github-text",
9719            if decision.is_some() {
9720                "language decided by the language judge"
9721            } else {
9722                "language judge unavailable; using built-in heuristics"
9723            },
9724        );
9725        decision
9726    }
9727
9728    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9729        Box::pin(self.merge_inner())
9730    }
9731
9732    async fn merge_inner(&mut self) -> Result<()> {
9733        if self.resource_halt()? || self.hold_base_sync().await? {
9734            return Ok(());
9735        }
9736        // Same reasoning as `gate`: ask the review and gate records directly
9737        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9738        // skip can rewrite on reentry to something that no longer says
9739        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9740        // so a hand-off (open findings, green verification) reaches merge
9741        // exactly like a genuinely clean round does.
9742        //
9743        // A run resumed mid-`land` never reaches here at all: `execute`
9744        // recognises `RunStatus::Landing` before it even calls `prep`, and
9745        // routes straight to `run_land` instead. That has to happen a level
9746        // up from this function, not with a check in here, because
9747        // `review_loop`'s own status recomputation (see its doc) runs
9748        // *before* `merge` on every reentry and would otherwise overwrite
9749        // the `Landing` marker with `Gating` before this node ever saw it.
9750        if self
9751            .state
9752            .base_sync
9753            .as_ref()
9754            .is_some_and(|s| s.conflict.is_some())
9755            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9756                != Some(RunStatus::Gating)
9757            // `gate_ran == false` is not "passed" - `gate` leaves it false
9758            // both before it has ever run and when its last attempt was
9759            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9760            // permission to merge on nothing but the review record. Only a
9761            // gate that actually ran may proceed; an intentional local
9762            // review can also finish with verification explicitly not configured.
9763            // `RunState::gate_status` computes that distinction.
9764            || !self.state.gate_allows_progress()
9765        {
9766            return Ok(());
9767        }
9768        // This node's own record, not `status`: `status == Ready` is not
9769        // unique to the harmless `MergeMode::None` path this line was
9770        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9771        // run's PR was closed without merging — and on that run `mode` is
9772        // still `Pr`, so a reentry that fell through here would push and
9773        // open a second pull request. `self.state.merge` is set exactly once
9774        // this node (or `land`) has already produced a verdict, under every
9775        // mode, which is what "already done" actually means here.
9776        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9777            return Ok(());
9778        }
9779        let Some(winner) = self.state.winner().cloned() else {
9780            return Ok(());
9781        };
9782        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9783        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9784            self.state.status = RunStatus::Blocked;
9785            self.state.event(
9786                "gate",
9787                "winner changed after gate; fresh verification required",
9788            );
9789            self.state.save()?;
9790            return Ok(());
9791        }
9792        let wait = self.repository_wait();
9793        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9794            return Ok(());
9795        }
9796        let repo = self.state.repo.clone();
9797        let base = self.state.base_branch.clone();
9798        let mode = self.state.config.merge.mode;
9799        let style = self.state.config.merge.style;
9800        let facts = if is_review_run(&self.state) {
9801            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9802            let start = review_base(
9803                &repo,
9804                &self.state.config.merge.remote,
9805                &base,
9806                &self.state.base_commit,
9807                &winner.branch,
9808            )
9809            .await;
9810            branch_facts(&repo, &start, &winner.branch).await
9811        } else {
9812            None
9813        };
9814        // `None` when the base could not be freshly read: then an adopted
9815        // pull request's title is left alone.
9816        let leaked = if is_review_run(&self.state) {
9817            leaked_subjects(&self.state, &winner.branch).await
9818        } else {
9819            Some(Vec::new())
9820        };
9821        // `None`: parked on the owner's word about a withheld title or body.
9822        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9823        // the resume arrives here again.
9824        let Some(pr) = self
9825            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9826            .await?
9827        else {
9828            return Ok(());
9829        };
9830        let message = pr.commit_message();
9831
9832        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9833        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9834            return Ok(());
9835        }
9836        let outcome = match mode {
9837            MergeMode::None => MergeOutcome {
9838                mode,
9839                ok: true,
9840                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9841                empty: false,
9842            },
9843            MergeMode::Pr | MergeMode::Local
9844                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9845            {
9846                MergeOutcome {
9847                    mode,
9848                    ok: false,
9849                    detail: empty_candidate_detail(&self.state, &base),
9850                    empty: true,
9851                }
9852            }
9853            MergeMode::Local => {
9854                let on = git::current_branch(&repo).await?;
9855                if on.as_deref() != Some(base.as_str()) {
9856                    MergeOutcome {
9857                        mode,
9858                        ok: false,
9859                        detail: format!(
9860                            "{} has {} checked out, not the base branch {base}",
9861                            repo.display(),
9862                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
9863                        ),
9864                        empty: false,
9865                    }
9866                } else if !git::is_clean(&repo).await? {
9867                    MergeOutcome {
9868                        mode,
9869                        ok: false,
9870                        detail: format!("{} is dirty; refusing to merge", repo.display()),
9871                        empty: false,
9872                    }
9873                } else {
9874                    let out = match style {
9875                        MergeStyle::Merge => {
9876                            git::merge_no_ff(&repo, &winner.branch, &message).await?
9877                        }
9878                        MergeStyle::Squash => {
9879                            git::merge_squash(&repo, &winner.branch, &message).await?
9880                        }
9881                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
9882                    };
9883                    MergeOutcome {
9884                        mode,
9885                        ok: out.ok(),
9886                        detail: if out.ok() { out.stdout } else { out.stderr },
9887                        empty: false,
9888                    }
9889                }
9890            }
9891            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
9892                self.state.pr_publication_pending = true;
9893                self.state.save()?;
9894                let out =
9895                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
9896                self.state.pr_publication_pending = out.is_err();
9897                MergeOutcome {
9898                    mode,
9899                    ok: out.is_ok(),
9900                    detail: match out {
9901                        Ok(url) => url,
9902                        Err(e) => format!("{e:#}"),
9903                    },
9904                    empty: false,
9905                }
9906            }
9907            MergeMode::Pr => {
9908                let remote = self.state.config.merge.remote.clone();
9909                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
9910                let pushed = if self.state.foreign_checkout.is_some() {
9911                    let refspec = format!("{delivery_head}:refs/heads/{public}");
9912                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
9913                } else {
9914                    git::push(&winner.worktree, &remote, &winner.branch).await?
9915                };
9916                if !pushed.ok() {
9917                    MergeOutcome {
9918                        mode,
9919                        ok: false,
9920                        detail: pushed.stderr,
9921                        empty: false,
9922                    }
9923                } else {
9924                    if self.state.foreign_checkout.is_some() {
9925                        self.state.pr_pushed_head = Some(delivery_head.clone());
9926                    }
9927                    // A retry or resume of a run whose branch already has an
9928                    // open pull request adopts it rather than failing on a
9929                    // duplicate. Only this winner branch into this base:
9930                    // `branch_for` derives the name from the run id, so a
9931                    // different run's pull request never matches.
9932                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
9933                    let out = match pr_merge_plan(found) {
9934                        PrPlan::Create => {
9935                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
9936                                .await
9937                        }
9938                        PrPlan::Adopt { url, title } => {
9939                            self.state
9940                                .event("merge", format!("Pr: adopted open pull request {url}"));
9941                            if self.state.explicit_github_text_selection() {
9942                                // An explicit publication selection applies the prepared
9943                                // payload; acceptance alone is not publication proof.
9944                                land::set_pr_text_verbatim(
9945                                    &winner.worktree,
9946                                    &url,
9947                                    &pr.title,
9948                                    &pr.body,
9949                                )
9950                                .await
9951                                .map(|()| url)
9952                            } else {
9953                                if title != pr.title
9954                                    && (!is_review_run(&self.state)
9955                                        || leaked
9956                                            .as_deref()
9957                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
9958                                    && let Err(e) =
9959                                        if self.state.github_text.as_ref().is_some_and(|g| {
9960                                            g.resolved
9961                                                && g.title
9962                                                && g.choice == Some(GithubTextChoice::Original)
9963                                        }) {
9964                                            // The owner chose to post this title unmodified.
9965                                            land::set_pr_title_verbatim(
9966                                                &winner.worktree,
9967                                                &url,
9968                                                &pr.title,
9969                                            )
9970                                            .await
9971                                        } else {
9972                                            land::set_pr_title(
9973                                                &mut self.state,
9974                                                &winner.worktree,
9975                                                &url,
9976                                                &pr.title,
9977                                            )
9978                                            .await
9979                                        }
9980                                {
9981                                    tracing::warn!("could not refresh title of {url}: {e:#}");
9982                                    self.state
9983                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
9984                                }
9985                                Ok(url)
9986                            }
9987                        }
9988                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
9989                    };
9990                    match out {
9991                        Ok(url) => MergeOutcome {
9992                            mode,
9993                            ok: true,
9994                            detail: url,
9995                            empty: false,
9996                        },
9997                        Err(e) => MergeOutcome {
9998                            mode,
9999                            ok: false,
10000                            detail: e.to_string(),
10001                            empty: false,
10002                        },
10003                    }
10004                }
10005            }
10006        };
10007
10008        self.state.status = match (mode, outcome.ok) {
10009            (MergeMode::None, _) => RunStatus::Ready,
10010            (_, true) if outcome.empty => RunStatus::Ready,
10011            (MergeMode::Pr, true) => RunStatus::Ready,
10012            (_, true) => RunStatus::Merged,
10013            (_, false) => RunStatus::Blocked,
10014        };
10015        self.state.event(
10016            "merge",
10017            format!(
10018                "{:?}: {}",
10019                mode,
10020                outcome.detail.lines().next().unwrap_or("")
10021            ),
10022        );
10023        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10024            self.state.record_github_text_publication(&outcome.detail);
10025        }
10026        self.state.merge = Some(outcome);
10027        self.state.save()?;
10028
10029        // The PR is open and the run would historically stop here, leaving the
10030        // operator to watch checks, feed review comments back to a fixer, and
10031        // merge. That was done by hand six times in one session before this
10032        // existed. Opt-in, because merging is the one irreversible thing magi
10033        // can do to a repository.
10034        if self.state.config.graph.land
10035            && mode == MergeMode::Pr
10036            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10037        {
10038            self.run_land().await?;
10039        }
10040        // `run_land` may have left `status` at `Landing` - still waiting on
10041        // CI or the owner's approval, not actually settled - so this has to
10042        // read whatever `status` ended up as here, not the `Merged` this
10043        // function set a few lines up.
10044        self.settle_questions();
10045        Ok(())
10046    }
10047
10048    /// Enter `land`.
10049    ///
10050    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10051    /// a resumed run's re-entry. `land::land` itself is what serialises the
10052    /// two git-mutating moments inside the loop — the rebase push and
10053    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10054    /// to hold a lock across the whole call, and doing so would serialise
10055    /// this run's CI wait against a *different* run's land-approval resume
10056    /// in the same repository, which is exactly the "must not wait on
10057    /// another task" property the daemon's slot-freeing exists to give.
10058    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10059        Box::pin(self.run_land_inner())
10060    }
10061
10062    async fn run_land_inner(&mut self) -> Result<()> {
10063        crate::pr_head::ensure_owner(&self.state)?;
10064        let url = self
10065            .state
10066            .pr
10067            .as_ref()
10068            .map(|pr| pr.url.clone())
10069            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10070            .unwrap_or_default();
10071        let url = url.lines().next().unwrap_or("").trim().to_owned();
10072        if !url.starts_with("http") {
10073            return Ok(());
10074        }
10075        // A land failure is not a lost run: the work is on a branch and the
10076        // pull request is open, which is exactly where a human takes over.
10077        loop {
10078            match land::land(&mut self.state, &url).await {
10079                Ok(_)
10080                    if self
10081                        .state
10082                        .merge_repairs
10083                        .last()
10084                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10085                {
10086                    if self.repair_merge_review().await? {
10087                        continue;
10088                    }
10089                }
10090                Ok(_) if self.state.resource_block.is_some() => {
10091                    return self.stop_for_resource();
10092                }
10093                Ok(pr) if self.state.parked => {
10094                    // `land` already saved the parked marker; nothing here
10095                    // overrides `status` back to a terminal value while an
10096                    // approval is still outstanding.
10097                    let _ = pr;
10098                }
10099                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10100                    self.state.status = RunStatus::Superseded;
10101                    self.state.save()?;
10102                }
10103                Ok(pr) => {
10104                    self.state.status = match pr.state {
10105                        land::PrLifecycle::Merged => RunStatus::Merged,
10106                        _ => RunStatus::Blocked,
10107                    };
10108                    // Downstream of a confirmed merge only - see
10109                    // `bump::should_release_bump`'s own doc for why this one
10110                    // check covers all three of `land`'s success paths.
10111                    // Best-effort: the run already landed, so a failure here
10112                    // (the decision call, `gh`, `cargo`) is recorded and never
10113                    // turns a landed run into a failed one.
10114                    if bump::should_release_bump(self.state.status)
10115                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10116                    {
10117                        // The event is the run's own record. Not-eligible cases
10118                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10119                        // `Err` is a bump that was tried and failed:
10120                        // `after_merge` itself raises the operator notice for
10121                        // that, whether or not a release PR exists yet.
10122                        self.state
10123                            .event("bump", format!("release bump skipped: {e:#}"));
10124                    }
10125                    // Independent of the bump, and best-effort in the same way:
10126                    // findings the merge left open become follow-up tasks.
10127                    if self.state.status == RunStatus::Merged {
10128                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10129                    }
10130                    self.state.save()?;
10131                }
10132                Err(e) => {
10133                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10134                        return Err(e);
10135                    }
10136                    self.state.status = RunStatus::Blocked;
10137                    self.state.event("land", format!("gave up: {e}"));
10138                    self.state.save()?;
10139                }
10140            }
10141            break;
10142        }
10143        Ok(())
10144    }
10145
10146    /// One repair cycle stays under the existing driver/task claim. An
10147    /// interrupted fixer is rolled back and held rather than run twice.
10148    async fn repair_merge_review(&mut self) -> Result<bool> {
10149        use crate::run::MergeRepairPhase as Phase;
10150        crate::pr_head::ensure_owner(&self.state)?;
10151        let i = self.state.merge_repairs.len() - 1;
10152        let request = self.state.merge_repairs[i].clone();
10153        if request.phase == Phase::Fixing {
10154            let restored = match self.state.winner().cloned() {
10155                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10156                None => Err(anyhow::anyhow!("repair has no winning branch")),
10157            };
10158            let why = match restored {
10159                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10160                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10161                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10162            };
10163            self.hold_merge_repair(i, why)?;
10164            return Ok(false);
10165        }
10166        // A completed repair gate is a publication checkpoint. On reentry,
10167        // reject external changes before the ordinary gate path can replace
10168        // that evidence by verifying a new head. Requested repairs still
10169        // start their own review generation below.
10170        if request.phase == Phase::Reviewing && self.state.gate_ran {
10171            let winner = self
10172                .state
10173                .winner()
10174                .context("repair has no winning branch")?;
10175            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10176            if self.state.gate_head.as_deref() != Some(head.as_str())
10177                || !git::is_clean(&winner.worktree).await?
10178            {
10179                self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10180                return Ok(false);
10181            }
10182        }
10183        let failure = if i >= self.state.config.graph.land_rounds
10184            || self.state.config.graph.review_rounds == 0
10185        {
10186            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10187        } else {
10188            None
10189        };
10190        if let Some(why) = failure {
10191            self.hold_merge_repair(i, why)?;
10192            return Ok(false);
10193        }
10194        if request.phase == Phase::Requested {
10195            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10196                Ok(pr) => pr,
10197                Err(e) => {
10198                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10199                    return Ok(false);
10200                }
10201            };
10202            self.state.merge_repairs[i].phase = Phase::Fixing;
10203            self.state.land_approval = None;
10204            self.state.land_armed_head = None;
10205            self.state.save()?;
10206            // Serialize the exact records, including finding ids/details,
10207            // reconsideration reasons, final votes and verification output.
10208            let evidence = serde_json::to_string_pretty(&request)?;
10209            let reason = format!(
10210                "The owner requested fix findings and re-review, without merging. Address the unresolved Major findings and final rejecting votes in this exact review evidence. Do not merge or approve the PR.\n\n{evidence}"
10211            );
10212            let budget = self.state.config.graph.land_rounds;
10213            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10214            match result {
10215                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10216                Ok(land::Fixed::Deferred) => {
10217                    // An unavailable fixer did not spend this repair request.
10218                    // Restore partial fallback work before retrying it, as for
10219                    // an interrupted repair, without closing the request.
10220                    let worktree = self
10221                        .state
10222                        .winner()
10223                        .context("repair has no winning branch")?
10224                        .worktree
10225                        .clone();
10226                    self.graft_restore(&worktree, &request.head).await?;
10227                    self.state.merge_repairs[i].phase = Phase::Requested;
10228                    self.stop_for_resource()?;
10229                    return Ok(false);
10230                }
10231                Ok(land::Fixed::Failed(why)) => {
10232                    self.hold_merge_repair(
10233                        i,
10234                        format!(
10235                            "repair failed: {why}; inspect the branch and run an explicit review"
10236                        ),
10237                    )?;
10238                    return Ok(false);
10239                }
10240                Err(e) => {
10241                    self.hold_merge_repair(
10242                        i,
10243                        format!(
10244                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10245                        ),
10246                    )?;
10247                    return Ok(false);
10248                }
10249            }
10250            // Even no change gets a real new reviewer wave. The previous
10251            // evidence remains in the request; a former clean/concluded round
10252            // cannot short-circuit the new review or gate.
10253            self.begin_merge_repair_review(i)?;
10254        }
10255        self.review_loop().await?;
10256        self.gate().await?;
10257        if self.resource_halt()? || self.state.parked {
10258            return Ok(false);
10259        }
10260        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10261            != Some(RunStatus::Gating)
10262            || !self.state.gate_allows_progress()
10263        {
10264            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10265            return Ok(false);
10266        }
10267        // Review and gate may have added commits after the initial repair.
10268        // Publish exactly their final head to the existing PR, with a lease.
10269        let winner = self
10270            .state
10271            .winner()
10272            .cloned()
10273            .context("repair has no winning branch")?;
10274        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10275        if self.state.gate_head.as_deref() != Some(after.as_str())
10276            || !git::is_clean(&winner.worktree).await?
10277        {
10278            self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10279            return Ok(false);
10280        }
10281        let expected = self
10282            .state
10283            .pr_pushed_head
10284            .as_deref()
10285            .unwrap_or(&request.head)
10286            .to_owned();
10287        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10288        // Push the checked commit itself: a local ref moving after the check
10289        // must not change which commit the forge receives.
10290        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10291            return Ok(false);
10292        }
10293        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10294        let refspec = format!("{after}:refs/heads/{public}");
10295        let push = git::git_raw(
10296            &winner.worktree,
10297            &["push", &lease, &self.state.config.merge.remote, &refspec],
10298        )
10299        .await;
10300        match push {
10301            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10302            Ok(out) => {
10303                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10304                return Ok(false);
10305            }
10306            Err(e) => {
10307                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10308                return Ok(false);
10309            }
10310        }
10311        self.state.merge_repairs[i].phase = Phase::Complete;
10312        self.state.status = RunStatus::Landing;
10313        self.state.event(
10314            "repair",
10315            "new review and gate completed; fresh owner merge decision required",
10316        );
10317        self.state.save()?;
10318        Ok(true)
10319    }
10320
10321    fn merge_repair_artifacts(&self) -> PathBuf {
10322        let artifacts = agent::artifacts_dir(&self.state.dir());
10323        match self
10324            .state
10325            .merge_repairs
10326            .last()
10327            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10328        {
10329            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10330            None => artifacts,
10331        }
10332    }
10333
10334    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10335        if let Some(e2e) = self.state.head_e2e.take() {
10336            self.state
10337                .verification_history
10338                .push(crate::run::VerificationEvidence {
10339                    superseded_by: None,
10340                    archived_at: Some(Timestamp::now()),
10341                    fixes_spent: Some(self.state.gate_fixes.len()),
10342                    gate_head: None,
10343                    gate_ran: false,
10344                    gate: Vec::new(),
10345                    e2e: Some(e2e),
10346                });
10347        }
10348        self.state.reviews.clear();
10349        self.state.gate.clear();
10350        self.state.gate_ran = false;
10351        self.state.gate_head = None;
10352        self.state.gate_fixes.clear();
10353        self.state.gate_repair_e2e = None;
10354        self.state.pre_gate.clear();
10355        self.state.pre_gate_commit = None;
10356        self.state.contested_handoff = None;
10357        self.state.land_reruns = None;
10358        self.state.land_approval = None;
10359        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10360        self.state.status = RunStatus::Reviewing;
10361        self.state.save()
10362    }
10363
10364    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10365        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10366        self.state.merge_repairs[index].failure = Some(why.clone());
10367        self.state.status = RunStatus::Blocked;
10368        self.state.event("repair", why);
10369        self.state.save()
10370    }
10371
10372    // -------------------------------------------------------------- helpers
10373
10374    /// Fetch or create a seat, keeping its conversation across nodes.
10375    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10376        if let Some(existing) = self.state.seats.get(key)
10377            && existing.agent == agent
10378        {
10379            return existing.clone();
10380        }
10381        // A seat that changes agent mints its session id from the agent too,
10382        // like a handover: the old agent's uuid is already taken by the CLI.
10383        let fresh = if self.state.seats.contains_key(key) {
10384            handover_seat(key, agent, self.state.next_seat_seed())
10385        } else {
10386            SeatState::new(key, agent, self.state.seed)
10387        };
10388        self.state.seats.insert(key.to_owned(), fresh.clone());
10389        fresh
10390    }
10391
10392    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10393    /// seat to another roster agent, in which case that agent. Nodes that
10394    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10395    /// reconsideration) must keep talking to whoever answered it, not slip
10396    /// back to the agent that failed it.
10397    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10398        match self.state.seats.get(key) {
10399            Some(s) if s.agent != spec.id => {
10400                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10401            }
10402            _ => spec,
10403        }
10404    }
10405
10406    /// A candidate rendered for judging, with the leak policy applied.
10407    fn view(&self, c: &Candidate) -> CandidateView {
10408        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10409            .unwrap_or_default();
10410        let (patch, _) = blind::sanitize_patch(
10411            &format!("candidate {} patch", c.label),
10412            &raw,
10413            &self.state.config.blind,
10414        );
10415        CandidateView {
10416            label: c.label,
10417            branch: c.branch.clone(),
10418            summary: c.summary.clone(),
10419            stat: c.stat.clone(),
10420            patch,
10421        }
10422    }
10423
10424    /// The full candidate set as prompt text, for seats with no live session.
10425    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10426        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10427        prompt::judge(
10428            "(see above)",
10429            &views,
10430            self.roles.judges.len(),
10431            base_short,
10432            "en",
10433        )
10434    }
10435
10436    /// The final-vote prompt with everything a seat that has no session of its
10437    /// own needs: the candidates, the seat's own ranking and reasons, and the
10438    /// anonymised deliberation it took part in (only when there was one, so a
10439    /// handed-over seat never sees more than the seat it replaces did). The
10440    /// `Final vote` heading stays first.
10441    fn vote_prompt_full(
10442        &self,
10443        j: usize,
10444        labels: &[char],
10445        language: &str,
10446        candidates: &[Candidate],
10447        base_short: &str,
10448    ) -> String {
10449        let mut text = format!(
10450            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10451            prompt::final_vote(labels, language),
10452            self.state.instruction,
10453            self.candidate_block(candidates, base_short)
10454        );
10455        if let Some(own) = self
10456            .state
10457            .judgements
10458            .get(j)
10459            .filter(|r| !r.ranking.is_empty())
10460        {
10461            let reasons = own
10462                .reasons
10463                .iter()
10464                .map(|(k, v)| format!("- {k}: {v}"))
10465                .collect::<Vec<_>>()
10466                .join("\n");
10467            text.push_str(&format!(
10468                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10469                own.ranking.iter().collect::<String>(),
10470                if reasons.is_empty() {
10471                    ""
10472                } else {
10473                    ", because:\n"
10474                }
10475            ));
10476        }
10477        if !self.state.deliberation.is_empty() {
10478            text.push_str("\n# What was argued before this vote\n");
10479            for t in self.transcript(&[], j) {
10480                text.push_str(&format!(
10481                    "\n## {}{}\n\n{}\n",
10482                    t.who,
10483                    if t.is_self { " (you)" } else { "" },
10484                    t.body.trim()
10485                ));
10486            }
10487        }
10488        text
10489    }
10490
10491    /// Anonymised transcript for judge `self_idx`.
10492    ///
10493    /// The initial rankings are always the opening statements. Seeding them
10494    /// only when no turn had been taken yet meant every judge after the first
10495    /// argued against a single voice instead of against the actual split — the
10496    /// disagreement is the information, so it is always on the table.
10497    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10498        let mut turns = Vec::new();
10499        for j in &self.state.judgements {
10500            if j.ranking.is_empty() {
10501                continue;
10502            }
10503            let reasons = j
10504                .reasons
10505                .iter()
10506                .map(|(k, v)| format!("- {k}: {v}"))
10507                .collect::<Vec<_>>()
10508                .join("\n");
10509            turns.push(Turn {
10510                who: format!("Judge {} (opening ranking)", j.judge),
10511                is_self: j.judge == self_idx + 1,
10512                body: format!(
10513                    "Ranked {}{}{reasons}",
10514                    j.ranking.iter().collect::<String>(),
10515                    if reasons.is_empty() {
10516                        ""
10517                    } else {
10518                        ", because:\n"
10519                    }
10520                ),
10521            });
10522        }
10523        for t in self
10524            .state
10525            .deliberation
10526            .iter()
10527            .flat_map(|r| r.turns.iter())
10528            .chain(current)
10529        {
10530            turns.push(Turn {
10531                who: format!("Judge {}", t.judge),
10532                is_self: t.judge == self_idx + 1,
10533                body: t.body.clone(),
10534            });
10535        }
10536        turns
10537    }
10538}
10539
10540/// Does this seat still hold the context a follow-up prompt would rely on?
10541fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10542    agent::has_session(spec.kind, seat, sessions)
10543}
10544
10545/// The next entry in `roster` after `start`, never wrapping back to the
10546/// front, whose id is not in `tried` yet.
10547///
10548/// Starts one past `start` rather than at the front of `roster`: `start` is
10549/// the seat's own original position, and a seat whose candidate slot already
10550/// sits on the roster's second entry must fall through to the third next, not
10551/// restart at the first — which is very likely a different candidate's own
10552/// agent already. Never wraps back past `start`, for the same reason: an
10553/// entry earlier in the roster than the seat's own position is almost
10554/// certainly some *other* candidate slot's own agent, and once the tail of
10555/// the roster is exhausted there are no more untried agents for *this* seat
10556/// to fall through to — the caller's fallback chain ends there, exactly as
10557/// "no further untried agents remain in the list for that seat" asks for.
10558///
10559/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10560/// the same id twice (an operator's `roles.implementers` typo, or a
10561/// `[[agents]]` list reused across roles) must not let
10562/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10563/// over `roster` either finds an untried id or runs out, so this always
10564/// terminates regardless of duplicates.
10565fn next_untried_in_roster<'a>(
10566    roster: &'a [AgentSpec],
10567    start: usize,
10568    tried: &BTreeSet<String>,
10569) -> Option<&'a AgentSpec> {
10570    roster
10571        .get(start + 1..)?
10572        .iter()
10573        .find(|s| !tried.contains(&s.id))
10574}
10575
10576/// The successor for a seat, shared by all four seat kinds (implement, judge,
10577/// review, advise). `others` holds the ids that *currently* occupy the other
10578/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10579/// sees them), so roster entries beyond the seat count act as spares: a failed
10580/// seat goes to an agent no other seat holds whenever the roster permits.
10581///
10582/// `carried` is `Some` only for the review loop's carried failure history.
10583/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10584/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10585/// whole roster: untried and not another seat's occupant; (3) the plain walk
10586/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10587/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10588/// a better outcome than an empty seat, and it keeps the answer to "is there
10589/// a successor at all" exactly what it was before occupants were considered,
10590/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10591/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10592/// carried failure is a cheaper bet than doubling an agent on the panel, and
10593/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10594/// the same round are handled one at a time, so a seat later in the batch
10595/// sees an earlier one's new occupant but not yet its own freed agent.
10596fn pick_successor<'a>(
10597    roster: &'a [AgentSpec],
10598    start: usize,
10599    tried: &BTreeSet<String>,
10600    carried: Option<&BTreeSet<String>>,
10601    others: &BTreeSet<String>,
10602) -> Option<&'a AgentSpec> {
10603    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10604    roster
10605        .get(start + 1..)
10606        .and_then(|tail| {
10607            tail.iter()
10608                .filter(free)
10609                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10610        })
10611        .or_else(|| {
10612            carried
10613                .is_some()
10614                .then(|| roster.iter().find(free))
10615                .flatten()
10616        })
10617        .or_else(|| match carried {
10618            Some(c) => next_for_seat(roster, start, tried, c),
10619            None => next_untried_in_roster(roster, start, tried),
10620        })
10621}
10622
10623/// The next agent for a seat that carries its failure history across rounds
10624/// (the review loop). `round_tried` is this round's own bound and starts
10625/// empty every round; `carried_failed` only decides priority.
10626///
10627/// First: an id walking forward from `start`, never wrapping, that is neither
10628/// tried this round nor failed in an earlier one. Only when that is exhausted
10629/// does it rescue: the first roster id (in roster order, so this one *does*
10630/// look before `start`) not yet tried this round, which is by then a carried
10631/// failure. Each id is rescued at most once per round, so it cannot loop.
10632fn next_for_seat<'a>(
10633    roster: &'a [AgentSpec],
10634    start: usize,
10635    round_tried: &BTreeSet<String>,
10636    carried_failed: &BTreeSet<String>,
10637) -> Option<&'a AgentSpec> {
10638    roster
10639        .get(start + 1..)?
10640        .iter()
10641        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10642        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10643}
10644
10645/// Where a reviewer seat starts a round: the agent that last answered it when
10646/// it is still on the roster and not marked failed, else the spec's own agent
10647/// unless it failed, else the next roster agent that has not failed, else the
10648/// spec's own agent again (the whole roster failed). Ids no longer on the
10649/// roster are ignored. An empty roster has no handover, so the spec stands.
10650fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10651    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10652        return spec;
10653    };
10654    let ok = |id: &str| !h.failed.contains(id);
10655    if let Some(last) = h.last_ok.as_deref()
10656        && ok(last)
10657        && let Some(s) = roster.iter().find(|s| s.id == last)
10658    {
10659        return s.clone();
10660    }
10661    if ok(&spec.id) {
10662        return spec;
10663    }
10664    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10665    roster
10666        .get(from + 1..)
10667        .into_iter()
10668        .flatten()
10669        .chain(roster.iter())
10670        .find(|s| ok(&s.id))
10671        .cloned()
10672        .unwrap_or(spec)
10673}
10674
10675/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10676/// seed so a CLI that mints its session id up front (`--session-id`) never
10677/// reuses the uuid the previous agent already opened under the same seat key.
10678pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10679    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10680}
10681
10682/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10683/// so the classifier below and the code that builds the message cannot drift.
10684const TIMED_OUT: &str = "timed out";
10685
10686impl FailClass {
10687    /// `None` for an answer; otherwise how the turn failed.
10688    fn of(out: &AgentOutcome) -> Option<Self> {
10689        match out {
10690            AgentOutcome::Ok(_) => None,
10691            AgentOutcome::Quota(_) => Some(Self::Quota),
10692            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10693            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10694            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10695            // Not a failure of the agent. Callers check for it first; `None`
10696            // here means "no class to hand over on".
10697            AgentOutcome::ResourceBlocked(_) => None,
10698        }
10699    }
10700
10701    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10702    fn stem_word(&self) -> &'static str {
10703        match self {
10704            Self::Quota => "quota",
10705            _ => "handover",
10706        }
10707    }
10708}
10709
10710/// The message's first line with its variable parts removed — digit runs and
10711/// path-like tokens — so "exit code 2" and "exit code 7" read
10712/// as one kind of failure.
10713fn failure_signature(msg: &str) -> String {
10714    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10715    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10716    // the historical machine key while the process diagnosis uses readable prose.
10717    if let Some(code) = line
10718        .strip_prefix("process exited with no usable output (exit code ")
10719        .and_then(|s| s.strip_suffix(')'))
10720        .and_then(|s| s.parse::<i32>().ok())
10721    {
10722        line = format!("exited with some({code}) and no usable output");
10723    } else if matches!(
10724        line.as_str(),
10725        "process exited with no usable output (no exit code reported)"
10726            | "process exited with no usable output (exit code unavailable)"
10727    ) {
10728        line = "exited with none and no usable output".to_owned();
10729    }
10730    let mut out = Vec::new();
10731    for word in line.split_whitespace() {
10732        if word.contains('/') || word.contains('\\') {
10733            out.push("<path>".to_owned());
10734            continue;
10735        }
10736        let mut w = String::new();
10737        let mut in_digits = false;
10738        for c in word.chars() {
10739            if c.is_ascii_digit() {
10740                if !in_digits {
10741                    w.push('#');
10742                }
10743                in_digits = true;
10744            } else {
10745                in_digits = false;
10746                w.push(c);
10747            }
10748        }
10749        out.push(w);
10750    }
10751    out.join(" ").chars().take(120).collect()
10752}
10753
10754/// Whether a seat that just failed with `cur` may go to the next roster agent.
10755/// A quota or a timeout always may. Any other failure may not when the agent
10756/// before it failed the same way: an error the prompt causes would otherwise
10757/// walk the whole roster. `prev` is the class of the immediately preceding
10758/// agent's failure, so a quota or timeout in between breaks the run of
10759/// identical failures by itself.
10760fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10761    match cur {
10762        FailClass::Quota | FailClass::Timeout => true,
10763        FailClass::Other(_) => prev != Some(cur),
10764    }
10765}
10766
10767/// A short human reason for a failed outcome, for the handover record.
10768fn fail_reason(out: &AgentOutcome) -> String {
10769    match out {
10770        AgentOutcome::Ok(_) => String::new(),
10771        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10772        AgentOutcome::Dropped(o) => format!(
10773            "the CLI dropped the stream ({})",
10774            o.dropped
10775                .as_ref()
10776                .map(|d| d.why.as_str())
10777                .unwrap_or("it ended without delivering its answer")
10778        ),
10779        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10780            e.lines().next().unwrap_or("").chars().take(160).collect()
10781        }
10782    }
10783}
10784
10785/// Note one handover in the run: the structured record and, in the timeline,
10786/// the sentence a person reads. A quota keeps the wording it always had.
10787pub(crate) fn record_handover(
10788    state: &mut RunState,
10789    node: &str,
10790    seat: &str,
10791    from: &str,
10792    to: &str,
10793    class: &FailClass,
10794    reason: &str,
10795) {
10796    let message = if *class == FailClass::Quota {
10797        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10798    } else {
10799        format!("{seat}: handed over {from} -> {to} ({reason})")
10800    };
10801    state.event(node, message);
10802    state.handovers.push(Handover {
10803        at: Timestamp::now(),
10804        node: node.to_owned(),
10805        seat: seat.to_owned(),
10806        from: from.to_owned(),
10807        to: to.to_owned(),
10808        reason: reason.to_owned(),
10809    });
10810}
10811
10812/// Did this reply report running a command whose own CLI never confirmed an
10813/// exit status?
10814///
10815/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10816/// command *finished* (see that type's own doc), so this can only be `true`
10817/// for a command whose completion event carried no readable exit code — not
10818/// for one that simply is not mentioned at all. That is the one signal this
10819/// crate can read, from the same record `state.jobs` renders, about a reply
10820/// standing next to work its own CLI cannot vouch for finishing; it is
10821/// deliberately not a check on the exit code's *value* (a fixer legitimately
10822/// runs a command that fails mid-iteration before it succeeds) and not a
10823/// guess at a command still running in the background (which emits no event
10824/// at all, and so leaves no evidence here to find).
10825fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10826    commands.iter().any(|c| c.exit_code.is_none())
10827}
10828
10829/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10830/// trusted as a verified no-op — the adoption guard's own text-level half.
10831///
10832/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10833/// timed out): a marker only earns the benefit of the doubt from a turn the
10834/// CLI itself vouches for finishing properly, the same house style
10835/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10836/// *fix* report to for `commands`. A candidate that timed out, exited
10837/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10838/// is, whatever prose it wrote — this returns `None` before it ever looks at
10839/// `text`. The remaining guards (the tree really is empty, the evidence is
10840/// non-empty) are the caller's: this only reads what the reply *claimed*.
10841fn verified_noop_claim(
10842    usable: bool,
10843    commands: &[agent::CommandEvidence],
10844    text: &str,
10845) -> Option<String> {
10846    (usable && !has_unconfirmed_command(commands))
10847        .then(|| verdict::verified_noop(text))
10848        .flatten()
10849}
10850
10851fn short(commit: &str) -> String {
10852    commit.chars().take(7).collect()
10853}
10854
10855fn make_executable(path: &Path) -> Result<()> {
10856    #[cfg(unix)]
10857    {
10858        use std::os::unix::fs::PermissionsExt as _;
10859        let mut perms = std::fs::metadata(path)?.permissions();
10860        perms.set_mode(0o755);
10861        std::fs::set_permissions(path, perms)?;
10862    }
10863    #[cfg(not(unix))]
10864    {
10865        let _ = path;
10866    }
10867    Ok(())
10868}
10869
10870/// What every seat in one batch shares: where the answers are attributed, the
10871/// prompt overlay they inherit, and the build cache they are told to use.
10872///
10873/// A struct rather than four more parameters: `wave` also needs the run's
10874/// state (to record who is answering right now) and the attempt number, and
10875/// eight positional arguments is both unreadable and a clippy error.
10876struct WaveCtx<'a> {
10877    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
10878    /// paid for it.
10879    run: &'a str,
10880    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
10881    node: &'a str,
10882    prompts: &'a Prompts,
10883    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
10884    cache: Option<&'a Path>,
10885    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
10886    /// `JobRecord::round`. `None` for every other node.
10887    round: Option<usize>,
10888    /// Carry each seat's failed-agent history across waves (the review loop
10889    /// only): start-of-round priority and handover choice read
10890    /// [`RunState::seat_history`], and every answer or failure writes it.
10891    carry_seats: bool,
10892    /// The run's park / interrupt requests, so a wait for a shared resource
10893    /// can be abandoned the moment the operator asks to park.
10894    pauses: Option<(&'a Pause, &'a Pause)>,
10895}
10896
10897/// Shared scheduling policy for operations and spawned seat invocations.
10898fn repository_wait(
10899    state: &RunState,
10900    pauses: Option<(&Pause, &Pause)>,
10901) -> crate::repo_lock::WaitPolicy {
10902    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
10903    let inherited = crate::repo_lock::WaitPolicy::current();
10904    crate::repo_lock::WaitPolicy::new(
10905        Duration::from_secs(state.config.graph.timeout_resource_wait),
10906        move || {
10907            inherited.cancelled()
10908                || pauses
10909                    .as_ref()
10910                    .is_some_and(|(a, b)| a.parked() || b.parked())
10911        },
10912    )
10913}
10914
10915fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
10916    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
10917        state.event("resource", timeout.0.description());
10918        state.resource_block = Some(timeout.0.clone());
10919        return;
10920    }
10921    if error.is::<crate::repo_lock::ResourceBlocked>() {
10922        state.resource_block = Some(crate::run::ResourceBlock {
10923            cause: crate::run::ResourceBlockCause::Other,
10924            node: "repository".into(),
10925            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
10926                "disk admission"
10927            } else if error.to_string().contains("disk pressure") {
10928                "disk pressure"
10929            } else if error.to_string().contains("disk admission") {
10930                "disk admission"
10931            } else if error.to_string().contains(crate::incremental::BLOCKED) {
10932                "incremental cache admission"
10933            } else {
10934                "repository coordination"
10935            }
10936            .into(),
10937            detail: format!("{error:#}"),
10938            at: Timestamp::now(),
10939        });
10940        state.event("resource", error.to_string());
10941    }
10942}
10943
10944async fn coordinate_operation(
10945    state: &mut RunState,
10946    cwd: &Path,
10947    wait: &crate::repo_lock::WaitPolicy,
10948) -> Result<Option<crate::repo_lock::SeatLease>> {
10949    let result =
10950        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
10951            .await;
10952    if let Err(e) = &result {
10953        record_repository_block(state, e);
10954    }
10955    result
10956}
10957
10958/// Run one job, honouring the parallelism budget.
10959async fn run_one(
10960    job: SeatJob,
10961    sem: Arc<Semaphore>,
10962    ctx: &WaveCtx<'_>,
10963    state: &mut RunState,
10964    attempt: usize,
10965) -> (SeatState, AgentOutcome) {
10966    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
10967        .await
10968        .pop()
10969        .expect("one job in, one result out");
10970    (seat, out)
10971}
10972
10973/// Run every job concurrently, capped by the semaphore, preserving order.
10974///
10975/// Every seat in the batch is recorded into [`RunState::active`] before the
10976/// wave starts and cleared as each answer lands, so the run's own record says
10977/// who is still being waited on rather than only who finished.
10978async fn wave(
10979    jobs: Vec<SeatJob>,
10980    sem: Arc<Semaphore>,
10981    ctx: &WaveCtx<'_>,
10982    state: &mut RunState,
10983    attempt: usize,
10984) -> Vec<(usize, SeatState, AgentOutcome)> {
10985    let WaveCtx {
10986        run,
10987        node,
10988        prompts,
10989        cache,
10990        round,
10991        carry_seats: _,
10992        pauses,
10993    } = *ctx;
10994    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
10995    for job in &jobs {
10996        state.seat_started(node, &job.seat.key, job.timeout, attempt);
10997    }
10998    if let Err(e) = state.save() {
10999        // A failed persist of "who is answering right now" must not abort the
11000        // wave: the seats are already being asked, and the alternative is
11001        // losing the answers to save a status line nobody may even be
11002        // watching.
11003        tracing::warn!("could not persist in-progress seats: {e:#}");
11004    }
11005    // Shared-mode waves keep their existing single lease. Isolated writers
11006    // acquire their own checkout's target at seat admission.
11007    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11008    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11009    // never borrowed from a job's agent budget (and never charged to it either,
11010    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11011    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11012    let cache_guard = if let Some(cache_dir) = cache {
11013        if jobs_had_a_writer {
11014            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11015            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11016            match acquire_cache_lease(
11017                state,
11018                cache_dir,
11019                &owner,
11020                resource_limit,
11021                node,
11022                node,
11023                &cancel,
11024            )
11025            .await
11026            {
11027                Ok(Some(g)) => Some(g),
11028                // Parking: leave without spawning anything. The run parks at
11029                // the next boundary and the seats are asked afresh on resume.
11030                Ok(None) => {
11031                    if let Some(block) = &mut state.resource_block {
11032                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11033                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11034                        };
11035                    }
11036                    return block_wave(
11037                        jobs,
11038                        state,
11039                        node,
11040                        attempt,
11041                        "parked while waiting for the shared build cache",
11042                    );
11043                }
11044                // An unreadable lease is not contention: keep the old
11045                // fallback (no shared cache for this wave's seats).
11046                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11047                Err(e) => {
11048                    // Writing seats may not build into a cache this run does
11049                    // not hold, and an agent that cannot be given one is not
11050                    // asked at all: the run stops resumably instead.
11051                    let why = format!("{e:#}");
11052                    state.event(
11053                        "resource",
11054                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11055                    );
11056                    return block_wave(jobs, state, node, attempt, &why);
11057                }
11058            }
11059        } else {
11060            None
11061        }
11062    } else {
11063        None
11064    };
11065    // Every job keeps its whole budget: the wait above was not the agent's.
11066    // Restart the seats' clocks so "started" means "being spawned now".
11067    state.seats_spawning(node, attempt);
11068    if let Err(e) = state.save() {
11069        tracing::warn!("could not persist the start of a wave: {e:#}");
11070    }
11071    // Queueing behind this wave's own seats for a parallelism slot is normal
11072    // (each of them is bounded by its own agent timeout); only a wait beyond
11073    // all of them plus the resource limit means the slots never came back.
11074    let slot_limit = resource_limit
11075        + jobs
11076            .iter()
11077            .map(|j| j.timeout)
11078            .max()
11079            .unwrap_or_default()
11080            .saturating_mul(jobs.len() as u32);
11081    let mut set = tokio::task::JoinSet::new();
11082    // Seats announce themselves here the moment they hold a parallelism
11083    // permit, i.e. just before their CLI is spawned.
11084    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11085    let overlay = prompts.overlay(node);
11086    let repository_wait = repository_wait(state, pauses);
11087    for (i, mut job) in jobs.into_iter().enumerate() {
11088        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11089        if cache.is_some() {
11090            job.prompt.push('\n');
11091            job.prompt
11092                .push_str(&prompt::build_cache_note(node, job.allow_write));
11093        }
11094        let sem = Arc::clone(&sem);
11095        let run = run.to_owned();
11096        let node = node.to_owned();
11097        // Only implementers were told about the task's attachments, so only
11098        // their seats get the directory widened for reading.
11099        let attachments = if node == "implement" {
11100            state.attachments.clone()
11101        } else {
11102            Vec::new()
11103        };
11104        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11105        // `prompt::build_cache_note`'s doc for why setting it anyway is
11106        // exactly how a sandboxed reviewer's write refusal got reported as a
11107        // defect in the patch, not a property of its own seat. And a
11108        // write-allowed one is handed it only when the lease above was
11109        // actually acquired: a wave that could not get it (`cache_guard` is
11110        // `None`, see its own comment) must not send seats to build into a
11111        // directory this run does not hold - that is the exact concurrent,
11112        // unmanaged-write race this module exists to prevent, not something
11113        // "proceeding anyway" is allowed to reintroduce.
11114        let cache = cache
11115            .filter(|_| job.allow_write && cache_guard.is_some())
11116            .map(Path::to_path_buf);
11117        let spawned_tx = spawned_tx.clone();
11118        let repository_wait = repository_wait.clone();
11119        let coordination = state.config.coordination.clone();
11120        let fetched_base = state.fetched_base.clone();
11121        set.spawn(async move {
11122            // A wait for a parallelism slot is scheduling, not the agent: it
11123            // is bounded by its own limit and ends as a resource block, never
11124            // as a timeout of the agent that was not started.
11125            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11126                Ok(p) => p,
11127                Err(_) => {
11128                    return (
11129                        i,
11130                        job.seat,
11131                        AgentOutcome::ResourceBlocked(format!(
11132                            "no parallel slot became free within {}s",
11133                            slot_limit.as_secs()
11134                        )),
11135                        None,
11136                        false,
11137                    );
11138                }
11139            };
11140            spawned_tx.send(job.seat.key.clone()).ok();
11141            let mut seat = job.seat;
11142            let out = repository_wait
11143                .scope(agent::invoke(
11144                    &job.spec,
11145                    &mut seat,
11146                    &Invocation {
11147                        coordination: coordination.as_ref(),
11148                        fetched_base: fetched_base.as_ref(),
11149                        cwd: &job.cwd,
11150                        prompt: &job.prompt,
11151                        timeout: job.timeout,
11152                        allow_write: job.allow_write,
11153                        sessions: job.sessions,
11154                        artifacts: &job.artifacts,
11155                        stem: &job.stem,
11156                        run: &run,
11157                        node: &node,
11158                        cache_dir: cache.as_deref(),
11159                        attachments: &attachments,
11160                        writable: &[],
11161                    },
11162                ))
11163                .await;
11164            let cache_block = out
11165                .as_ref()
11166                .err()
11167                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11168                .map(|timeout| timeout.0.clone());
11169            let interrupted = out
11170                .as_ref()
11171                .err()
11172                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11173            let out = match out {
11174                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11175                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11176                // Billed work the CLI failed to hand over is not an ordinary
11177                // failure, but its text is the CLI's raw error JSON, not an
11178                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11179                // read it as one by forgetting to check. `usable()` is always
11180                // false here (dropped implies an empty response), so this has
11181                // to be checked before the catch-all `Failed` below or the
11182                // one shape this exists for is lost with the rest.
11183                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11184                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11185                Ok(o) => AgentOutcome::Failed(format!(
11186                    "process exited with no usable output ({})",
11187                    crate::notices::exit_status(o.exit_code)
11188                )),
11189                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11190                    AgentOutcome::ResourceBlocked(e.to_string())
11191                }
11192                Err(e) => AgentOutcome::Failed(e.to_string()),
11193            };
11194            (i, seat, out, cache_block, interrupted)
11195        });
11196    }
11197    drop(spawned_tx);
11198    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11199    loop {
11200        let joined = tokio::select! {
11201            Some(key) = spawned_rx.recv() => {
11202                // The clock of this seat starts now, not when it queued.
11203                state.seat_spawned(&key);
11204                if let Err(e) = state.save() {
11205                    tracing::warn!("could not persist a seat's start: {e:#}");
11206                }
11207                continue;
11208            }
11209            joined = set.join_next() => joined,
11210        };
11211        let Some(joined) = joined else {
11212            break;
11213        };
11214        let (i, seat, out, cache_block, interrupted) = match joined {
11215            Ok(v) => v,
11216            // No seat to clear: a panicked task never reported which one it
11217            // was. The defensive sweep below this loop is what stops that
11218            // seat's `active` entry from surviving forever.
11219            Err(e) => {
11220                tracing::error!("agent task panicked: {e}");
11221                continue;
11222            }
11223        };
11224        state.seat_finished(&seat.key);
11225        if interrupted
11226            && node == "implement"
11227            && let Some(label) = state
11228                .candidates
11229                .iter()
11230                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11231                .map(|candidate| candidate.label)
11232        {
11233            state.candidate_preservation.insert(
11234                label,
11235                "interrupted implementation awaiting persistence".into(),
11236            );
11237            state.interrupted_implementations.insert(label);
11238        }
11239        if let Some(block) = cache_block
11240            && state.resource_block.is_none()
11241        {
11242            state.event("resource", block.description());
11243            state.resource_block = Some(block);
11244        }
11245        if let AgentOutcome::ResourceBlocked(why) = &out
11246            && state.resource_block.is_none()
11247        {
11248            state.resource_block = Some(crate::run::ResourceBlock {
11249                cause: crate::run::ResourceBlockCause::Other,
11250                node: node.to_owned(),
11251                kind: if why.contains("disk pressure") {
11252                    "disk pressure"
11253                } else if why.contains("disk admission") {
11254                    "disk admission"
11255                } else if why.contains(crate::incremental::BLOCKED) {
11256                    "incremental cache admission"
11257                } else if why.contains(crate::build_target::KIND) {
11258                    crate::build_target::KIND
11259                } else if why.contains("repository coordination") {
11260                    "repository coordination"
11261                } else {
11262                    "parallel slot"
11263                }
11264                .to_owned(),
11265                detail: why.clone(),
11266                at: Timestamp::now(),
11267            });
11268            let activity = if interrupted {
11269                "agent execution interrupted"
11270            } else {
11271                "no agent was started"
11272            };
11273            state.event("resource", format!("{node}: {activity} - {why}"));
11274        }
11275        record_jobs(state, node, round, &seat.key, &out);
11276        if let Err(e) = state.save() {
11277            tracing::warn!("could not persist a seat's completion: {e:#}");
11278        }
11279        if collected.len() <= i {
11280            collected.resize_with(i + 1, || None);
11281        }
11282        collected[i] = Some((i, seat, out));
11283    }
11284    // Belt-and-braces for the panic branch above: every seat this exact batch
11285    // started shares this `(node, attempt)` pair, and every seat that finished
11286    // normally already cleared itself, so anything left tagged with it here
11287    // can only be a panicked task's leftover. Cleared unconditionally rather
11288    // than left to read as still answering forever.
11289    if state
11290        .active
11291        .values()
11292        .any(|a| a.node == node && a.attempt == attempt)
11293    {
11294        state
11295            .active
11296            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11297        if let Err(e) = state.save() {
11298            tracing::warn!("could not persist the end of a wave: {e:#}");
11299        }
11300    }
11301    // Whether or not the lease above was actually held, several worktrees
11302    // may just have built into the cache with nothing here able to name one
11303    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11304    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11305    // clean it might not have strictly needed; trusting a stale match would
11306    // cost it a wrong answer.
11307    if let Some(cache_dir) = cache
11308        && jobs_had_a_writer
11309    {
11310        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11311    }
11312    if let Some(guard) = cache_guard {
11313        guard.release();
11314    }
11315    collected.into_iter().flatten().collect()
11316}
11317
11318/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11319/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11320/// this is data collection, not the fix-specific completion contract in
11321/// [`Runner::continue_fix_report`], and applies regardless of which node
11322/// asked.
11323///
11324/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11325/// evidence from; `Failed` does not, and correctly contributes nothing — a
11326/// timeout or crash is not itself evidence about a command the seat may have
11327/// started.
11328fn record_jobs(
11329    state: &mut RunState,
11330    node: &str,
11331    round: Option<usize>,
11332    seat: &str,
11333    out: &AgentOutcome,
11334) {
11335    let commands: &[agent::CommandEvidence] = match out {
11336        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11337        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11338    };
11339    let checked_at = Timestamp::now();
11340    for c in commands {
11341        state.jobs.push(JobRecord {
11342            node: node.to_owned(),
11343            round,
11344            seat: seat.to_owned(),
11345            id: c.id.clone(),
11346            description: c.description.clone(),
11347            checked_at,
11348            status: match c.exit_code {
11349                Some(0) => JobStatus::Completed,
11350                Some(_) => JobStatus::Failed,
11351                None => JobStatus::Unknown,
11352            },
11353            exit_code: c.exit_code,
11354            result_summary: c.result_summary.clone(),
11355            source: c.source.clone(),
11356        });
11357    }
11358}
11359
11360/// Is a review round clean, given how many reviewer seats answered against
11361/// how many the round expected?
11362///
11363/// A seat that never answered (timeout, crash, unparsable output) is not a
11364/// seat that read the patch and found nothing — treating it as such is
11365/// exactly the bug this function exists to close. Under the default `block`
11366/// policy a missing seat can never be clean; `warn` still requires the seats
11367/// that *did* answer to have found nothing blocking and verification to be
11368/// green.
11369///
11370/// `quota_missing` narrows that `block` default for exactly one cause of
11371/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11372/// a session limit lifts by the very next round buys nothing — the seat is
11373/// asked again with the same quota — so once every missing seat is accounted
11374/// for by a quota loss (and at least one seat *did* answer, so a decision has
11375/// something to rest on) the round is decided on the panel that could answer,
11376/// same as `warn` would. A panel that lost every seat to quota is not
11377/// decided here: `answered == 0` falls through to the existing `block`
11378/// fallback so a fully collapsed panel still waits rather than landing on no
11379/// review at all.
11380fn round_is_clean(
11381    blocking: usize,
11382    e2e_ok: bool,
11383    answered: usize,
11384    expected: usize,
11385    quota_missing: usize,
11386    policy: IncompleteReviewPolicy,
11387) -> bool {
11388    if blocking != 0 || !e2e_ok {
11389        return false;
11390    }
11391    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11392        return true;
11393    }
11394    answered > 0 && expected - answered <= quota_missing
11395}
11396
11397/// The review loop's own conclusion, derived entirely from its persisted
11398/// round records and the round budget that produced them — never from
11399/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11400/// recomputes the identical answer regardless of what an earlier node in the
11401/// same walk, or a previous walk, did to `status`.
11402///
11403/// `None` while more rounds remain to try, including when review never ran
11404/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11405/// gone clean, or the budget is spent, or the tree has stopped moving (see
11406/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11407///
11408/// - An incomplete panel that raised nothing is missing input, not a
11409///   verified tree — never a hand-off candidate, whatever verification said
11410///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11411/// - Otherwise, green e2e on the last round hands off (see
11412///   [`Runner::stop_reviewing`]); red e2e blocks.
11413///
11414/// A last round whose own verification is still `ResourceBlocked` — magi
11415/// itself never got a command to run, not evidence the patch is broken —
11416/// is neither: this returns `None` for it too, the same as "more rounds
11417/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11418/// handling of that shape) instead of this cheap recomputation guessing a
11419/// verdict a real attempt never produced.
11420pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11421    if max_rounds == 0
11422        || reviews.last().is_some_and(|r| {
11423            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11424        })
11425    {
11426        return Some(RunStatus::Gating);
11427    }
11428    let last = reviews.last()?;
11429    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11430    if reviews.len() < max_rounds && !stagnant {
11431        return None;
11432    }
11433    if last.incomplete() && last.blocking == 0 {
11434        return Some(RunStatus::Blocked);
11435    }
11436    if last.e2e_status() == E2eStatus::ResourceBlocked
11437        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11438    {
11439        return None;
11440    }
11441    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11442        RunStatus::Gating
11443    } else {
11444        RunStatus::Blocked
11445    })
11446}
11447
11448/// How long a re-ask may take, given the budget the first attempt had.
11449///
11450/// A `nudged` retry is a request to restate an answer the seat has already
11451/// worked out: it carries no new work, so it does not deserve the original
11452/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11453/// 133 seconds while a third sat for over ten minutes on a resumed session
11454/// holding 410 KB of prior output - and because the retry had inherited the
11455/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11456/// judging round whose other seats were long finished.
11457///
11458/// A quarter of the budget, with a floor so that a deliberately short timeout
11459/// does not collapse to nothing. A retry that re-sends the whole prompt
11460/// (because the seat kept no context) is the original job again, and keeps the
11461/// original budget.
11462pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11463    if nudged {
11464        (full / 4).max(Duration::from_secs(120)).min(full)
11465    } else {
11466        full
11467    }
11468}
11469
11470/// Run a wave and parse each reply, re-asking the seats whose reply was
11471/// unusable.
11472///
11473/// The re-ask is a nudge rather than the whole prompt again when the seat still
11474/// holds its conversation, which is the difference between a cheap retry and
11475/// paying for the entire candidate set twice.
11476///
11477/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11478/// successor in `roster` is handed to it instead of being re-asked: the
11479/// handover is the retry. A seat with no successor left (a single-agent
11480/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11481/// the asks to one seat in one node number at most
11482/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11483/// is asked once (a dropped stream is nudged first), and only the last agent
11484/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11485/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11486/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11487/// other failure stops the chain when the previous agent failed the same way
11488/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11489/// [`has_context`] is false and the job's own full prompt and full budget are
11490/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11491/// intermediate ones are not losses) and is returned as a failure like any
11492/// other absent seat — the caller decides whether the panel still has a
11493/// quorum. An empty `roster` disables handover: failures are nudged as they
11494/// always were, and a quota is simply lost. A reply that fails to parse or
11495/// validate is the prompt's doing and is only ever nudged, never handed over.
11496///
11497/// The returned [`SeatState`] names the agent that answered (or tried last).
11498#[allow(clippy::too_many_arguments)]
11499async fn ask_json_wave<T>(
11500    jobs: Vec<SeatJob>,
11501    sem: Arc<Semaphore>,
11502    retries: usize,
11503    roster: &[AgentSpec],
11504    ctx: &WaveCtx<'_>,
11505    losses: &mut Vec<QuotaLoss>,
11506    state: &mut RunState,
11507    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11508) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11509where
11510    T: serde::de::DeserializeOwned + Send + 'static,
11511{
11512    ask_wave_with(
11513        jobs,
11514        sem,
11515        retries,
11516        roster,
11517        ctx,
11518        losses,
11519        state,
11520        &|text: &str| {
11521            let v = verdict::extract_json::<T>(text)?;
11522            validate(&v)?;
11523            Ok(v)
11524        },
11525    )
11526    .await
11527}
11528
11529/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11530/// a node whose answer is prose (deliberation) shares the same handover,
11531/// failure classification, quota bookkeeping and bounds instead of a copy.
11532///
11533/// A seat handed to another roster agent is sent the job's `handover` prompt
11534/// (when it has one) rather than `prompt`: the new agent has no session, so a
11535/// resume-style prompt would be incomplete. That holds for the handover ask
11536/// and for every nudge to that agent whose `has_context` is false.
11537#[allow(clippy::too_many_arguments)]
11538async fn ask_wave_with<T>(
11539    jobs: Vec<SeatJob>,
11540    sem: Arc<Semaphore>,
11541    retries: usize,
11542    roster: &[AgentSpec],
11543    ctx: &WaveCtx<'_>,
11544    losses: &mut Vec<QuotaLoss>,
11545    state: &mut RunState,
11546    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11547) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11548where
11549    T: Send + 'static,
11550{
11551    let n = jobs.len();
11552    let originals: Vec<SeatJob> = jobs;
11553    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11554    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11555    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11556    // answer, N once it has gone through N nudges. Read back once this
11557    // returns, so a caller building a history record (`ReviewRecord`) can
11558    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11559    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11560    // field's own doc.
11561    let mut nudges: Vec<usize> = vec![0; n];
11562    // The agent now occupying each seat, the ids it has already been through,
11563    // where in the roster the walk began, the class of the last failure, and
11564    // the stem word of a handover not yet asked (full prompt, full budget).
11565    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11566    let mut tried: Vec<BTreeSet<String>> = specs
11567        .iter()
11568        .map(|s| BTreeSet::from([s.id.clone()]))
11569        .collect();
11570    let starts: Vec<usize> = specs
11571        .iter()
11572        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11573        .collect();
11574    let carry = ctx.carry_seats && !roster.is_empty();
11575    // Carried across rounds: ids that failed the seat earlier, and how the
11576    // last failure went (so a repeat of it is not handed over again).
11577    let carried: Vec<BTreeSet<String>> = originals
11578        .iter()
11579        .map(|j| {
11580            state
11581                .seat_history
11582                .get(&j.seat.key)
11583                .filter(|_| carry)
11584                .map(|h| h.failed.clone())
11585                .unwrap_or_default()
11586        })
11587        .collect();
11588    let mut prev: Vec<Option<FailClass>> = originals
11589        .iter()
11590        .map(|j| {
11591            state
11592                .seat_history
11593                .get(&j.seat.key)
11594                .filter(|_| carry)
11595                .and_then(|h| h.last_fail.clone())
11596        })
11597        .collect();
11598    let next_agent =
11599        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11600            let others: BTreeSet<String> = specs
11601                .iter()
11602                .enumerate()
11603                .filter(|(j, _)| *j != i)
11604                .map(|(_, s)| s.id.clone())
11605                .collect();
11606            pick_successor(
11607                roster,
11608                starts[i],
11609                tried,
11610                carry.then(|| &carried[i]),
11611                &others,
11612            )
11613            .cloned()
11614        };
11615    let mut fresh: Vec<Option<String>> = vec![None; n];
11616    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11617    let mut pending: Vec<usize> = (0..n).collect();
11618
11619    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11620    // asks: an agent with a successor is asked once and handed over, and only
11621    // a seat with no successor spends `retries` nudges on the same agent. This
11622    // only guarantees the loop's own termination whatever those say.
11623    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11624    for round in 0..max_rounds {
11625        if pending.is_empty() {
11626            break;
11627        }
11628        let mut batch = Vec::with_capacity(pending.len());
11629        let mut renudged: Vec<&str> = Vec::new();
11630        for &i in &pending {
11631            let src = &originals[i];
11632            // A seat now held by another agent than the job named has no
11633            // session of its own: it gets the full-context prompt whenever
11634            // it is asked in full (the handover ask, a nudge it cannot
11635            // resume).
11636            let full: &str = match &src.handover {
11637                Some(h) if specs[i].id != src.spec.id => h,
11638                _ => &src.prompt,
11639            };
11640            // The prompt and the budget are one decision: a nudge restates
11641            // finished work, a re-sent prompt redoes it.
11642            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11643                (
11644                    full.to_owned(),
11645                    src.timeout,
11646                    format!("{}-{word}-{}", src.stem, specs[i].id),
11647                )
11648            } else if nudges[i] == 0 {
11649                (full.to_owned(), src.timeout, src.stem.clone())
11650            } else {
11651                renudged.push(src.seat.key.as_str());
11652                let why = done[i]
11653                    .as_ref()
11654                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11655                    .unwrap_or_else(|| "no parsable answer".to_owned());
11656                let nudge = prompt::nudge(&why);
11657                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11658                let prompt = if nudged {
11659                    nudge
11660                } else {
11661                    format!("{full}\n\n---\n\n{nudge}")
11662                };
11663                (
11664                    prompt,
11665                    retry_budget(src.timeout, nudged),
11666                    format!("{}-retry{}", src.stem, nudges[i]),
11667                )
11668            };
11669            batch.push(SeatJob {
11670                spec: specs[i].clone(),
11671                seat: seats[i].clone(),
11672                cwd: src.cwd.clone(),
11673                prompt,
11674                timeout,
11675                allow_write: src.allow_write,
11676                sessions: src.sessions,
11677                artifacts: src.artifacts.clone(),
11678                stem,
11679                handover: None,
11680            });
11681        }
11682
11683        if !renudged.is_empty() {
11684            state.event(
11685                ctx.node,
11686                format!("retry {round}: re-asking {}", renudged.join(", ")),
11687            );
11688        }
11689        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11690        let mut still = Vec::new();
11691        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11692            seats[i] = seat;
11693            // No agent was asked: nothing to hand over, nudge, remember or
11694            // charge. The caller sees `resource_block` and stops the node.
11695            if let AgentOutcome::ResourceBlocked(why) = &out {
11696                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11697                continue;
11698            }
11699            let class = FailClass::of(&out);
11700            // A dropped stream is nudged first (the conversation is still
11701            // there to pick up); only a seat whose nudges are spent hands over.
11702            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11703                && nudges[i] < retries
11704                && !roster.is_empty();
11705            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11706                let next = should_hand_over(prev[i].as_ref(), &cur)
11707                    .then(|| next_agent(i, &tried[i], &specs))
11708                    .flatten();
11709                if carry {
11710                    let h = state
11711                        .seat_history
11712                        .entry(originals[i].seat.key.clone())
11713                        .or_default();
11714                    h.failed.insert(specs[i].id.clone());
11715                    h.last_fail = Some(cur.clone());
11716                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11717                        h.last_ok = None;
11718                    }
11719                    // Saved before the next agent is asked, so a restart in
11720                    // between does not forget who failed.
11721                    if let Err(e) = state.save() {
11722                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11723                    }
11724                }
11725                if let Some(next) = next {
11726                    record_handover(
11727                        state,
11728                        ctx.node,
11729                        &originals[i].seat.key,
11730                        &specs[i].id,
11731                        &next.id,
11732                        &cur,
11733                        &fail_reason(&out),
11734                    );
11735                    tried[i].insert(next.id.clone());
11736                    prev[i] = Some(cur.clone());
11737                    seats[i] =
11738                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11739                    specs[i] = next;
11740                    fresh[i] = Some(cur.stem_word().to_owned());
11741                    nudges[i] = 0;
11742                    done[i] = Some(Err(anyhow::anyhow!(
11743                        "handed over after: {}",
11744                        fail_reason(&out)
11745                    )));
11746                    still.push(i);
11747                    continue;
11748                }
11749            }
11750            if carry
11751                && !nudge_first
11752                && let Some(cur) = class.clone()
11753            {
11754                // The chain ended here (no successor, or a repeated failure).
11755                let h = state
11756                    .seat_history
11757                    .entry(originals[i].seat.key.clone())
11758                    .or_default();
11759                h.failed.insert(specs[i].id.clone());
11760                h.last_fail = Some(cur);
11761            }
11762            let parsed = match out {
11763                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11764                AgentOutcome::Quota(o) => {
11765                    last_quota[i] = o.quota.clone();
11766                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11767                }
11768                // Not a parseable answer: the nudge loop re-asks it, which is
11769                // exactly what a dropped stream needs. Just don't hand its raw
11770                // error JSON to `extract_json`.
11771                AgentOutcome::Dropped(o) => {
11772                    let why = o
11773                        .dropped
11774                        .as_ref()
11775                        .map(|d| d.why.as_str())
11776                        .unwrap_or("the CLI ended the stream without delivering its answer");
11777                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11778                }
11779                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11780                    Err(anyhow::anyhow!(e))
11781                }
11782            };
11783            let quota = class == Some(FailClass::Quota);
11784            let failed = parsed.is_err();
11785            if !failed && matches!(ctx.node, "judge" | "vote") {
11786                // A validated answer restores this seat's quorum presence,
11787                // including on the normal path after an all-seat block.
11788                state
11789                    .quota
11790                    .retain(|loss| loss.seat != originals[i].seat.key);
11791            }
11792            done[i] = Some(parsed);
11793            if carry && !failed {
11794                let h = state
11795                    .seat_history
11796                    .entry(originals[i].seat.key.clone())
11797                    .or_default();
11798                h.failed.remove(&specs[i].id);
11799                h.last_ok = Some(specs[i].id.clone());
11800                h.last_fail = None;
11801            }
11802            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11803            // fail the same way; and never re-ask a seat that already parsed.
11804            // A failed agent that still has a successor is not re-asked
11805            // either: the handover was its remedy and has just been refused
11806            // (the chain stops on a repeated failure class). A seat with no
11807            // successor left (a single-agent roster, the roster's tail, or an
11808            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11809            let agent_failure = class.is_some()
11810                && !nudge_first
11811                && !roster.is_empty()
11812                && next_agent(i, &tried[i], &specs).is_some();
11813            if failed && !quota && !agent_failure && nudges[i] < retries {
11814                nudges[i] += 1;
11815                still.push(i);
11816            }
11817        }
11818        pending = still;
11819    }
11820
11821    // One loss per seat whose chain ended on a quota: the intermediate ones
11822    // were absorbed by a handover and are not losses.
11823    for (i, q) in last_quota.into_iter().enumerate() {
11824        if let Some(quota) = q {
11825            losses.push(QuotaLoss::from_report(
11826                originals[i].seat.key.clone(),
11827                ctx.node,
11828                Some(&quota),
11829            ));
11830        }
11831    }
11832
11833    // A stalled quorum already has its own recovery checkpoint. Refresh
11834    // its missing seats before deciding whether it can resume.
11835    if state.status != RunStatus::Stalled
11836        && ctx.node != "deliberate"
11837        && n > 0
11838        && losses.len() == n
11839        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11840    {
11841        block_machine_outage(state, ctx.node, losses);
11842        state.quota.append(losses);
11843    }
11844
11845    seats
11846        .into_iter()
11847        .zip(done)
11848        .zip(nudges)
11849        .map(|((seat, res), attempts)| {
11850            (
11851                seat,
11852                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
11853                attempts,
11854            )
11855        })
11856        .collect()
11857}
11858
11859/// A node with no available agent has no task verdict. Preserve the node
11860/// checkpoint and record why a subsequent explicit resume is needed.
11861pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
11862    let mut auth: Vec<_> = losses
11863        .iter()
11864        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
11865        .map(|loss| loss.agent.clone())
11866        .collect();
11867    auth.sort();
11868    auth.dedup();
11869    let (kind, detail) = if auth.is_empty() {
11870        (
11871            "agent usage limit",
11872            "All seats reached their agent usage limits; resume after usage is available"
11873                .to_owned(),
11874        )
11875    } else {
11876        (
11877            "agent authentication",
11878            format!(
11879                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
11880                auth.join(", ")
11881            ),
11882        )
11883    };
11884    state.resource_block = Some(crate::run::ResourceBlock {
11885        node: node.to_owned(),
11886        kind: kind.to_owned(),
11887        cause: crate::run::ResourceBlockCause::Other,
11888        detail: detail.clone(),
11889        at: Timestamp::now(),
11890    });
11891    state.event(node, detail);
11892}
11893
11894/// Did the wave end without asking any agent (see [`block_wave`])?
11895fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
11896    results
11897        .iter()
11898        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
11899}
11900
11901/// Settle a wave that never spawned anything: every job answers
11902/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
11903/// else about the seat (session, history, quota) is touched.
11904fn block_wave(
11905    jobs: Vec<SeatJob>,
11906    state: &mut RunState,
11907    node: &str,
11908    attempt: usize,
11909    why: &str,
11910) -> Vec<(usize, SeatState, AgentOutcome)> {
11911    state.resource_wait = None;
11912    state
11913        .active
11914        .retain(|_, a| !(a.node == node && a.attempt == attempt));
11915    if let Err(e) = state.save() {
11916        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
11917    }
11918    jobs.into_iter()
11919        .enumerate()
11920        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
11921        .collect()
11922}
11923
11924/// Acquire the shared build cache's lease, waiting out contention within
11925/// `budget` (never past it — see AGENTS.md's build-cache section on why an
11926/// unbounded wait is never acceptable).
11927///
11928/// A first, non-blocking check happens before ever waiting; if it finds the
11929/// lease busy, that fact is logged as a `verify` event *and* flushed with
11930/// [`RunState::save`] immediately — not only once the wait finally succeeds
11931/// or gives up — so a `magi show` run by a different process while this one
11932/// is still waiting reads a `run.json` that says so, rather than whatever it
11933/// looked like before the wait started. The same applies to the terminal
11934/// failure: logged and saved before this returns `Err`, so a caller that
11935/// could not get the lease at all still leaves a legible record of why.
11936async fn acquire_cache_lease(
11937    state: &mut RunState,
11938    cache_dir: &Path,
11939    owner: &crate::cache::Owner,
11940    budget: Duration,
11941    node: &str,
11942    context: &str,
11943    cancel: &(dyn Fn() -> bool + Sync),
11944) -> Result<Option<crate::cache::Guard>> {
11945    let home = crate::run::home();
11946    let kind = if crate::build_target::isolated(&state.config) {
11947        crate::build_target::KIND
11948    } else {
11949        "shared build cache"
11950    };
11951    let started = Instant::now();
11952    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
11953        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
11954        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
11955        Err(e) => {
11956            state.event(
11957                "verify",
11958                format!(
11959                    "{context}: could not check the {kind} at {}: {e:#}",
11960                    cache_dir.display()
11961                ),
11962            );
11963            if let Err(e2) = state.save() {
11964                tracing::warn!("could not persist a cache-check failure: {e2:#}");
11965            }
11966            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
11967        }
11968    };
11969    state.event(
11970        "verify",
11971        format!(
11972            "{context}: waiting for the {kind} at {} ({})",
11973            cache_dir.display(),
11974            busy.describe()
11975        ),
11976    );
11977    // Seats of this node are waiting, not running: say so, so the countdown a
11978    // reader sees only ever measures an agent that has been spawned.
11979    state.resource_wait = Some(crate::run::ResourceWait {
11980        node: context.to_owned(),
11981        kind: kind.to_owned(),
11982        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
11983        since: Timestamp::now(),
11984        limit_secs: budget.as_secs(),
11985    });
11986    if let Err(e) = state.save() {
11987        tracing::warn!("could not persist a cache wait: {e:#}");
11988    }
11989    let remaining = budget.saturating_sub(started.elapsed());
11990    let waited = crate::cache::wait_for_unless(
11991        &home,
11992        cache_dir,
11993        owner,
11994        remaining,
11995        Duration::from_secs(5),
11996        cancel,
11997    )
11998    .await;
11999    state.resource_wait = None;
12000    let cause = match &waited {
12001        Ok(Some(_)) => None,
12002        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12003        Err(error)
12004            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12005        {
12006            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12007                target: cache_dir.to_owned(),
12008                waited_secs: started.elapsed().as_secs(),
12009                limit_secs: budget.as_secs(),
12010            })
12011        }
12012        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12013            Some(crate::run::ResourceBlockCause::Timeout {
12014                waited_secs: started.elapsed().as_secs(),
12015                limit_secs: budget.as_secs(),
12016            })
12017        }
12018        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12019    };
12020    if let Some(cause) = cause {
12021        let detail = match &waited {
12022            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12023            Err(error) => format!("{error:#}"),
12024        };
12025        state.resource_block = Some(crate::run::ResourceBlock {
12026            cause,
12027            node: node.to_owned(),
12028            kind: kind.into(),
12029            detail: format!("{}: {detail}", cache_dir.display()),
12030            at: Timestamp::now(),
12031        });
12032        state.event(
12033            "resource",
12034            state.resource_block.as_ref().unwrap().description(),
12035        );
12036    }
12037    if let Err(error) = state.save() {
12038        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12039    }
12040    waited
12041}
12042
12043/// The lease state could not be read at all (unreadable lease file, a
12044/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12045/// known to be contended, so a wave degrades to running without a shared cache
12046/// instead of stopping on a hold that [`crate::triage`] could never release.
12047#[derive(Debug)]
12048struct CacheCheckError(String);
12049
12050impl std::fmt::Display for CacheCheckError {
12051    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12052        f.write_str(&self.0)
12053    }
12054}
12055
12056impl std::error::Error for CacheCheckError {}
12057
12058/// Keep a specific acquisition outcome when the caller adds command evidence.
12059fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12060    let kind = if crate::build_target::isolated(&state.config) {
12061        crate::build_target::KIND
12062    } else {
12063        "shared build cache"
12064    };
12065    state
12066        .resource_block
12067        .get_or_insert_with(|| crate::run::ResourceBlock {
12068            cause: crate::run::ResourceBlockCause::Other,
12069            node: node.to_owned(),
12070            kind: kind.into(),
12071            detail: format!("{error:#}"),
12072            at: Timestamp::now(),
12073        });
12074    if let Err(error) = state.save() {
12075        tracing::warn!("could not persist cache resource block: {error:#}");
12076    }
12077}
12078
12079tokio::task_local! {
12080    static VERIFY_TARGET: PathBuf;
12081}
12082
12083/// Run `body` — a verify command batch — while holding the shared build
12084/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12085/// never interleave with another borrower's build against the same
12086/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12087/// timeout, or a human's own `magi review`. See the `cache` module doc for
12088/// why this matters more than Cargo's own per-target locking covers — two
12089/// *different* worktrees building the same package name/version into one
12090/// cache directory is a staleness bug, not a lock contention one.
12091///
12092/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12093/// agent waves do. Repository scheduling also has its own bounded,
12094/// cancellable resource-wait policy. Contention must not consume the
12095/// verification budget: `body` receives the full `budget` after both leases
12096/// are acquired and the cache is fresh. Without a shared cache, only
12097/// repository coordination is acquired before handing over the full budget.
12098///
12099/// A lease that cannot be acquired within the resource wait is reported as a single
12100/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12101/// verification — the same shape a spawn failure already takes in
12102/// [`run_commands`], so a caller need not special-case it.
12103#[allow(clippy::too_many_arguments)]
12104async fn with_cache_lease<'s, F, Fut>(
12105    state: &'s mut RunState,
12106    cache_dir: Option<&Path>,
12107    node: &str,
12108    seat: &str,
12109    worktree: &Path,
12110    head: &str,
12111    budget: Duration,
12112    context: &str,
12113    wait: &crate::repo_lock::WaitPolicy,
12114    body: F,
12115) -> Result<(Vec<CommandOutcome>, bool)>
12116where
12117    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12118    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12119{
12120    // Match editing waves: cache first, repository second. In particular,
12121    // pre_gate must never hold the repository while waiting for a wave's cache.
12122    let started = Instant::now();
12123    let home = crate::run::home();
12124    let isolated = crate::build_target::isolated(&state.config);
12125    let planned_target = if isolated {
12126        let plan = (|| -> Result<PathBuf> {
12127            crate::build_target::supports(&state.config)?;
12128            crate::build_target::resolve(&home, worktree)
12129        })();
12130        match plan {
12131            Ok(path) => Some(path),
12132            Err(error) => {
12133                record_cache_error(state, node, &error);
12134                return Ok((
12135                    vec![CommandOutcome {
12136                        command: "(planning isolated build cache)".into(),
12137                        code: None,
12138                        output_tail: format!("{error:#}"),
12139                        duration_ms: 0,
12140                        resource_blocked: true,
12141                    }],
12142                    false,
12143                ));
12144            }
12145        }
12146    } else {
12147        None
12148    };
12149    let cache_dir = planned_target.as_deref().or(cache_dir);
12150    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12151    let guard = if let Some(cache_dir) = cache_dir {
12152        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12153        match acquire_cache_lease(
12154            state,
12155            cache_dir,
12156            &owner,
12157            resource_limit,
12158            node,
12159            context,
12160            &|| wait.cancelled(),
12161        )
12162        .await
12163        .and_then(|g| {
12164            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12165        }) {
12166            Ok(g) => Some(g),
12167            Err(e) => {
12168                record_cache_error(state, node, &e);
12169                return Ok((
12170                    vec![CommandOutcome {
12171                        command: if isolated {
12172                            "(waiting for the isolated build cache)"
12173                        } else {
12174                            "(waiting for the shared build cache)"
12175                        }
12176                        .into(),
12177                        code: None,
12178                        output_tail: e.to_string(),
12179                        duration_ms: started.elapsed().as_millis() as u64,
12180                        resource_blocked: true,
12181                    }],
12182                    false,
12183                ));
12184            }
12185        }
12186    } else {
12187        None
12188    };
12189    let _coordination = coordinate_operation(state, worktree, wait).await?;
12190    if let Some(path) = &planned_target {
12191        state.event(node, format!("isolated build target: {}", path.display()));
12192    }
12193    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12194        let identity = crate::cache::Identity::new(worktree, head);
12195        let fresh = crate::cache::ensure_fresh(
12196            &home,
12197            cache_dir,
12198            &identity,
12199            &state.config.verify.cargo_manifests(),
12200        );
12201        if let Err(e) = fresh {
12202            record_cache_error(state, node, &e);
12203            state.event(
12204                "verify",
12205                format!(
12206                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12207                    worktree.display(),
12208                    short(head)
12209                ),
12210            );
12211            if let Some(guard) = guard {
12212                guard.release();
12213            }
12214            return Ok((
12215                vec![CommandOutcome {
12216                    command: "(confirming the build cache is fresh)".into(),
12217                    code: None,
12218                    output_tail: e.to_string(),
12219                    duration_ms: started.elapsed().as_millis() as u64,
12220                    resource_blocked: true,
12221                }],
12222                false,
12223            ));
12224        }
12225    }
12226    let future = body(state, budget);
12227    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12228        VERIFY_TARGET.scope(target, future).await
12229    } else {
12230        future.await
12231    };
12232    if !timed_out_pids.is_empty() {
12233        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12234    }
12235    // Drop repository coordination before releasing the cache, reversing the
12236    // acquisition order. A cancelled/error future also drops both guards.
12237    drop(_coordination);
12238    if let Some(guard) = guard {
12239        guard.release();
12240    }
12241    Ok((outcomes, retried))
12242}
12243
12244/// Poll `pids` — commands [`run_commands`] reports as still running when its
12245/// own timeout elapsed — until every one is confirmed gone, or
12246/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12247///
12248/// Real confirmation where confirmation is possible, not a substitute for
12249/// full process-tree observation: a grandchild the timed-out process spawned
12250/// and that survives independently of it is invisible to a pid check the
12251/// same way it always was, and continuing to observe and collect *that*
12252/// stays a different piece of work with its own owner. This only narrows a
12253/// fixed blind wait into an actual check of the pids this process does know
12254/// about.
12255async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12256    wait_for_pids_with(
12257        pids,
12258        crate::proc::pid_alive,
12259        LEASE_RELEASE_POLL,
12260        LEASE_RELEASE_MAX_WAIT,
12261    )
12262    .await;
12263}
12264
12265/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12266/// interval and ceiling supplied by the caller, so the polling *logic* -
12267/// returns as soon as every pid reports dead, gives up at the ceiling
12268/// otherwise - is testable on millisecond durations without asking the real
12269/// OS about a pid at all.
12270async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12271    pids: &[u32],
12272    alive: F,
12273    poll: Duration,
12274    max_wait: Duration,
12275) {
12276    let deadline = Instant::now() + max_wait;
12277    loop {
12278        if pids.iter().all(|&pid| !alive(pid)) {
12279            return;
12280        }
12281        if Instant::now() >= deadline {
12282            return;
12283        }
12284        tokio::time::sleep(poll).await;
12285    }
12286}
12287
12288/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12289/// admission that it could not even get a verify command to run, as opposed
12290/// to evidence the command actually produced? A caller that would otherwise
12291/// read a resource-blocked outcome as a red command must check this first:
12292/// see [`Runner::gate`], which retries rather than records `Blocked` when
12293/// this is true.
12294fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12295    outcomes.iter().any(|o| o.resource_blocked)
12296}
12297
12298/// What [`Runner::gate_fix_round`] decided.
12299pub(crate) enum GateFix {
12300    /// The tree changed and `verify.e2e` is still green: run the gate again.
12301    Retry,
12302    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12303    /// last failure stands and the run ends blocked.
12304    Stop,
12305    /// `verify.e2e` could not run after the fix (magi's own contention):
12306    /// decide nothing now, a later reentry retries.
12307    Defer,
12308}
12309
12310/// Is every red command in `outcomes` an ordinary failure the code could
12311/// explain: it ran, exited non-zero, and said something?
12312///
12313/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12314/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12315/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12316/// what the command is stays the gate's business.
12317pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12318    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12319    red.peek().is_some()
12320        && red.all(|o| {
12321            !o.resource_blocked
12322                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12323                && !o.output_tail.trim().is_empty()
12324        })
12325}
12326
12327/// Describe one verify command's outcome for the event log, distinguishing a
12328/// build/link failure — the toolchain never produced a binary to run — from
12329/// an actual test failure, since only the latter is a verdict on the patch.
12330fn e2e_outcome_label(o: &CommandOutcome) -> String {
12331    if o.ok() {
12332        return "pass".to_owned();
12333    }
12334    let reason = if o.build_failed() {
12335        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12336    } else {
12337        format!("FAIL ({:?})", o.code)
12338    };
12339    format!(
12340        "{reason}\n{}",
12341        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12342    )
12343}
12344
12345/// Does `outcomes` hold a failure worth one more run on the same commit?
12346///
12347/// Only an ordinary test result qualifies: every red command ran, exited
12348/// non-zero and said which way (not a build/link failure, a timeout or kill,
12349/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12350/// evidence about the machine or the toolchain, never about a flaky test.
12351fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12352    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12353    red.peek().is_some()
12354        && !verify_inconclusive(outcomes)
12355        && red.all(|o| {
12356            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12357        })
12358}
12359
12360/// Said at the top of the output a fixer gets when the same command failed on
12361/// both attempts, so it reads as a reproduced failure and not a one-off.
12362const FAILED_TWICE: &str = "[this command failed twice on the same commit; the output below is \
12363                            the second attempt's]";
12364
12365/// Run `verify.e2e`, retrying once if the first attempt could not build or
12366/// link — a build/link failure is frequently a race against a shared
12367/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12368/// `verify` event per command, tagged with `context` (normally `"round N"`)
12369/// so the call sites that need this — the ordinary per-round leg in
12370/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12371/// will ever call a round green, `verify_current_head` and the gate-repair
12372/// check — read identically in the event log.
12373///
12374/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12375/// only after the failed commands have run once more on the same commit, in
12376/// the same worktree and — because the caller holds it around this whole
12377/// function — under the same cache lease, with a full `timeout` of their own
12378/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12379/// flake: the head is verified, the first failure is recorded and filed
12380/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12381/// stands, carrying the second attempt's output. One verification is therefore
12382/// run at most three times: the build/link retry, then this one rerun.
12383/// `round` is the review round the verification belongs to, if any.
12384async fn run_e2e_with_retry(
12385    state: &mut RunState,
12386    shell: &[String],
12387    commands: &[String],
12388    worktree: &Path,
12389    timeout: Duration,
12390    context: &str,
12391    round: Option<usize>,
12392) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12393    let (mut e2e, mut timed_out_pids) = run_commands(
12394        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12395    )
12396    .await;
12397    for o in &e2e {
12398        state.event(
12399            "verify",
12400            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12401        );
12402    }
12403    // A build/link failure is not a verdict on the patch — it is frequently a
12404    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12405    // one retry before letting a red like that decide the round.
12406    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12407    if verify_retried {
12408        state.event(
12409            "verify",
12410            format!(
12411                "{context}: verify could not build/link, not a test result — retrying once \
12412                 before concluding"
12413            ),
12414        );
12415        let retried = run_commands(
12416            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12417        )
12418        .await;
12419        e2e = retried.0;
12420        // Both attempts' timeouts matter, not just the last one: the first
12421        // attempt's descendants may still be alive alongside the retry's.
12422        timed_out_pids.extend(retried.1);
12423        for o in &e2e {
12424            state.event(
12425                "verify",
12426                format!(
12427                    "{context}: retry `{}` -> {}",
12428                    o.command,
12429                    e2e_outcome_label(o)
12430                ),
12431            );
12432        }
12433    }
12434    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12435        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12436        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12437        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12438        state.event(
12439            "verify",
12440            format!(
12441                "{context}: {} failed with a test result — running it once more on the same \
12442                 commit {} before deciding",
12443                rerun_commands
12444                    .iter()
12445                    .map(|c| format!("`{c}`"))
12446                    .collect::<Vec<_>>()
12447                    .join(", "),
12448                short(&head)
12449            ),
12450        );
12451        let (second, pids) = run_commands(
12452            state,
12453            "verify",
12454            "e2e",
12455            1 + usize::from(verify_retried),
12456            shell,
12457            &rerun_commands,
12458            worktree,
12459            timeout,
12460        )
12461        .await;
12462        timed_out_pids.extend(pids);
12463        for o in &second {
12464            state.event(
12465                "verify",
12466                format!(
12467                    "{context}: rerun `{}` -> {}",
12468                    o.command,
12469                    e2e_outcome_label(o)
12470                ),
12471            );
12472        }
12473        let mut reproduced = false;
12474        for (slot, &i) in failed.iter().enumerate() {
12475            let Some(again) = second.get(slot) else {
12476                break;
12477            };
12478            let first = std::mem::replace(&mut e2e[i], again.clone());
12479            if again.ok() {
12480                let signature = crate::flake::signature(&first.output_tail, first.code);
12481                let flake = crate::run::VerifyFlake {
12482                    round,
12483                    context: context.to_owned(),
12484                    head: head.clone(),
12485                    command: first.command.clone(),
12486                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12487                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12488                    at: Timestamp::now(),
12489                    task: None,
12490                    filed: false,
12491                    filing_error: None,
12492                };
12493                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12494            } else if !again.resource_blocked {
12495                reproduced = true;
12496                e2e[i].output_tail = format!("{FAILED_TWICE}\n{}", again.output_tail);
12497            }
12498        }
12499        if reproduced {
12500            state.event(
12501                "verify",
12502                format!("{context}: the failure reproduced on the second run — it stands"),
12503            );
12504        }
12505    }
12506    (e2e, verify_retried, timed_out_pids)
12507}
12508
12509/// Run configured shell commands in `cwd`, in order. The second element is
12510/// the pid of every command that hit `timeout` and was still running when
12511/// this stopped waiting on it (best-effort: `None` when the platform did not
12512/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12513/// that releases a shared resource afterward needs to know.
12514///
12515/// Records `task` into [`RunState::active`] at every command boundary
12516/// (`RunState::task_command`) and clears it once the whole list has run
12517/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12518/// for minutes with no seat and no output of its own to show for it (see
12519/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12520/// apart from "not yet run" without this), and this is the only place that
12521/// knows which command is running right now and how many are left. Three
12522/// saves per command — start, not per second — matching the same "only at a
12523/// boundary" rule [`wave`] already follows for seats.
12524#[allow(clippy::too_many_arguments)]
12525async fn run_commands(
12526    state: &mut RunState,
12527    node: &str,
12528    task: &str,
12529    attempt: usize,
12530    shell: &[String],
12531    commands: &[String],
12532    cwd: &Path,
12533    timeout: Duration,
12534) -> (Vec<CommandOutcome>, Vec<u32>) {
12535    let isolated = crate::build_target::isolated(&state.config);
12536    if isolated && let Some(block) = &state.resource_block {
12537        return (
12538            vec![CommandOutcome {
12539                command: "(isolated build admission)".into(),
12540                code: None,
12541                output_tail: block.description(),
12542                duration_ms: 0,
12543                resource_blocked: true,
12544            }],
12545            Vec::new(),
12546        );
12547    }
12548    if commands.is_empty() {
12549        // Nothing to mark as running and nothing to clear — an empty list
12550        // means "not configured", and touching `active` (or the disk) over
12551        // that would be a write for every round of a repo with no
12552        // `verify.e2e` / `verify.gate` commands at all.
12553        return (Vec::new(), Vec::new());
12554    }
12555    let mut out = Vec::new();
12556    let mut timed_out_pids = Vec::new();
12557    let total = commands.len();
12558    for (idx, command) in commands.iter().enumerate() {
12559        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12560        if let Err(e) = state.save() {
12561            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12562        }
12563        let started = Instant::now();
12564        let mut cmd = tokio::process::Command::new(&shell[0]);
12565        cmd.quiet();
12566        // Verify the checkout as a standalone caller. Worker ownership and
12567        // pinned executable selection belong to this driver, not to tests or
12568        // tools it runs. Preserve home/seat context and Running's containment.
12569        for key in crate::worker::INVOCATION_ENV {
12570            cmd.env_remove(key);
12571        }
12572        cmd.env_remove(crate::build_id::EXPECT_ENV);
12573        cmd.args(&shell[1..])
12574            .current_dir(cwd)
12575            .stdin(std::process::Stdio::null())
12576            .stdout(std::process::Stdio::piped())
12577            .stderr(std::process::Stdio::piped())
12578            .kill_on_drop(true);
12579        let mut outputs = Vec::new();
12580        let mut cache = None;
12581        let home = crate::run::home();
12582        let head = if isolated {
12583            Some(git::rev_parse(cwd, "HEAD").await)
12584        } else {
12585            None
12586        };
12587        let protected = (|| -> Result<()> {
12588            crate::incremental::configure(&mut cmd, cwd)?;
12589            cache = if isolated {
12590                let target = VERIFY_TARGET
12591                    .try_with(Clone::clone)
12592                    .context("isolated verification has no target lease")?;
12593                cmd.arg(crate::build_target::command::normalize(command)?);
12594                crate::build_target::command::configure(&mut cmd, &target)?;
12595                Some(target)
12596            } else {
12597                crate::build_target::command::clear(&mut cmd)?;
12598                cmd.arg(command);
12599                state.config.cache_dir()
12600            };
12601            let mut paths = vec![cwd.to_owned()];
12602            if let Some(cache) = &cache {
12603                paths.push(cache.clone());
12604            }
12605            let admit = if isolated {
12606                crate::retention::OutputLease::admit_isolated
12607            } else {
12608                crate::retention::OutputLease::admit
12609            };
12610            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12611            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12612                outputs.push(guard);
12613            }
12614            if let Some(cache) = &cache {
12615                outputs.push(crate::retention::OutputLease::cache(
12616                    &crate::run::home(),
12617                    cache,
12618                    false,
12619                )?);
12620                if let Some(head) = head {
12621                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12622                    if task == "pre_gate" {
12623                        crate::cache::invalidate_identity(&home, cache);
12624                    }
12625                }
12626            }
12627            Ok(())
12628        })();
12629        if let Err(e) = protected {
12630            let detail = format!("execution admission unavailable: {e:#}");
12631            state.resource_block = Some(crate::run::ResourceBlock {
12632                cause: crate::run::ResourceBlockCause::Other,
12633                node: node.to_owned(),
12634                kind: if detail.contains("disk admission") {
12635                    "disk admission"
12636                } else {
12637                    "output ownership"
12638                }
12639                .to_owned(),
12640                detail: detail.clone(),
12641                at: Timestamp::now(),
12642            });
12643            out.push(CommandOutcome {
12644                command: command.clone(),
12645                code: None,
12646                output_tail: detail,
12647                duration_ms: 0,
12648                resource_blocked: true,
12649            });
12650            break;
12651        }
12652        let spawned = if isolated {
12653            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12654        } else {
12655            crate::seat_process::Running::spawn(cmd, None, outputs)
12656        };
12657        let (code, body) = match spawned {
12658            Ok(mut running) => {
12659                let pid = running.child().id();
12660                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12661                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12662                let mut paths = vec![cwd.to_owned()];
12663                if let Some(cache) = cache {
12664                    paths.push(cache);
12665                }
12666                let mut pressure = None;
12667                let status = tokio::select! {
12668                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12669                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12670                        pressure = Some(reason); None
12671                    }
12672                };
12673                let (code, failure) = match status {
12674                    Some(Ok(Ok(status))) => (
12675                        status.code(),
12676                        status
12677                            .code()
12678                            .is_none()
12679                            .then(|| format!("command terminated: {status}")),
12680                    ),
12681                    Some(Ok(Err(error))) => {
12682                        (None, Some(format!("failed waiting for command: {error}")))
12683                    }
12684                    Some(Err(_)) => {
12685                        // Leased cleanup confirms process-tree death itself.
12686                        // Unleased commands still need the caller's PID check
12687                        // after kill-on-drop, before releasing cache ownership.
12688                        if !running.coordinated()
12689                            && let Some(pid) = pid
12690                        {
12691                            timed_out_pids.push(pid);
12692                        }
12693                        (
12694                            None,
12695                            Some(format!("timed out after {}s", timeout.as_secs())),
12696                        )
12697                    }
12698                    None => (None, None),
12699                };
12700                running.finish().await;
12701                if let Some(reason) = pressure {
12702                    state.resource_block = Some(crate::run::ResourceBlock {
12703                        cause: crate::run::ResourceBlockCause::Other,
12704                        node: node.to_owned(),
12705                        kind: "disk pressure".to_owned(),
12706                        detail: reason.clone(),
12707                        at: Timestamp::now(),
12708                    });
12709                    out.push(CommandOutcome {
12710                        command: command.clone(),
12711                        code: None,
12712                        output_tail: reason,
12713                        duration_ms: started.elapsed().as_millis() as u64,
12714                        resource_blocked: true,
12715                    });
12716                    break;
12717                }
12718                let mut body = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12719                body.push_str(&agent::collect(&stderr, err_reader, Duration::from_secs(2)).await);
12720                if let Some(failure) = failure {
12721                    body.push('\n');
12722                    body.push_str(&failure);
12723                }
12724                (code, body)
12725            }
12726            Err(e) if isolated => {
12727                let e = anyhow::Error::new(e)
12728                    .context(format!("could not start managed build `{}`", shell[0]));
12729                record_cache_error(state, node, &e);
12730                out.push(CommandOutcome {
12731                    command: command.clone(),
12732                    code: None,
12733                    output_tail: format!("{e:#}"),
12734                    duration_ms: 0,
12735                    resource_blocked: true,
12736                });
12737                break;
12738            }
12739            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
12740        };
12741        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12742        if !body.is_empty() {
12743            // The full text is kept whatever the summary dropped. A fresh
12744            // name per command so a resume or retry never overwrites an
12745            // earlier run's output. A failed write changes no verdict.
12746            match crate::run::write_verification_artifact(state, task, &body) {
12747                Ok(name) if summary != body => {
12748                    summary = format!("[full output: artifacts/{name}]\n{summary}");
12749                }
12750                Ok(_) => {}
12751                Err(e) => {
12752                    let warning = format!("could not save the full {task} output: {e:#}");
12753                    tracing::warn!("{warning}");
12754                    state.event(node, warning);
12755                    if summary != body {
12756                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12757                    }
12758                }
12759            }
12760        }
12761        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12762        out.push(CommandOutcome {
12763            command: command.clone(),
12764            code,
12765            output_tail: summary,
12766            duration_ms: started.elapsed().as_millis() as u64,
12767            resource_blocked,
12768        });
12769        if resource_blocked {
12770            state.resource_block = Some(crate::run::ResourceBlock {
12771                cause: crate::run::ResourceBlockCause::Other,
12772                node: node.to_owned(),
12773                kind: "incremental cache admission".into(),
12774                detail: body,
12775                at: Timestamp::now(),
12776            });
12777            break;
12778        }
12779    }
12780    state.task_finished(task);
12781    if let Err(e) = state.save() {
12782        tracing::warn!("could not persist the end of {task}: {e:#}");
12783    }
12784    (out, timed_out_pids)
12785}
12786
12787/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12788/// section (`report::run`) and in the `merge` event this node records — for
12789/// the operator to run by hand.
12790///
12791/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12792/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12793/// merge commits", or "require linear history") rejects the push a `--no-ff`
12794/// merge would produce, which is exactly the guidance this function replaces.
12795/// `message`'s first line becomes the squash commit's subject, matching the
12796/// note `report::run` prints alongside this command — see that function for
12797/// why an explicit subject is not optional there.
12798fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12799    let repo = repo.display();
12800    match style {
12801        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12802        MergeStyle::Squash => {
12803            // The subject sits inside double quotes, and a title an agent
12804            // wrote may carry the characters that break out of them.
12805            let subject = message
12806                .lines()
12807                .next()
12808                .unwrap_or(branch)
12809                .replace(['\\', '"', '$', '`'], "");
12810            format!(
12811                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12812            )
12813        }
12814        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12815    }
12816}
12817
12818/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12819/// under the hood, rejects a `title` over 256 characters and the whole
12820/// command fails — no PR at all, for a run whose body was otherwise fine
12821/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12822/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12823/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12824/// this bound. It is a margin, not a guarantee — a title packed
12825/// with multi-unit characters could still in principle land close to the
12826/// edge, but a real task title's occasional emoji or accented letter fits
12827/// comfortably inside it.
12828const PR_TITLE_MAX: usize = 240;
12829
12830/// A pull request title from the opening line of `text`, or `None` when that
12831/// line is not English (GitHub text is) or has no letters.
12832///
12833/// A line within `max` is kept as is. A longer one is cut at the end of its
12834/// first sentence when that falls inside `max`, else at a word boundary with a
12835/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
12836/// make every merely-truncated title look non-English). The language check
12837/// runs on the kept text before any mark is added, so only what GitHub will
12838/// show is judged: an English opening followed by non-ASCII far past the cut
12839/// still passes.
12840fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
12841    let line = queue::first_line(text)?;
12842    let chars: Vec<char> = line.chars().collect();
12843    let (kept, mark) = if chars.len() <= max {
12844        (line.to_owned(), "")
12845    } else if let Some(end) = sentence_end(&chars, max) {
12846        (chars[..end].iter().collect::<String>(), "")
12847    } else {
12848        let room = max.saturating_sub(3);
12849        // Cut at the last space inside the room; when the char just past the
12850        // room is a space the room already ends on a word.
12851        let cut = if chars[room].is_whitespace() {
12852            room
12853        } else {
12854            chars[..room]
12855                .iter()
12856                .rposition(|c| c.is_whitespace())
12857                .unwrap_or(room)
12858        };
12859        let head: String = chars[..cut].iter().collect();
12860        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
12861        (head.to_owned(), "...")
12862    };
12863    if kept.is_empty() {
12864        return None;
12865    }
12866    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
12867        return None;
12868    }
12869    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
12870        return None;
12871    }
12872    Some(format!("{kept}{mark}"))
12873}
12874
12875/// The char length of the first sentence of `chars` when it ends within `max`
12876/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
12877/// abbreviations so `e.g. foo` does not end a title early.
12878fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
12879    const MIN: usize = 20;
12880    for i in MIN..max.min(chars.len()) {
12881        if !matches!(chars[i], '.' | '!' | '?') {
12882            continue;
12883        }
12884        let Some(&next) = chars.get(i + 1) else {
12885            continue;
12886        };
12887        if !next.is_whitespace() {
12888            continue;
12889        }
12890        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
12891        if after.is_some_and(|c| c.is_ascii_lowercase()) {
12892            continue;
12893        }
12894        let word: String = chars[..i]
12895            .iter()
12896            .rev()
12897            .take_while(|c| !c.is_whitespace())
12898            .collect::<Vec<_>>()
12899            .into_iter()
12900            .rev()
12901            .collect();
12902        let word = word.to_ascii_lowercase();
12903        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
12904            continue;
12905        }
12906        let end = chars[..i]
12907            .iter()
12908            .rposition(|c| !c.is_whitespace())
12909            .map_or(i, |p| p + 1);
12910        return Some(end);
12911    }
12912    None
12913}
12914
12915/// What `merge = "pr"` (and the merge commit of the other modes) says about a
12916/// change: a title and a body describing what was *implemented*, not the task
12917/// that asked for it. A task reads as a request; a reader of the merged
12918/// history wants the change.
12919struct PrMessage {
12920    title: String,
12921    body: String,
12922}
12923
12924impl PrMessage {
12925    /// Title, blank line, body. The first line is the squash/merge commit
12926    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
12927    /// has to stay one sensible line.
12928    fn commit_message(&self) -> String {
12929        format!("{}\n\n{}", self.title, self.body)
12930    }
12931}
12932
12933/// The text after a leading `TITLE:` (any case) on `line`.
12934fn title_marker(line: &str) -> Option<&str> {
12935    let line = line.trim();
12936    let head = line.get(..6)?;
12937    head.eq_ignore_ascii_case("title:")
12938        .then(|| line[6..].trim())
12939}
12940
12941/// The implementer's own one-line title: the `TITLE:` line the implement
12942/// prompt asks for at the top of its SUMMARY. Candidate commits are all
12943/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
12944/// source, and a title that says as much is refused here too.
12945fn summary_title(summary: &str) -> Option<String> {
12946    let first = summary.lines().find(|l| !l.trim().is_empty())?;
12947    let raw = title_marker(first)?;
12948    if raw.is_empty() {
12949        return None;
12950    }
12951    let title = queue::title_from(raw, PR_TITLE_MAX);
12952    let lower = title.to_ascii_lowercase();
12953    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12954        return None;
12955    }
12956    Some(title)
12957}
12958
12959/// How `open_review`'s instruction begins; see [`landing_title`].
12960const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
12961
12962/// Marker `open_review` gives a candidate that nothing in the roster wrote.
12963pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
12964
12965/// Does this run review work that already existed, rather than implement a
12966/// task? Runs recorded before `reviewed_commits` existed carry only the
12967/// candidate marker.
12968pub(crate) fn is_review_run(state: &RunState) -> bool {
12969    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
12970}
12971
12972/// The title of a review-only run: the subject of the oldest commit under
12973/// review. Later commits are usually fixups, and `instruction` is the review
12974/// prompt, which says nothing about the change. GitHub text is English, so a
12975/// non-ASCII or blank subject yields `None` and the caller's neutral title.
12976fn review_title(state: &RunState) -> Option<String> {
12977    english_subject(
12978        state.reviewed_commits.as_ref()?.first()?,
12979        state.config.graph.github_english(),
12980    )
12981}
12982
12983/// `raw` as a pull request title, or `None` when it is blank, not English
12984/// (GitHub text is), or one of magi's own candidate commit subjects.
12985fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
12986    let raw = raw.trim();
12987    if raw.is_empty() {
12988        return None;
12989    }
12990    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
12991        return None;
12992    }
12993    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
12994        return None;
12995    }
12996    let title = queue::title_from(raw, PR_TITLE_MAX);
12997    let lower = title.to_ascii_lowercase();
12998    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12999        return None;
13000    }
13001    Some(title)
13002}
13003
13004/// What a review-only run's branch says about itself, read at the moment the
13005/// pull request is opened.
13006#[derive(Debug, Clone, PartialEq, Eq)]
13007struct BranchFacts {
13008    /// `(subject, body)` of each commit, oldest first.
13009    commits: Vec<(String, String)>,
13010    /// Trimmed `git diff --stat`.
13011    stat: String,
13012}
13013
13014/// Longest diff stat shown: this many file lines plus the summary line.
13015const STAT_FILE_LINES: usize = 25;
13016/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13017const COMMITS_MAX_CHARS: usize = 20_000;
13018
13019/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13020/// say or finds nothing, so the caller falls back to what the run recorded.
13021async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13022    let commits = git::commit_log(repo, base, branch).await.ok()?;
13023    if commits.is_empty() {
13024        return None;
13025    }
13026    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13027    let lines: Vec<&str> = stat.lines().collect();
13028    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13029        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13030        let more = format!(" ... {omitted} more file(s)");
13031        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13032        kept.push(&more);
13033        kept.push(lines[lines.len() - 1]);
13034        kept.join("\n")
13035    } else {
13036        lines.join("\n")
13037    };
13038    Some(BranchFacts { commits, stat })
13039}
13040
13041/// Defang what would break the surrounding markdown: a closing `</details>`
13042/// and a code fence.
13043fn markdown_safe(text: &str) -> String {
13044    text.replace("</details>", "&lt;/details&gt;")
13045        .replace("\x60\x60\x60", "~~~")
13046}
13047
13048fn neutral_title(state: &RunState, winner: char) -> String {
13049    format!(
13050        "chore: land candidate {} of run {}",
13051        winner.to_ascii_uppercase(),
13052        state.id
13053    )
13054}
13055
13056/// Reuse the graph's bounded fixer without starting another graph or driver.
13057/// Copy the working state back even on errors so spent rounds remain visible.
13058pub(crate) async fn repair_landing_gate(
13059    state: &mut RunState,
13060    winner: &Candidate,
13061    outcomes: &[CommandOutcome],
13062) -> Result<GateFix> {
13063    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13064        return Ok(GateFix::Stop);
13065    }
13066    let mut runner = Runner {
13067        roles: state.config.resolve_roles()?,
13068        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13069        state: state.clone(),
13070        pause: Pause::new(),
13071        interrupt: Pause::new(),
13072    };
13073    let result = runner.gate_fix_round(winner, outcomes).await;
13074    *state = runner.state;
13075    result
13076}
13077
13078/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13079/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13080pub(crate) async fn verify_current_head(
13081    state: &mut RunState,
13082    winner: &Candidate,
13083    wait: &crate::repo_lock::WaitPolicy,
13084) -> Result<bool> {
13085    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13086    // Preserve the previous record before replacing it, including on crash recovery.
13087    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13088        state
13089            .verification_history
13090            .push(crate::run::VerificationEvidence {
13091                superseded_by: Some(head.clone()),
13092                archived_at: Some(Timestamp::now()),
13093                fixes_spent: Some(state.gate_fixes.len()),
13094                gate_head: None,
13095                gate_ran: false,
13096                gate: Vec::new(),
13097                e2e: state.head_e2e.take(),
13098            });
13099    }
13100    if let Some(e) = &state.head_e2e
13101        && e.head == head
13102    {
13103        if e.passed {
13104            return Ok(true);
13105        }
13106        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13107            state.status = RunStatus::Blocked;
13108            state.save()?;
13109            return Ok(false);
13110        }
13111    } else if state.reviews.last().is_some_and(|r| {
13112        r.verified_head.as_deref() == Some(head.as_str())
13113            && (r.e2e_status() == E2eStatus::Passed
13114                || (r.e2e_status() == E2eStatus::NotConfigured
13115                    && state.config.verify.e2e.is_empty()))
13116    }) || state
13117        .gate_repair_e2e
13118        .as_ref()
13119        .is_some_and(|e| e.head == head && e.passed)
13120    {
13121        return Ok(true);
13122    }
13123    if let Some(e) = &state.gate_repair_e2e
13124        && e.head == head
13125        && !e.passed
13126        && !e.outcomes.is_empty()
13127        && !verify_inconclusive(&e.outcomes)
13128    {
13129        state.status = RunStatus::Blocked;
13130        state.save()?;
13131        return Ok(false);
13132    }
13133    state.head_e2e = Some(crate::run::GateRepairE2e {
13134        head: head.clone(),
13135        passed: false,
13136        outcomes: Vec::new(),
13137    });
13138    state.save()?;
13139    let commands = state.config.verify.e2e.clone();
13140    let shell = state.config.shell();
13141    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13142    let cache_dir = state.config.cache_dir();
13143    let outcomes = if commands.is_empty() {
13144        Vec::new()
13145    } else {
13146        let (outcomes, _) = with_cache_lease(
13147            state,
13148            cache_dir.as_deref(),
13149            "e2e",
13150            "e2e",
13151            &winner.worktree,
13152            &head,
13153            timeout,
13154            "current head e2e",
13155            wait,
13156            |state, budget| async move {
13157                run_e2e_with_retry(
13158                    state,
13159                    &shell,
13160                    &commands,
13161                    &winner.worktree,
13162                    budget,
13163                    "current head e2e",
13164                    None,
13165                )
13166                .await
13167            },
13168        )
13169        .await?;
13170        outcomes
13171    };
13172    let unresolved = verify_inconclusive(&outcomes);
13173    let passed = !unresolved
13174        && outcomes.iter().all(CommandOutcome::ok)
13175        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13176    if !outcomes.is_empty() && !unresolved {
13177        state.record_base_progress(&head);
13178    }
13179    state.head_e2e = Some(crate::run::GateRepairE2e {
13180        head: head.clone(),
13181        passed,
13182        outcomes,
13183    });
13184    if !passed && !unresolved {
13185        state.status = RunStatus::Blocked;
13186        state.event(
13187            "e2e",
13188            format!("verify.e2e failed on head {head}; nothing published"),
13189        );
13190    }
13191    state.save()?;
13192    Ok(passed)
13193}
13194
13195/// Recheck a repair's e2e requirement across failures, resource deferrals and
13196/// process interruptions. A successful result only applies to its exact SHA.
13197pub(crate) async fn check_gate_repair_e2e(
13198    state: &mut RunState,
13199    winner: &Candidate,
13200    wait: &crate::repo_lock::WaitPolicy,
13201) -> Result<GateFix> {
13202    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13203        return Ok(GateFix::Retry);
13204    }
13205    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13206    if state
13207        .gate_repair_e2e
13208        .as_ref()
13209        .is_some_and(|r| r.head == head && r.passed)
13210    {
13211        return Ok(GateFix::Retry);
13212    }
13213    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13214        head: head.clone(),
13215        passed: false,
13216        outcomes: Vec::new(),
13217    });
13218    state.save()?;
13219    let commands = state.config.verify.e2e.clone();
13220    let outcomes = if commands.is_empty() {
13221        Vec::new()
13222    } else {
13223        let shell = state.config.shell();
13224        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13225        let cache_dir = state.config.cache_dir();
13226        let (outcomes, _) = with_cache_lease(
13227            state,
13228            cache_dir.as_deref(),
13229            "e2e",
13230            "e2e",
13231            &winner.worktree,
13232            &head,
13233            timeout,
13234            "gate repair e2e",
13235            wait,
13236            |state, budget| async move {
13237                run_e2e_with_retry(
13238                    state,
13239                    &shell,
13240                    &commands,
13241                    &winner.worktree,
13242                    budget,
13243                    "gate repair e2e",
13244                    None,
13245                )
13246                .await
13247            },
13248        )
13249        .await?;
13250        outcomes
13251    };
13252    let deferred = verify_inconclusive(&outcomes);
13253    let passed = outcomes.iter().all(CommandOutcome::ok)
13254        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13255    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13256        head,
13257        passed,
13258        outcomes,
13259    });
13260    state.save()?;
13261    if deferred {
13262        Ok(GateFix::Defer)
13263    } else if !passed {
13264        state.event(
13265            "gate",
13266            "verify.e2e failed after gate repair; nothing published",
13267        );
13268        Ok(GateFix::Stop)
13269    } else {
13270        Ok(GateFix::Retry)
13271    }
13272}
13273
13274/// Run the same configured gate for a landing head and a fresh graph.
13275pub(crate) async fn run_landing_gate(
13276    state: &mut RunState,
13277    winner: &Candidate,
13278    wait: &crate::repo_lock::WaitPolicy,
13279) -> Result<Vec<CommandOutcome>> {
13280    let shell = state.config.shell();
13281    let gate_commands = state.config.verify.gate.clone();
13282    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13283    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13284        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13285        Vec::new()
13286    } else {
13287        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13288        let cache_dir = state.config.cache_dir();
13289        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13290        let (outcomes, _) = with_cache_lease(
13291            state,
13292            cache_dir.as_deref(),
13293            "gate",
13294            "gate",
13295            &winner.worktree,
13296            &head,
13297            timeout,
13298            "final gate",
13299            wait,
13300            |state, budget| {
13301                let shell = shell.clone();
13302                let gate_commands = gate_commands.clone();
13303                let winner = winner.clone();
13304                async move {
13305                    Runner::run_pre_gate(state, &winner).await;
13306                    // Bind command evidence after mechanical fixes, before commands start.
13307                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13308                    let (outcomes, timed_out_pids) = run_commands(
13309                        state,
13310                        "gate",
13311                        "gate",
13312                        0,
13313                        &shell,
13314                        &gate_commands,
13315                        &winner.worktree,
13316                        budget,
13317                    )
13318                    .await;
13319                    (outcomes, false, timed_out_pids)
13320                }
13321            },
13322        )
13323        .await?;
13324        outcomes
13325    };
13326    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13327    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13328        let mut outcomes = outcomes;
13329        outcomes.push(CommandOutcome {
13330            command: "gate head stability".into(), code: None,
13331            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13332            duration_ms: 0, resource_blocked: false,
13333        });
13334        return Ok(outcomes);
13335    }
13336    if outcomes.is_empty() {
13337        // Nothing configured to check — distinct from every other
13338        // silence in this run's event log, since an empty `gate` alone
13339        // no longer says whether the gate ran at all (see
13340        // `RunState::gate_ran`'s own doc).
13341        state.event("gate", "no gate commands configured; not tested");
13342    }
13343    for o in &outcomes {
13344        state.event(
13345            "gate",
13346            format!(
13347                "`{}` -> {}",
13348                o.command,
13349                if o.ok() {
13350                    "pass".to_owned()
13351                } else {
13352                    format!(
13353                        "FAIL ({:?})\n{}",
13354                        o.code,
13355                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13356                    )
13357                }
13358            ),
13359        );
13360    }
13361    Ok(outcomes)
13362}
13363
13364/// The pull request title to hand to `land::merge_subject`. A review-only run
13365/// opened by an earlier build titled its pull request with the review prompt;
13366/// that title is dropped (empty, so the fallback applies) rather than landed.
13367/// Any other title, including an operator's rename, passes through untouched,
13368/// and so does every title of a run that implements a task.
13369pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13370    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13371        ""
13372    } else {
13373        pr_title
13374    }
13375}
13376
13377/// What the squash subject falls back to when the pull request title is empty
13378/// or candidate-shaped: for a review-only run the derived title, never the
13379/// review prompt held in `instruction`.
13380pub fn landing_subject_source(state: &RunState) -> String {
13381    if is_review_run(state) {
13382        let winner = state.candidates.first().map_or('A', |c| c.label);
13383        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13384    }
13385    state.instruction.clone()
13386}
13387
13388/// `summary` without its `TITLE:` line, which the pull request title already
13389/// carries.
13390fn summary_without_title(summary: &str) -> String {
13391    let mut lines = summary.trim().lines().peekable();
13392    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13393        lines.next();
13394    }
13395    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13396}
13397
13398/// The pull request title and body for the winning candidate.
13399///
13400/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13401/// the task's own opening line via [`queue::title_from`] when there is none.
13402/// `state.instruction` can open with blank lines (`task_text` only rejects a
13403/// body that is blank *entirely*), which `title_from` skips.
13404///
13405/// Publishing uses an independent description generated from the final diff
13406/// and structured evidence. Internal summaries and reports remain local.
13407/// Non-publishing previews may display the original task and candidate summary.
13408/// The footer retains the run and candidate provenance.
13409#[cfg(test)]
13410fn pr_message(state: &RunState, winner: char) -> PrMessage {
13411    pr_message_with(state, winner, None)
13412}
13413
13414/// [`pr_message`] with what the branch of a review-only run says about itself.
13415/// `facts` is ignored for a run that implements a task.
13416#[cfg(test)]
13417fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13418    let raw = pr_message_raw(
13419        state,
13420        winner,
13421        facts,
13422        crate::pr_outcome::FinalHead::Unreported,
13423        ChangeNote::NotAsked,
13424    );
13425    let id = crate::scrub::Identity::current();
13426    PrMessage {
13427        title: crate::scrub::scrub(&raw.title, &id),
13428        body: crate::scrub::scrub(&raw.body, &id),
13429    }
13430}
13431
13432/// What the public description may say about the change itself.
13433#[derive(Debug, Clone, Copy)]
13434enum ChangeNote<'a> {
13435    /// A local preview or non-publishing merge mode: no public generation needed.
13436    NotAsked,
13437    /// A summary written from the final diff.
13438    Summary(&'a crate::run::ChangeSummary),
13439    /// A summary was asked for and could not be produced; the text says why.
13440    Unavailable(&'a str),
13441}
13442
13443fn pr_message_raw(
13444    state: &RunState,
13445    winner: char,
13446    facts: Option<&BranchFacts>,
13447    head: crate::pr_outcome::FinalHead<'_>,
13448    change: ChangeNote<'_>,
13449) -> PrMessage {
13450    if !matches!(change, ChangeNote::NotAsked) {
13451        let (title, mut body) = match change {
13452            ChangeNote::Summary(c) => (
13453                c.title.clone(),
13454                format!("## Summary\n\n{}\n\n", c.body.trim()),
13455            ),
13456            ChangeNote::Unavailable(why) => (
13457                neutral_title(state, winner),
13458                format!(
13459                    "## 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"
13460                ),
13461            ),
13462            ChangeNote::NotAsked => unreachable!(),
13463        };
13464        body.push_str(&public_pr_evidence(state, head));
13465        body.push_str(&format!(
13466            "\n---\nmagi:run/{} magi:candidate-{}\n",
13467            state.id,
13468            winner.to_ascii_lowercase()
13469        ));
13470        return PrMessage { title, body };
13471    }
13472    pr_preview(state, winner, facts, head)
13473}
13474
13475/// Append public facts from the run records after every prose generation,
13476/// including posting-gate rewrites. The agent cannot drop this provenance.
13477fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13478    let mut body = crate::pr_outcome::review_rounds(state);
13479    body.push_str(&crate::pr_outcome::final_verification(state, head));
13480    let open = state.last_round_findings();
13481    if !open.is_empty() {
13482        body.push_str("## Open review findings\n\n");
13483        for f in open {
13484            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13485        }
13486        body.push('\n');
13487    }
13488    if let Some(c) = state.change_summary.as_ref()
13489        && head == crate::pr_outcome::FinalHead::At(&c.head)
13490    {
13491        body.push_str(&format!(
13492            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13493            c.base, c.head
13494        ));
13495    }
13496    body
13497}
13498
13499/// Local-only preview of the operator's task and candidate summary.
13500fn pr_preview(
13501    state: &RunState,
13502    winner: char,
13503    facts: Option<&BranchFacts>,
13504    head: crate::pr_outcome::FinalHead<'_>,
13505) -> PrMessage {
13506    let summary = state
13507        .candidates
13508        .iter()
13509        .find(|c| c.label == winner)
13510        .map(|c| c.summary.as_str())
13511        .unwrap_or_default();
13512    // The fallback is the operator's own words and may not be English; GitHub
13513    // text always is, so a non-English task gets a neutral title instead.
13514    let review = is_review_run(state);
13515    let title = if review {
13516        facts
13517            .and_then(|f| {
13518                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13519            })
13520            .or_else(|| review_title(state))
13521            .or_else(|| {
13522                state
13523                    .candidates
13524                    .iter()
13525                    .find(|c| c.label == winner)
13526                    .filter(|c| !c.branch.starts_with("magi/"))
13527                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13528            })
13529            .unwrap_or_else(|| neutral_title(state, winner))
13530    } else {
13531        summary_title(summary).unwrap_or_else(|| {
13532            english_title(
13533                &state.instruction,
13534                PR_TITLE_MAX,
13535                state.config.graph.github_english(),
13536            )
13537            .unwrap_or_else(|| neutral_title(state, winner))
13538        })
13539    };
13540
13541    let mut body = String::new();
13542    let what = summary_without_title(summary);
13543    if !what.is_empty() {
13544        body.push_str("## Summary\n\n");
13545        body.push_str(&what);
13546        body.push_str("\n\n");
13547    }
13548
13549    // Review history uses structured facts across all rounds, never reports.
13550    body.push_str(&crate::pr_outcome::review_rounds(state));
13551    body.push_str(&crate::pr_outcome::final_verification(state, head));
13552    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13553
13554    let open = state.open_findings();
13555    if !open.is_empty() {
13556        body.push_str("## Open review findings\n\n");
13557        for f in &open {
13558            body.push_str(&format!(
13559                "- `{}` [{:?}] {}\n",
13560                f.id, f.severity, "Context retained in local review records."
13561            ));
13562        }
13563        body.push('\n');
13564    }
13565
13566    if let Some(fix) = fix
13567        && !fix.rejected.is_empty()
13568    {
13569        body.push_str("## Declined by the fixer\n\n");
13570        for r in &fix.rejected {
13571            body.push_str(&format!(
13572                "- `{}`: {}\n",
13573                r.id, "Reason retained in local review records."
13574            ));
13575        }
13576        body.push('\n');
13577    }
13578
13579    if review {
13580        // The review prompt is not the task; list what the branch carries.
13581        body.push_str("## Commits under review\n\n");
13582        if let Some(facts) = facts {
13583            let mut left = COMMITS_MAX_CHARS;
13584            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13585                let mut entry = format!("- {}\n", markdown_safe(subject));
13586                for l in markdown_safe(text).lines() {
13587                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13588                }
13589                if left == 0 {
13590                    body.push_str(&format!(
13591                        "- ... {} more commit(s)\n",
13592                        facts.commits.len() - i
13593                    ));
13594                    break;
13595                }
13596                if entry.len() > left {
13597                    // Even the first commit is cut: one huge body must not
13598                    // push the whole description past GitHub's limit.
13599                    let mut end = left;
13600                    while !entry.is_char_boundary(end) {
13601                        end -= 1;
13602                    }
13603                    entry.truncate(end);
13604                    entry.push_str("\n  ... (truncated)\n");
13605                    left = 0;
13606                } else {
13607                    left -= entry.len();
13608                }
13609                body.push_str(&entry);
13610            }
13611            if !facts.stat.trim().is_empty() {
13612                body.push_str(&format!(
13613                    "\n## Diff stat\n\n```\n{}\n```\n",
13614                    markdown_safe(facts.stat.trim())
13615                ));
13616            }
13617        } else {
13618            match &state.reviewed_commits {
13619                Some(subjects) => {
13620                    for s in subjects {
13621                        body.push_str(&format!("- {}\n", s.trim()));
13622                    }
13623                }
13624                None => {
13625                    // An older run kept only the prompt, with the commit list
13626                    // after its first paragraph.
13627                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13628                    body.push_str(rest.trim());
13629                    body.push('\n');
13630                }
13631            }
13632        }
13633    } else {
13634        let task = state.instruction.trim();
13635        let task = if task.is_empty() {
13636            "(empty task)"
13637        } else {
13638            task
13639        };
13640        body.push_str(&format!(
13641            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13642            task.replace("</details>", "&lt;/details&gt;")
13643        ));
13644    }
13645
13646    body.push_str(&format!(
13647        "\n---\nmagi:run/{} magi:candidate-{}\n",
13648        state.id,
13649        winner.to_ascii_lowercase()
13650    ));
13651
13652    PrMessage { title, body }
13653}
13654
13655/// Source imports have already been prepared from structured inputs. Legacy
13656/// inferred references must never instruct a seat to reconstruct those imports.
13657fn seeded_instruction(state: &RunState) -> String {
13658    let mut inputs = Vec::new();
13659    if let Some(start) = &state.sources.start_from {
13660        inputs.push(format!(
13661            "Start from `{}` at `{}` (including ancestry).",
13662            start.token, start.sha
13663        ));
13664    }
13665    for pick in &state.sources.pick_commits {
13666        inputs.push(format!(
13667            "Pick `{}` at `{}` (single commit).",
13668            pick.token, pick.sha
13669        ));
13670    }
13671    if inputs.is_empty() {
13672        state.instruction.clone()
13673    } else {
13674        format!(
13675            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13676            state.instruction,
13677            inputs.join("\n")
13678        )
13679    }
13680}
13681
13682/// Does the winner have no commits ahead of the base it would land on?
13683/// Any failure to find out reads as "not empty": the merge then behaves as it
13684/// always did rather than refusing on a guess.
13685async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13686    let base = &state.base_branch;
13687    let mut against = base.clone();
13688    if mode == MergeMode::Pr {
13689        // A pull request lands on the remote's base, never the local branch
13690        // of the same name: if that cannot be read, "not empty" is the safe
13691        // answer.
13692        let remote = &state.config.merge.remote;
13693        let tracking = format!("{remote}/{base}");
13694        let fetched = git::fetch(repo, remote, base).await;
13695        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13696            against = tracking;
13697        } else {
13698            return false;
13699        }
13700    }
13701    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13702}
13703
13704/// Why nothing was opened for an empty winner, with what the task's own
13705/// references resolved to.
13706fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13707    let mut detail = format!(
13708        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13709         nothing to open a pull request for"
13710    );
13711    detail.push_str(
13712        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13713    );
13714    detail
13715}
13716
13717/// What the `Pr` merge does once it knows whether the branch already has an
13718/// open pull request.
13719#[derive(Debug, PartialEq, Eq)]
13720enum PrPlan {
13721    Create,
13722    Adopt { url: String, title: String },
13723    Stop(String),
13724}
13725
13726/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13727/// a failed lookup -> stop with the real reason. Never guesses.
13728fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13729    match found {
13730        Ok(land::OpenPr::None) => PrPlan::Create,
13731        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13732        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13733            "several open pull requests exist for this branch, not picking one: {}",
13734            urls.join(" ")
13735        )),
13736        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13737    }
13738}
13739
13740/// `gh pr create`, returning the PR url.
13741pub(crate) async fn gh_pr_create(
13742    cwd: &Path,
13743    base: &str,
13744    head: &str,
13745    title: &str,
13746    body: &str,
13747) -> Result<String> {
13748    let out = tokio::process::Command::new("gh")
13749        .args([
13750            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13751        ])
13752        .current_dir(cwd)
13753        .quiet()
13754        .stdin(std::process::Stdio::null())
13755        .output()
13756        .await
13757        .context("spawn gh")?;
13758    if out.status.success() {
13759        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13760    } else {
13761        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13762    }
13763}
13764
13765/// Never force deletion of uncommitted work, including unknown legacy trees.
13766async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13767    match std::fs::symlink_metadata(path) {
13768        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13769            // A previous cleanup may have removed the tree before a branch
13770            // deletion or state save failed. Unregister it if still present.
13771            git::worktree_remove_clean(repo, path).await?;
13772            return Ok(());
13773        }
13774        Err(e) => return Err(e.into()),
13775        Ok(_) => {}
13776    }
13777    if !git::is_clean(path).await? {
13778        bail!(
13779            "worktree has uncommitted work; refusing removal: {}",
13780            path.display()
13781        );
13782    }
13783    if !git::worktree_remove_clean(repo, path).await? {
13784        bail!("worktree removal refused: {}", path.display());
13785    }
13786    Ok(())
13787}
13788
13789/// Read seats return replies, not working-tree changes. Only registered,
13790/// detached seats directly inside this run's root may discard those changes.
13791async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13792    if !crate::retention::read_seat(path) || !path.exists() {
13793        return remove_preserved_worktree(&state.repo, path).await;
13794    }
13795    let owned = std::fs::symlink_metadata(path)?.is_dir()
13796        && path.parent().map(Path::canonicalize).transpose()?
13797            == Some(state.worktree_root().canonicalize()?)
13798        && crate::retention::worktrees(state)
13799            .await?
13800            .contains(&path.canonicalize()?);
13801    let common = crate::repo_lock::common_dir(&state.repo).await?;
13802    if !owned
13803        || common.is_none()
13804        || crate::repo_lock::common_dir(path).await? != common
13805        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
13806            .await?
13807            .ok()
13808        || state.candidates.iter().any(|c| c.worktree == path)
13809    {
13810        return remove_preserved_worktree(&state.repo, path).await;
13811    }
13812    let changes = git::status_porcelain(path).await?;
13813    if !git::worktree_remove(&state.repo, path).await? {
13814        bail!(
13815            "read-only seat worktree removal refused: {}",
13816            path.display()
13817        );
13818    }
13819    if !changes.is_empty() {
13820        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
13821        let paths: String = paths.chars().take(1024).collect();
13822        state.event(
13823            "fold",
13824            format!(
13825                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
13826                path.file_name().unwrap_or_default().to_string_lossy(),
13827                changes.lines().count()
13828            ),
13829        );
13830    }
13831    Ok(())
13832}
13833
13834fn fold_target(
13835    home: &Path,
13836    root: &Path,
13837    path: &Path,
13838    isolated: bool,
13839) -> Option<crate::build_target::FoldTarget> {
13840    if !isolated {
13841        return None;
13842    }
13843    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
13844        Ok(target) => target,
13845        Err(error) => {
13846            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
13847            None
13848        }
13849    }
13850}
13851
13852fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
13853    if let Some(target) = target
13854        && let Err(error) = target.reclaim_orphaned_target(home)
13855    {
13856        tracing::warn!(%error, "isolated target retained after fold");
13857    }
13858}
13859
13860/// Tear a run's worktrees and branches down.
13861///
13862/// `home` is where the updated `run.json` is saved (via
13863/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
13864/// a housekeeping pass already has its own honest `home` handed to it, and
13865/// falling through to the global here would write back through whichever
13866/// directory some other process or test pinned into that `OnceLock` first,
13867/// not the one the caller actually resolved its `runs` and `state` from.
13868pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
13869    fold_run_with_policy(state, drop_winner, home, false).await
13870}
13871
13872/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
13873pub async fn fold_run_overriding_recovery_retention(
13874    state: &mut RunState,
13875    drop_winner: bool,
13876    home: &Path,
13877) -> Result<Vec<String>> {
13878    fold_run_with_policy(state, drop_winner, home, true).await
13879}
13880
13881async fn fold_run_with_policy(
13882    state: &mut RunState,
13883    drop_winner: bool,
13884    home: &Path,
13885    override_recovery_retention: bool,
13886) -> Result<Vec<String>> {
13887    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
13888        && !override_recovery_retention
13889    {
13890        bail!("refusing fold: {reason}");
13891    }
13892    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
13893        bail!("candidate preservation incomplete; refusing cleanup");
13894    }
13895    // Serialize ordinary folding with the same starts/resumes as target-only
13896    // eviction. Otherwise a second janitor could remove the whole worktree
13897    // around a live output borrower even though target eviction was fenced.
13898    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
13899    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
13900    // An override must use current durable ownership, not a pre-lock snapshot.
13901    if override_recovery_retention {
13902        *state = RunState::load_under(&state.id, home)?;
13903        anyhow::ensure!(
13904            state.status.done() && !state.status.resumable(),
13905            "recovery retention override requires a finished, non-resumable run"
13906        );
13907        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
13908        anyhow::ensure!(
13909            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
13910            "run is live or its ownership is unknown"
13911        );
13912        anyhow::ensure!(
13913            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
13914            "candidate preservation incomplete; refusing cleanup"
13915        );
13916    }
13917    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
13918    if let Some(reason) = &retention_reason
13919        && !override_recovery_retention
13920    {
13921        bail!("refusing fold: {reason}");
13922    }
13923    let _driver = crate::driver::maintenance(home, &state.id)?;
13924    let mut output_guards = Vec::new();
13925    for entry in std::fs::read_dir(state.worktree_root())
13926        .into_iter()
13927        .flatten()
13928        .flatten()
13929    {
13930        if entry.path().join(".git").is_file() {
13931            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
13932        }
13933    }
13934    let repo = state.repo.clone();
13935    // CLI, Web and automatic cleanup all enter here, independently of
13936    // Runner::fold_losers. Protect deletion and shared config release too.
13937    let wait = repository_wait(state, None);
13938    let _coordination = match coordinate_operation(state, &repo, &wait).await {
13939        Ok(lease) => lease,
13940        Err(e) => {
13941            state.save_under(home)?;
13942            return Err(e);
13943        }
13944    };
13945    // Confirmed merges dispose of their owned sources after durable evidence
13946    // capture. Preflight every source before removing anything.
13947    let _source_outputs = if retention_reason.is_some()
13948        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
13949    {
13950        verify_merged_fold_sources(state, drop_winner, home).await?
13951    } else {
13952        Vec::new()
13953    };
13954    if let Some(reason) = retention_reason {
13955        state.event(
13956            "fold",
13957            format!(
13958                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
13959                state.id
13960            ),
13961        );
13962        state.save_under(home)?;
13963    }
13964    let root = state.worktree_root();
13965    let winner = state.tally.as_ref().map(|t| t.winner);
13966    let mut removed = Vec::new();
13967    let isolated = crate::build_target::isolated(&state.config);
13968
13969    for i in 0..state.candidates.len() {
13970        let c = state.candidates[i].clone();
13971        let is_winner = Some(c.label) == winner;
13972        if is_winner && !drop_winner {
13973            continue;
13974        }
13975        let existed = c.worktree.exists();
13976        let target = fold_target(home, &root, &c.worktree, isolated);
13977        // A vanished directory can still have a Git registration that keeps
13978        // its branch checked out. Remove that registration before the branch.
13979        remove_preserved_worktree(&repo, &c.worktree).await?;
13980        reclaim_fold_target(home, target);
13981        if existed {
13982            removed.push(c.worktree.to_string_lossy().into_owned());
13983        }
13984        // A branch handed to a later run (and its pull request) is not this
13985        // run's to delete.
13986        let handed_over = state.released_branches.contains(&c.branch);
13987        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
13988            if !git::branch_delete(&repo, &c.branch).await? {
13989                bail!("candidate branch removal refused");
13990            }
13991            removed.push(c.branch.clone());
13992        }
13993        state.candidates[i].folded = true;
13994    }
13995
13996    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
13997        let path = name.path();
13998        let keep = !drop_winner
13999            && winner.is_some_and(|w| {
14000                path.file_name()
14001                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14002            });
14003        if keep {
14004            continue;
14005        }
14006        let target = fold_target(home, &root, &path, isolated);
14007        remove_read_seat_worktree(state, &path).await?;
14008        reclaim_fold_target(home, target);
14009        removed.push(path.to_string_lossy().into_owned());
14010    }
14011
14012    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14013    // judge worktrees, so once the loop above has cleared all of them out,
14014    // the parent is a bare directory nobody else was ever going to remove -
14015    // git only ever managed what was inside it. Left alone, one of these
14016    // accumulates per fully-folded run; the operator's own machine had 74.
14017    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14018    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14019    // so does anything a run never claimed that happens to share the bay.
14020    remove_if_empty(&root);
14021
14022    if state.enabled_worktree_config && drop_winner {
14023        // A release, not a raw disable: some sibling run in this repository
14024        // may still hold its own reference (see `git::acquire_worktree_config`),
14025        // and only the last release actually turns the setting back off.
14026        git::release_worktree_config(&repo).await.ok();
14027        state.enabled_worktree_config = false;
14028    }
14029    state.save_under(home)?;
14030    Ok(removed)
14031}
14032
14033async fn verify_merged_fold_sources(
14034    state: &RunState,
14035    drop_winner: bool,
14036    home: &Path,
14037) -> Result<Vec<std::fs::File>> {
14038    let winner = state.tally.as_ref().map(|t| t.winner);
14039    let mut heads = BTreeSet::new();
14040    for candidate in &state.candidates {
14041        if Some(candidate.label) == winner && !drop_winner {
14042            continue;
14043        }
14044        anyhow::ensure!(
14045            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14046            "candidate recovery source is outside the inventoried run root: {}",
14047            candidate.worktree.display()
14048        );
14049        match std::fs::symlink_metadata(&candidate.worktree) {
14050            Ok(_) => {}
14051            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14052            Err(error) => return Err(error.into()),
14053        }
14054        if !state.released_branches.contains(&candidate.branch)
14055            && git::branch_exists(&state.repo, &candidate.branch).await?
14056        {
14057            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14058        }
14059    }
14060    let mut cargo_guards = Vec::new();
14061    let entries = match std::fs::read_dir(state.worktree_root()) {
14062        Ok(entries) => Some(entries),
14063        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14064        Err(error) => return Err(error.into()),
14065    };
14066    for entry in entries.into_iter().flatten() {
14067        let path = entry?.path();
14068        let metadata = std::fs::symlink_metadata(&path)?;
14069        anyhow::ensure!(
14070            metadata.is_dir() && !metadata.file_type().is_symlink(),
14071            "non-directory or symlink recovery source retained: {}",
14072            path.display()
14073        );
14074        if !drop_winner
14075            && winner.is_some_and(|w| {
14076                path.file_name()
14077                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14078            })
14079        {
14080            continue;
14081        }
14082        anyhow::ensure!(
14083            path.join(".git").is_file(),
14084            "unregistered recovery source retained: {}",
14085            path.display()
14086        );
14087        anyhow::ensure!(
14088            git::git(
14089                &path,
14090                &[
14091                    "status",
14092                    "--porcelain",
14093                    "--untracked-files=all",
14094                    "--ignored",
14095                    "--",
14096                    ".",
14097                    ":(exclude)target"
14098                ]
14099            )
14100            .await?
14101            .is_empty(),
14102            "source changes or ignored recovery files retained: {}",
14103            path.display()
14104        );
14105        match std::fs::symlink_metadata(path.join("target")) {
14106            Ok(_) => {
14107                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14108            }
14109            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14110            Err(error) => return Err(error.into()),
14111        }
14112        for checkpoint in [
14113            "rebase-merge",
14114            "rebase-apply",
14115            "sequencer",
14116            "CHERRY_PICK_HEAD",
14117            "MERGE_HEAD",
14118            "REBASE_HEAD",
14119            "REVERT_HEAD",
14120            "BISECT_LOG",
14121            "AUTO_MERGE",
14122            "MERGE_MSG",
14123        ] {
14124            let location = git::git(
14125                &path,
14126                &[
14127                    "rev-parse",
14128                    "--path-format=absolute",
14129                    "--git-path",
14130                    checkpoint,
14131                ],
14132            )
14133            .await?;
14134            anyhow::ensure!(
14135                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14136                if e.kind() == std::io::ErrorKind::NotFound),
14137                "Git recovery checkpoint retained: {checkpoint}"
14138            );
14139        }
14140        heads.insert(git::rev_parse(&path, "HEAD").await?);
14141    }
14142    crate::fold_evidence::preserve(state, home, &heads).await?;
14143
14144    Ok(cargo_guards)
14145}
14146
14147/// Remove `dir` if it exists and has nothing in it.
14148///
14149/// Best-effort and silent by design: a directory that is not empty (a run
14150/// whose winner is still parked there, a stray file some other process left)
14151/// is exactly the case this must refuse, and a directory that is already gone
14152/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14153/// already refuses a non-empty directory, so the emptiness check below is
14154/// belt, not suspenders - it is what keeps this from ever attempting the
14155/// removal in the case that matters, rather than trusting `remove_dir`'s
14156/// error path to have no side effects if it ever changed.
14157fn remove_if_empty(dir: &Path) {
14158    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14159        std::fs::remove_dir(dir).ok();
14160    }
14161}
14162
14163/// Severity of the worst open finding in the last review round, for reporting.
14164pub fn worst_open(state: &RunState) -> Option<Severity> {
14165    state
14166        .reviews
14167        .last()?
14168        .reviews
14169        .iter()
14170        .flat_map(|r| r.findings.iter())
14171        .map(|f| f.severity)
14172        .max()
14173}
14174
14175/// `[worktree] setup` hides its products per worktree, which needs
14176/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14177/// worktrees, like the hook's; every place that runs setup calls this first.
14178async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14179    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14180        git::acquire_worktree_config(repo).await?;
14181        state.enabled_worktree_config = true;
14182    }
14183    Ok(())
14184}
14185
14186#[cfg(test)]
14187mod tests {
14188    #[tokio::test]
14189    async fn launcher_base_fetch_requires_remote_success() {
14190        let tmp = tempfile::tempdir().unwrap();
14191        let repo = tmp.path().join("repo");
14192        let remote = tmp.path().join("remote");
14193        std::fs::create_dir(&repo).unwrap();
14194        std::fs::create_dir(&remote).unwrap();
14195        git::git(&remote, &["init", "--bare", "-b", "main"])
14196            .await
14197            .unwrap();
14198        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14199        git::git(
14200            &repo,
14201            &[
14202                "-c",
14203                "user.name=Fixture",
14204                "-c",
14205                "user.email=fixture@example.invalid",
14206                "commit",
14207                "--allow-empty",
14208                "-m",
14209                "fixture",
14210            ],
14211        )
14212        .await
14213        .unwrap();
14214        git::git(
14215            &repo,
14216            &["remote", "add", "origin", remote.to_str().unwrap()],
14217        )
14218        .await
14219        .unwrap();
14220        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14221        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14222        assert_eq!(
14223            resolve_base(&repo, "main", "origin", None)
14224                .await
14225                .unwrap()
14226                .commit,
14227            head
14228        );
14229        #[cfg(unix)]
14230        {
14231            let policy: crate::config::Coordination = toml::from_str(
14232                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14233            ).unwrap();
14234            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14235            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14236            let held = crate::repo_lock::SeatLease::operation_with(
14237                &repo,
14238                Some(&policy),
14239                &crate::repo_lock::WaitPolicy::default(),
14240            )
14241            .await
14242            .unwrap();
14243            assert!(held.is_some());
14244            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14245            tokio::pin!(fetch);
14246            assert!(
14247                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14248                    .await
14249                    .is_err()
14250            );
14251            assert!(
14252                !repo.join(".git/FETCH_HEAD").exists(),
14253                "no fetch before admission"
14254            );
14255            drop(held);
14256            let fetched = fetch.await.unwrap();
14257            assert_eq!(fetched.commit, head);
14258            assert_eq!(fetched.remote, "origin");
14259            assert_eq!(fetched.branch, "main");
14260        }
14261        // A surviving tracking ref is not successful fetch evidence.
14262        git::git(
14263            &repo,
14264            &[
14265                "remote",
14266                "set-url",
14267                "origin",
14268                tmp.path().join("missing").to_str().unwrap(),
14269            ],
14270        )
14271        .await
14272        .unwrap();
14273        let error = resolve_base(&repo, "main", "origin", None)
14274            .await
14275            .unwrap_err()
14276            .to_string();
14277        assert!(error.contains("cannot read origin/main"));
14278        assert!(error.contains("refusing to branch off"));
14279    }
14280
14281    #[test]
14282    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14283        let leaked = vec!["chore(deps): update a crate".to_owned()];
14284        let own = "fix(daemon): apply a chosen action";
14285        assert!(should_retitle("", own, &leaked));
14286        assert!(should_retitle(
14287            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14288            own,
14289            &leaked
14290        ));
14291        assert!(should_retitle(
14292            "chore: land candidate A of run 1",
14293            own,
14294            &leaked
14295        ));
14296        assert!(should_retitle(
14297            "magi: candidate A (uncommitted work)",
14298            own,
14299            &leaked
14300        ));
14301        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14302        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14303        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14304    }
14305
14306    #[test]
14307    fn pr_merge_plan_creates_adopts_or_stops() {
14308        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14309        assert_eq!(
14310            pr_merge_plan(Ok(land::OpenPr::One {
14311                url: "u".into(),
14312                title: "t".into()
14313            })),
14314            PrPlan::Adopt {
14315                url: "u".into(),
14316                title: "t".into()
14317            }
14318        );
14319        let PrPlan::Stop(many) =
14320            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14321        else {
14322            panic!("many must stop");
14323        };
14324        assert!(many.contains('a') && many.contains('b'));
14325        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14326            panic!("a failed lookup must stop");
14327        };
14328        assert!(err.contains("bad token"));
14329    }
14330
14331    use super::*;
14332    use crate::run::GateStatus;
14333    use std::collections::BTreeMap;
14334    use std::time::Duration;
14335
14336    fn conductor() -> AgentSpec {
14337        AgentSpec {
14338            id: "conductor".to_owned(),
14339            kind: crate::config::AgentKind::Command,
14340            model: None,
14341            command: vec!["true".to_owned()],
14342            extra_args: Vec::new(),
14343            env: BTreeMap::new(),
14344            prompt_delivery: None,
14345            max_turn_secs: None,
14346        }
14347    }
14348
14349    fn spec(id: &str) -> AgentSpec {
14350        AgentSpec {
14351            id: id.to_owned(),
14352            kind: crate::config::AgentKind::Command,
14353            model: None,
14354            command: vec!["true".to_owned()],
14355            extra_args: Vec::new(),
14356            env: BTreeMap::new(),
14357            prompt_delivery: None,
14358            max_turn_secs: None,
14359        }
14360    }
14361
14362    fn ids(xs: &[&str]) -> BTreeSet<String> {
14363        xs.iter().map(|s| (*s).to_owned()).collect()
14364    }
14365
14366    #[test]
14367    fn pick_successor_skips_an_agent_another_seat_holds() {
14368        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14369        let roster = [spec("a"), spec("b"), spec("c")];
14370        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14371        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14372    }
14373
14374    #[test]
14375    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14376        // The other seat started on c but was handed to d; c is free again.
14377        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14378        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14379        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14380        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14381        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14382    }
14383
14384    #[test]
14385    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14386        let roster = [spec("a"), spec("b")];
14387        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14388        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14389        let carried = ids(&["b"]);
14390        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14391        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14392    }
14393
14394    #[test]
14395    fn pick_successor_returns_none_without_any_untried_successor() {
14396        let roster = [spec("a"), spec("b")];
14397        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14398        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14399        let carried = ids(&["a"]);
14400        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14401    }
14402
14403    #[test]
14404    fn pick_successor_rescue_avoids_another_seats_occupant() {
14405        // b is a carried failure and free; a is held by the other seat.
14406        let roster = [spec("a"), spec("b"), spec("c")];
14407        let carried = ids(&["b", "c"]);
14408        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14409        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14410    }
14411
14412    #[test]
14413    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14414        let roster = [spec("a"), spec("b"), spec("c")];
14415        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14416        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14417    }
14418
14419    #[test]
14420    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14421        let roster = [spec("a"), spec("b"), spec("c")];
14422        let failed = ids(&["a", "b", "c"]);
14423        // Rescue looks at the whole roster, once per id, then runs out.
14424        let mut tried = ids(&["b"]);
14425        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14426        assert_eq!(first.id, "a");
14427        tried.insert(first.id.clone());
14428        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14429        assert_eq!(second.id, "c");
14430        tried.insert(second.id.clone());
14431        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14432    }
14433
14434    #[test]
14435    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14436        let roster = [spec("a"), spec("b")];
14437        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14438        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14439    }
14440
14441    #[test]
14442    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14443        let roster = [spec("a"), spec("b"), spec("c")];
14444        let h = SeatHistory {
14445            failed: ids(&["a"]),
14446            last_ok: Some("b".to_owned()),
14447            last_fail: None,
14448        };
14449        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14450        // A last answerer that left the roster, or later failed, is ignored.
14451        let gone = SeatHistory {
14452            last_ok: Some("zzz".to_owned()),
14453            ..h.clone()
14454        };
14455        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14456        let failed = SeatHistory {
14457            failed: ids(&["a", "b"]),
14458            last_ok: Some("b".to_owned()),
14459            last_fail: None,
14460        };
14461        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14462    }
14463
14464    #[test]
14465    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14466        let first = SeatState::new("review-1", "alpha", 7);
14467        let next = handover_seat("review-1", "gamma", 7);
14468        assert_ne!(first.claude_session, next.claude_session);
14469    }
14470
14471    #[test]
14472    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14473        let mut state = state_with_summary("x", "y");
14474        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14475        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14476        assert_ne!(a.claude_session, b.claude_session);
14477    }
14478
14479    #[test]
14480    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14481        let roster = [spec("a"), spec("b")];
14482        let h = SeatHistory {
14483            failed: ids(&["a", "b"]),
14484            ..SeatHistory::default()
14485        };
14486        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14487        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14488        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14489    }
14490
14491    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14492    // fallback loop depends on to terminate: it must walk forward from the
14493    // seat's own position, never restart at the front of the roster, and it
14494    // must never hand back an id already tried, however many times that id
14495    // happens to appear.
14496
14497    #[test]
14498    fn failure_signature_ignores_numbers_and_paths() {
14499        assert_eq!(
14500            failure_signature("exited with Some(2) and no usable output"),
14501            failure_signature("exited with Some(137) and no usable output")
14502        );
14503        assert_eq!(
14504            failure_signature("process exited with no usable output (exit code 2)"),
14505            failure_signature("process exited with no usable output (exit code 137)")
14506        );
14507        for (old, new) in [
14508            (
14509                "exited with Some(2) and no usable output",
14510                "process exited with no usable output (exit code 2)",
14511            ),
14512            (
14513                "exited with None and no usable output",
14514                "process exited with no usable output (exit code unavailable)",
14515            ),
14516        ] {
14517            let previous = FailClass::Other(failure_signature(old));
14518            let current = FailClass::Other(failure_signature(new));
14519            assert_eq!(previous, current, "resumption retains the failure class");
14520            assert!(!should_hand_over(Some(&previous), &current));
14521        }
14522        assert_eq!(
14523            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14524            failure_signature("cannot open /var/x.txt: denied")
14525        );
14526        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14527    }
14528
14529    #[test]
14530    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14531        let other = FailClass::Other("x".into());
14532        assert!(should_hand_over(None, &FailClass::Quota));
14533        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14534        assert!(should_hand_over(
14535            Some(&FailClass::Timeout),
14536            &FailClass::Timeout
14537        ));
14538        assert!(should_hand_over(None, &other));
14539        assert!(!should_hand_over(Some(&other), &other));
14540        assert!(should_hand_over(
14541            Some(&other),
14542            &FailClass::Other("y".into())
14543        ));
14544        // A quota or timeout in between ends the run of identical failures.
14545        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14546        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14547    }
14548
14549    #[test]
14550    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14551        let a = SeatState::new("judge-1", "alpha", 7);
14552        let b = handover_seat("judge-1", "beta", 7);
14553        assert_ne!(a.claude_session, b.claude_session);
14554        assert_eq!(b.turns, 0);
14555    }
14556
14557    #[test]
14558    fn a_timeout_is_classified_apart_from_other_failures() {
14559        assert_eq!(
14560            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14561            Some(FailClass::Timeout)
14562        );
14563        assert!(matches!(
14564            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14565            Some(FailClass::Other(_))
14566        ));
14567    }
14568
14569    #[test]
14570    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14571        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14572        let tried = BTreeSet::from(["beta".to_owned()]);
14573        // beta sits at index 1; the next candidate is gamma, never alpha —
14574        // which is very likely a different candidate slot's own agent.
14575        let next = next_untried_in_roster(&roster, 1, &tried);
14576        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14577    }
14578
14579    #[test]
14580    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14581        let roster = vec![spec("alpha"), spec("beta")];
14582        let tried = BTreeSet::from(["beta".to_owned()]);
14583        // beta is the roster's last entry: nothing follows it, and alpha —
14584        // earlier in the roster, almost certainly a different candidate
14585        // slot's own agent — must not be reached by wrapping back to it.
14586        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14587    }
14588
14589    #[test]
14590    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14591        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14592        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14593        // beta (index 1) and gamma (index 2, the only entry after it) have
14594        // both been tried; alpha (index 0) never has, but it comes before
14595        // beta's own position, so there is nothing further for this seat.
14596        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14597    }
14598
14599    #[test]
14600    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14601        let roster = vec![spec("a"), spec("a"), spec("b")];
14602        let tried = BTreeSet::from(["a".to_owned()]);
14603        let next = next_untried_in_roster(&roster, 0, &tried);
14604        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14605    }
14606
14607    #[test]
14608    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14609        let roster = vec![spec("a"), spec("b")];
14610        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14611        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14612    }
14613
14614    #[test]
14615    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14616        let dir = tempfile::tempdir().unwrap();
14617        let bay = dir.path().join("ffff");
14618
14619        // Not there yet: nothing to do, nothing to panic on.
14620        remove_if_empty(&bay);
14621        assert!(!bay.exists());
14622
14623        // Something still inside - the winner's worktree, or a stray file -
14624        // keeps the directory standing.
14625        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14626        remove_if_empty(&bay);
14627        assert!(bay.exists(), "non-empty directory must survive");
14628
14629        // Once the last entry is gone, so is the directory itself.
14630        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14631        remove_if_empty(&bay);
14632        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14633    }
14634
14635    // `round_is_clean` is the exact decision this task fixed: a round with a
14636    // seat that never answered must not read the same as a round every seat
14637    // actually reviewed. These are deterministic and process-free by design —
14638    // the equivalent end-to-end check (a real reviewer timing out under a
14639    // live graph run) is a genuine race against wall-clock contention, and a
14640    // spawn slow enough to blow even a generous budget under a loaded test
14641    // run must not turn this specific regression check flaky.
14642
14643    #[test]
14644    fn a_full_panel_that_found_nothing_is_clean() {
14645        assert!(round_is_clean(
14646            0,
14647            true,
14648            2,
14649            2,
14650            0,
14651            IncompleteReviewPolicy::Block
14652        ));
14653    }
14654
14655    #[test]
14656    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14657        assert!(!round_is_clean(
14658            0,
14659            true,
14660            1,
14661            2,
14662            0,
14663            IncompleteReviewPolicy::Block
14664        ));
14665    }
14666
14667    #[test]
14668    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14669        assert!(!round_is_clean(
14670            1,
14671            true,
14672            1,
14673            2,
14674            0,
14675            IncompleteReviewPolicy::Warn
14676        ));
14677    }
14678
14679    #[test]
14680    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14681        assert!(round_is_clean(
14682            0,
14683            true,
14684            1,
14685            2,
14686            0,
14687            IncompleteReviewPolicy::Warn
14688        ));
14689    }
14690
14691    #[test]
14692    fn a_full_panel_with_an_open_finding_is_not_clean() {
14693        assert!(!round_is_clean(
14694            1,
14695            true,
14696            2,
14697            2,
14698            0,
14699            IncompleteReviewPolicy::Block
14700        ));
14701    }
14702
14703    #[test]
14704    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14705        assert!(!round_is_clean(
14706            0,
14707            false,
14708            2,
14709            2,
14710            0,
14711            IncompleteReviewPolicy::Block
14712        ));
14713    }
14714
14715    // The stall this task closes: under the default `block` policy, a seat
14716    // missing only because it was rate limited must not force a wait for a
14717    // session limit that will not lift by the next round. `round_is_clean`
14718    // is where that quorum carve-out lives; the review loop around it never
14719    // changes what a reviewer's vote or a finding's severity means.
14720
14721    #[test]
14722    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14723        // 1 of 2 answered, and the one missing was quota'd — the exact
14724        // "review-2 rate limited (quota)" shape from the field report.
14725        assert!(round_is_clean(
14726            0,
14727            true,
14728            1,
14729            2,
14730            1,
14731            IncompleteReviewPolicy::Block
14732        ));
14733    }
14734
14735    #[test]
14736    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14737        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14738        // not a quota loss (`quota_missing` stays 0) — worth another try.
14739        assert!(!round_is_clean(
14740            0,
14741            true,
14742            1,
14743            2,
14744            0,
14745            IncompleteReviewPolicy::Block
14746        ));
14747    }
14748
14749    #[test]
14750    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14751        assert!(!round_is_clean(
14752            1,
14753            true,
14754            1,
14755            2,
14756            1,
14757            IncompleteReviewPolicy::Block
14758        ));
14759        assert!(!round_is_clean(
14760            0,
14761            false,
14762            1,
14763            2,
14764            1,
14765            IncompleteReviewPolicy::Block
14766        ));
14767    }
14768
14769    #[test]
14770    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14771        // Every seat quota'd, nobody answered: there is no panel to decide
14772        // on, so this must fall through to the existing block-and-retry
14773        // fallback rather than call an unreviewed patch clean.
14774        assert!(!round_is_clean(
14775            0,
14776            true,
14777            0,
14778            2,
14779            2,
14780            IncompleteReviewPolicy::Block
14781        ));
14782    }
14783
14784    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14785        CommandOutcome {
14786            command: "test".to_owned(),
14787            code,
14788            output_tail: String::new(),
14789            duration_ms: 0,
14790            resource_blocked,
14791        }
14792    }
14793
14794    #[cfg(unix)]
14795    #[tokio::test]
14796    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
14797        ask_test_home();
14798        let temp = tempfile::tempdir().unwrap();
14799        let mut runner = runner_at(RunStatus::Gating);
14800        let shell = vec!["sh".to_owned(), "-c".to_owned()];
14801        let commands = vec![
14802            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
14803            "touch must-not-run".to_owned(),
14804        ];
14805        let (outcomes, retried, pids) = run_e2e_with_retry(
14806            &mut runner.state,
14807            &shell,
14808            &commands,
14809            temp.path(),
14810            Duration::from_secs(5),
14811            "fixture",
14812            None,
14813        )
14814        .await;
14815        assert_eq!(outcomes.len(), 1);
14816        assert!(outcomes[0].resource_blocked);
14817        assert!(!outcomes[0].build_failed());
14818        assert!(!retried);
14819        assert!(pids.is_empty());
14820        assert!(!temp.path().join("must-not-run").exists());
14821        assert_eq!(
14822            runner.state.resource_block.as_ref().unwrap().kind,
14823            "incremental cache admission"
14824        );
14825    }
14826
14827    #[test]
14828    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
14829        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
14830        assert!(
14831            !verify_inconclusive(&[outcome(Some(1), false)]),
14832            "an ordinary failure is still evidence about the patch"
14833        );
14834        assert!(verify_inconclusive(&[outcome(None, true)]));
14835        assert!(
14836            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
14837            "one inconclusive outcome taints the whole batch"
14838        );
14839        assert!(!verify_inconclusive(&[]));
14840    }
14841
14842    #[tokio::test]
14843    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
14844        // Alive for the first two checks, then dead - confirms the loop
14845        // actually re-polls rather than deciding once and sleeping out the
14846        // ceiling regardless.
14847        let calls = std::sync::atomic::AtomicUsize::new(0);
14848        let started = Instant::now();
14849        wait_for_pids_with(
14850            &[123],
14851            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
14852            Duration::from_millis(5),
14853            Duration::from_secs(5),
14854        )
14855        .await;
14856        assert!(
14857            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
14858            "must keep checking rather than deciding on the first answer"
14859        );
14860        assert!(
14861            started.elapsed() < Duration::from_secs(1),
14862            "must return the moment it is confirmed dead, not wait out the ceiling"
14863        );
14864    }
14865
14866    #[tokio::test]
14867    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
14868        let started = Instant::now();
14869        wait_for_pids_with(
14870            &[123],
14871            |_| true, // never reports dead
14872            Duration::from_millis(5),
14873            Duration::from_millis(30),
14874        )
14875        .await;
14876        let elapsed = started.elapsed();
14877        assert!(
14878            elapsed >= Duration::from_millis(30),
14879            "must not give up before its own ceiling: {elapsed:?}"
14880        );
14881        assert!(
14882            elapsed < Duration::from_secs(1),
14883            "must not wait past its own ceiling either: {elapsed:?}"
14884        );
14885    }
14886
14887    #[tokio::test]
14888    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
14889        let started = Instant::now();
14890        wait_for_pids_with(
14891            &[],
14892            |_| true,
14893            Duration::from_secs(5),
14894            Duration::from_secs(5),
14895        )
14896        .await;
14897        assert!(
14898            started.elapsed() < Duration::from_millis(200),
14899            "an empty pid list has nothing to confirm"
14900        );
14901    }
14902
14903    // `review_conclusion` is the exact decision the review hand-off task
14904    // fixed: a round budget spent (or a tree that stopped moving) must not
14905    // collapse into `Blocked` regardless of what verification actually
14906    // said. Deterministic and process-free for the same reason the
14907    // `round_is_clean` family above is.
14908    fn review_round(
14909        clean: bool,
14910        blocking: usize,
14911        answered: usize,
14912        expected: usize,
14913        progressed: bool,
14914        e2e_ok: bool,
14915    ) -> ReviewRound {
14916        ReviewRound {
14917            round: 1,
14918            head: "h".to_owned(),
14919            verified_head: None,
14920            verified_at: None,
14921            reviews: Vec::new(),
14922            e2e: vec![CommandOutcome {
14923                command: "test".to_owned(),
14924                code: Some(if e2e_ok { 0 } else { 1 }),
14925                output_tail: String::new(),
14926                duration_ms: 0,
14927                resource_blocked: false,
14928            }],
14929            verify_retried: false,
14930            e2e_deferred: false,
14931            e2e_defer_reason: None,
14932            fix: None,
14933            blocking,
14934            answered,
14935            expected,
14936            clean,
14937            progressed,
14938            vote_split: false,
14939            reconsideration: Vec::new(),
14940            verdict: None,
14941        }
14942    }
14943
14944    #[test]
14945    fn review_conclusion_is_none_when_nothing_has_run() {
14946        assert_eq!(review_conclusion(&[], 3), None);
14947    }
14948
14949    #[test]
14950    fn review_conclusion_is_none_while_rounds_remain() {
14951        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
14952        assert_eq!(review_conclusion(&rounds, 3), None);
14953    }
14954
14955    #[test]
14956    fn review_conclusion_is_gating_once_a_round_is_clean() {
14957        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
14958        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
14959    }
14960
14961    #[test]
14962    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
14963        let rounds = vec![
14964            review_round(false, 1, 2, 2, true, true),
14965            review_round(false, 1, 2, 2, true, true),
14966        ];
14967        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
14968    }
14969
14970    #[test]
14971    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
14972        let rounds = vec![
14973            review_round(false, 1, 2, 2, true, true),
14974            review_round(false, 1, 2, 2, true, false),
14975        ];
14976        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
14977    }
14978
14979    #[test]
14980    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
14981        // Magi never got a command to run against this round's own head — a
14982        // resource-blocked attempt, not a red one — so this must never
14983        // settle on `Blocked` the way a genuine e2e failure would. `None`
14984        // here is what tells `Runner::review_loop` to retry the check
14985        // itself rather than trust this cheap recomputation with a verdict
14986        // it cannot actually produce.
14987        let mut blocked = review_round(false, 1, 2, 2, true, false);
14988        blocked.e2e[0].resource_blocked = true;
14989        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
14990        assert_eq!(review_conclusion(&rounds, 2), None);
14991    }
14992
14993    #[test]
14994    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
14995        // Missing input, not a verified tree — never a hand-off candidate.
14996        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
14997        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
14998    }
14999
15000    #[test]
15001    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15002        let rounds = vec![
15003            review_round(false, 1, 2, 2, false, true),
15004            review_round(false, 1, 2, 2, false, true),
15005        ];
15006        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15007    }
15008
15009    fn secs(n: u64) -> Duration {
15010        Duration::from_secs(n)
15011    }
15012
15013    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15014    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15015    #[tokio::test]
15016    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15017        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15018        if std::env::var_os(CHILD).is_none() {
15019            // Other tests reconcile every run in the process-global home,
15020            // briefly taking owner locks. This ancestry test expects an idle
15021            // predecessor, so give it its own process and pinned test home.
15022            let output = std::process::Command::new(std::env::current_exe().unwrap())
15023                .args([
15024                    "--exact",
15025                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15026                    "--nocapture",
15027                ])
15028                .env(CHILD, "1")
15029                .env_remove("MAGI_WORKER_HOME")
15030                .env_remove("MAGI_WORKER_ID")
15031                .output()
15032                .unwrap();
15033            assert!(
15034                output.status.success()
15035                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15036                "{}\n{}",
15037                String::from_utf8_lossy(&output.stdout),
15038                String::from_utf8_lossy(&output.stderr)
15039            );
15040            return;
15041        }
15042        ask_test_home();
15043        let tmp = tempfile::tempdir().unwrap();
15044        let repo = tmp.path().join("repo");
15045        std::fs::create_dir_all(&repo).unwrap();
15046        init_repo(&repo);
15047        let g = |args: &[&str]| {
15048            let out = std::process::Command::new("git")
15049                .args(args)
15050                .current_dir(&repo)
15051                .quiet()
15052                .output()
15053                .unwrap();
15054            assert!(
15055                out.status.success(),
15056                "{}",
15057                String::from_utf8_lossy(&out.stderr)
15058            );
15059        };
15060        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15061        g(&["checkout", "-b", "historical"]);
15062        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15063        g(&["add", "."]);
15064        g(&["commit", "-m", "old alternative"]);
15065        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15066        g(&["checkout", "-b", "magi/task-selected", &base]);
15067        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15068        g(&["add", "."]);
15069        g(&["commit", "-m", "measurement infrastructure"]);
15070        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15071        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15072        g(&["add", "."]);
15073        g(&["commit", "-m", "dependent implementation"]);
15074        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15075        g(&["checkout", "main"]);
15076        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15077        g(&["add", "."]);
15078        g(&["commit", "-m", "unrelated base change"]);
15079        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15080        let origin = tmp.path().join("origin.git");
15081        g(&[
15082            "clone",
15083            "--bare",
15084            repo.to_str().unwrap(),
15085            origin.to_str().unwrap(),
15086        ]);
15087        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15088        g(&["fetch", "origin"]);
15089        let selection = crate::pr_recovery::Selection {
15090            url: "https://example.test/project/pull/1".into(),
15091            branch: "magi/task-selected".into(),
15092            head: head.clone(),
15093            source_head: None,
15094            source_run: None,
15095            source_proof: None,
15096            disposition: Some(crate::pr_recovery::Disposition::Review),
15097            instruction: "preserve measured behavior".into(),
15098            approved_at: jiff::Timestamp::now(),
15099        };
15100        let mut template = runner_at(RunStatus::Reviewing);
15101        template.state.repo = repo.clone();
15102        template.state.base_commit = current.clone();
15103        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15104        template.state.origin = Some(crate::run::Origin::queue("selected"));
15105        template.state.pr_head = Some(selection.branch.clone());
15106        template.state.pr_recovery = Some(selection.clone());
15107        let mut runner =
15108            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15109                .await
15110                .unwrap();
15111        let wt = runner.state.winner().unwrap().worktree.clone();
15112        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15113        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15114        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15115        assert!(runner.state.seeds.is_empty());
15116        assert_eq!(runner.state.instruction, "preserve measured behavior");
15117        runner.sync_to_base().await.unwrap();
15118        assert_eq!(
15119            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15120            "prerequisite"
15121        );
15122        assert_eq!(
15123            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15124            "measured implementation"
15125        );
15126        assert_eq!(
15127            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15128            "current main change"
15129        );
15130        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15131        assert_eq!(
15132            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15133            head
15134        );
15135
15136        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15137        let mut partial = runner_at(RunStatus::Reviewing);
15138        partial.state.repo = repo.clone();
15139        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15140        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15141            run: Some("exit 1".into()),
15142            ..Default::default()
15143        }];
15144        let selection = runner.state.pr_recovery.clone().unwrap();
15145        partial.state.pr_recovery = Some(selection.clone());
15146        partial.state.pr_head = Some(selection.branch.clone());
15147        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15148        let id = partial.state.id.clone();
15149        let error = match Runner::open_selected(
15150            &repo,
15151            partial.state,
15152            partial.roles,
15153            1,
15154            runner.state.base_commit.clone(),
15155            selection,
15156        )
15157        .await
15158        {
15159            Ok(_) => panic!("setup must fail"),
15160            Err(e) => e,
15161        };
15162        assert_eq!(
15163            error
15164                .downcast_ref::<crate::run::StartupFailure>()
15165                .unwrap()
15166                .run,
15167            id
15168        );
15169        let failed = RunState::load(&id).unwrap();
15170        assert_eq!(failed.status, RunStatus::Failed);
15171        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15172        assert!(Runner::resume(&id).is_err());
15173        runner.state.status = RunStatus::Ready;
15174        runner.state.driver_exited = true;
15175        runner.state.save().unwrap();
15176        let mut retry = runner_at(RunStatus::Reviewing);
15177        retry.state.repo = repo.clone();
15178        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15179        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15180        reselected.approved_at = jiff::Timestamp::now();
15181        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15182        retry.state.pr_head = Some(reselected.branch.clone());
15183        retry.state.pr_recovery = Some(reselected.clone());
15184        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15185            .await
15186            .unwrap();
15187        let restarted = Runner::open_selected(
15188            &repo,
15189            retry.state,
15190            retry.roles,
15191            1,
15192            runner.state.base_commit.clone(),
15193            reselected,
15194        )
15195        .await
15196        .unwrap();
15197        assert_eq!(
15198            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15199                .await
15200                .unwrap(),
15201            head
15202        );
15203        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15204        assert_eq!(
15205            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15206            head
15207        );
15208    }
15209
15210    #[tokio::test]
15211    #[cfg(unix)]
15212    async fn fallback_and_interrupted_restoration_require_coordination() {
15213        use std::os::fd::AsRawFd as _;
15214        ask_test_home();
15215        let tmp = tempfile::tempdir().unwrap();
15216        let mut runner = registered_runner(tmp.path()).await;
15217        runner.state.config.graph.timeout_resource_wait = 1;
15218        let winner = runner.state.candidates[0].clone();
15219        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15220        let leftover = winner.worktree.join("leftover");
15221        std::fs::write(&leftover, "untrusted edits").unwrap();
15222        let next = tmp.path().join("next-fixer");
15223        let mut failed = spec("first");
15224        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15225        let mut successor = spec("second");
15226        successor.command = vec![
15227            "sh".into(),
15228            "-c".into(),
15229            format!("touch '{}'; echo done", next.display()),
15230        ];
15231        let attempts = vec![
15232            (failed.clone(), "first".into()),
15233            (successor.clone(), "second".into()),
15234        ];
15235        let lock_path = runner.state.repo.join(".git/updater.lock");
15236        let external = std::fs::File::create(&lock_path).unwrap();
15237        assert_eq!(
15238            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15239            0
15240        );
15241        let artifacts = tmp.path().join("artifacts");
15242        let build = |spec, seat| SeatJob {
15243            spec,
15244            seat,
15245            cwd: winner.worktree.clone(),
15246            prompt: "fixture".into(),
15247            timeout: Duration::from_secs(10),
15248            allow_write: true,
15249            sessions: false,
15250            artifacts: artifacts.clone(),
15251            stem: "fix".into(),
15252            handover: None,
15253        };
15254        let (_, _, out) = runner
15255            .ask_fixer_among(
15256                attempts.clone(),
15257                "graft",
15258                None,
15259                Some((&winner.worktree, &head)),
15260                build,
15261            )
15262            .await;
15263        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15264        assert!(leftover.exists(), "contention must prevent clean");
15265        assert!(!next.exists());
15266        assert!(runner.state.handovers.is_empty());
15267        // Early interrupted-repair rollback uses the same protected route.
15268        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15269            from_run: "earlier".into(),
15270            generation: 1,
15271            mode: crate::recovery::Mode::VerifyRepair,
15272            reasons: Vec::new(),
15273            reviewed_head: None,
15274            rounds: Vec::new(),
15275            open_findings: Vec::new(),
15276            evidence: None,
15277            criteria_inherited: true,
15278            repair: crate::recovery::Repair::Started {
15279                before: head.clone(),
15280            },
15281        });
15282        assert!(
15283            runner
15284                .recovery_repair(&winner)
15285                .await
15286                .unwrap_err()
15287                .is::<crate::repo_lock::ResourceBlocked>()
15288        );
15289        assert!(matches!(
15290            runner.state.recovery.as_ref().unwrap().repair,
15291            crate::recovery::Repair::Started { .. }
15292        ));
15293        assert!(leftover.exists());
15294        drop(external);
15295        runner.recovery_repair(&winner).await.unwrap();
15296        assert!(!leftover.exists());
15297        assert!(matches!(
15298            runner.state.recovery.as_ref().unwrap().repair,
15299            crate::recovery::Repair::Done { .. }
15300        ));
15301        // A hard lock-open failure also leaves HEAD and untracked work intact.
15302        std::fs::remove_file(&lock_path).unwrap();
15303        std::fs::create_dir(&lock_path).unwrap();
15304        std::fs::write(&leftover, "untrusted edits").unwrap();
15305        let (_, _, out) = runner
15306            .ask_fixer_among(
15307                attempts,
15308                "graft",
15309                None,
15310                Some((&winner.worktree, &head)),
15311                build,
15312            )
15313            .await;
15314        assert!(matches!(out, AgentOutcome::Failed(_)));
15315        assert!(leftover.exists());
15316        assert!(!next.exists());
15317        assert_eq!(
15318            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15319            head
15320        );
15321    }
15322
15323    #[cfg(unix)]
15324    async fn registered_runner(root: &Path) -> Runner {
15325        repository_runner(root, crate::config::test_coordination()).await
15326    }
15327
15328    async fn repository_runner(
15329        root: &Path,
15330        coordination: Option<crate::config::Coordination>,
15331    ) -> Runner {
15332        ask_test_home();
15333        let repo = root.join("repo");
15334        std::fs::create_dir_all(&repo).unwrap();
15335        init_repo(&repo);
15336        if coordination.is_some() {
15337            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15338        }
15339        let mut runner = runner_at(RunStatus::Prep);
15340        runner.state.repo = repo.clone();
15341        runner.state.config.coordination = coordination;
15342        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15343        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15344        runner.state.config.graph.advise = false;
15345        runner.roles.implementers = vec![spec("implement")];
15346        runner.roles.judges = vec![spec("judge")];
15347        runner.prep().await.unwrap();
15348        runner
15349    }
15350
15351    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15352
15353    #[tokio::test]
15354    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15355        let tmp = tempfile::tempdir().unwrap();
15356        let mut runner = repository_runner(tmp.path(), None).await;
15357        let prompts = runner.state.config.prompts.clone();
15358        let run = runner.state.id.clone();
15359        let ctx = WaveCtx {
15360            carry_seats: false,
15361            pauses: None,
15362            run: &run,
15363            node: "advise",
15364            prompts: &prompts,
15365            cache: None,
15366            round: None,
15367        };
15368        let jobs: Vec<_> = ["alpha", "beta"]
15369            .into_iter()
15370            .map(|id| SeatJob {
15371                spec: scripted(id, AUTH_OUTAGE),
15372                seat: SeatState::new(id, id, 7),
15373                prompt: "propose".into(),
15374                cwd: runner.state.candidates[0].worktree.clone(),
15375                timeout: Duration::from_secs(10),
15376                allow_write: false,
15377                sessions: false,
15378                artifacts: agent::artifacts_dir(&runner.state.dir()),
15379                stem: id.into(),
15380                handover: None,
15381            })
15382            .collect();
15383        let mut losses = Vec::new();
15384        let results = ask_wave_with(
15385            jobs.clone(),
15386            runner.sem.clone(),
15387            2,
15388            &[],
15389            &ctx,
15390            &mut losses,
15391            &mut runner.state,
15392            &|_: &str| Ok(()),
15393        )
15394        .await;
15395        assert!(
15396            results
15397                .iter()
15398                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15399        );
15400        assert_eq!(runner.state.quota.len(), 2);
15401        assert!(
15402            runner
15403                .state
15404                .quota
15405                .iter()
15406                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15407        );
15408        assert!(!runner.state.advise_attempted);
15409        runner.stop_for_resource().unwrap();
15410        assert_eq!(runner.state.status, RunStatus::Blocked);
15411        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15412        assert_eq!(
15413            runner.state.resource_block.as_ref().unwrap().kind,
15414            "agent authentication"
15415        );
15416        // A machine loss followed by an ordinary failure is not evidence
15417        // that the whole node was unavailable, and must not earn a refund.
15418        runner.state.resource_block = None;
15419        runner.state.quota.clear();
15420        let mut mixed = jobs;
15421        mixed[1].spec.command = vec!["false".into()];
15422        let results = ask_wave_with(
15423            mixed,
15424            runner.sem.clone(),
15425            0,
15426            &[],
15427            &ctx,
15428            &mut losses,
15429            &mut runner.state,
15430            &|_: &str| Ok(()),
15431        )
15432        .await;
15433        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15434        assert!(runner.state.resource_block.is_none());
15435        assert_eq!(losses.len(), 1);
15436    }
15437
15438    #[tokio::test]
15439    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15440        let tmp = tempfile::tempdir().unwrap();
15441        let mut runner = repository_runner(tmp.path(), None).await;
15442        let implementer = scripted("implement", AUTH_OUTAGE);
15443        runner.roles.implementers = vec![implementer.clone()];
15444        runner.state.config.agents = vec![implementer];
15445        runner.implement().await.unwrap();
15446        assert_eq!(runner.state.status, RunStatus::Blocked);
15447        assert_eq!(runner.state.quota.len(), 1);
15448        assert_eq!(
15449            runner.state.quota[0].cause,
15450            agent::QuotaCause::Authentication
15451        );
15452        let candidate = &runner.state.candidates[0];
15453        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15454        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15455    }
15456
15457    #[tokio::test]
15458    #[cfg(unix)]
15459    async fn parked_implementer_persists_completed_work() {
15460        for registered in [false, true] {
15461            let tmp = tempfile::tempdir().unwrap();
15462            let mut runner = registered_runner(tmp.path()).await;
15463            if !registered {
15464                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15465            }
15466            let marker = tmp.path().join("started");
15467            let release = tmp.path().join("release");
15468            let mut implementer = spec("implement");
15469            implementer.command = vec![
15470                "sh".into(),
15471                "-c".into(),
15472                format!(
15473                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15474                    marker.display(),
15475                    release.display()
15476                ),
15477            ];
15478            runner.roles.implementers = vec![implementer.clone()];
15479            runner.state.config.agents = vec![implementer];
15480            let pause = runner.pause.clone();
15481            let (result, ()) = tokio::join!(runner.implement(), async {
15482                tokio::time::timeout(Duration::from_secs(10), async {
15483                    while !marker.exists() {
15484                        tokio::time::sleep(Duration::from_millis(10)).await;
15485                    }
15486                })
15487                .await
15488                .unwrap();
15489                pause.park();
15490                std::fs::write(&release, "go").unwrap();
15491            });
15492            result.unwrap();
15493            let candidate = &runner.state.candidates[0];
15494            assert!(candidate.commits > 0, "{candidate:?}");
15495            assert!(candidate.summary.contains("saved-result"));
15496            assert_eq!(candidate.files, 1);
15497            let before = candidate.commits;
15498            runner.implement().await.unwrap();
15499            assert_eq!(runner.state.candidates[0].commits, before);
15500        }
15501    }
15502
15503    #[tokio::test]
15504    #[cfg(unix)]
15505    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15506        let tmp = tempfile::tempdir().unwrap();
15507        let mut runner = registered_runner(tmp.path()).await;
15508        let winner = runner.state.candidates[0].clone();
15509        let cache = tmp.path().join("cache");
15510        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15511        runner.state.config.graph.timeout_resource_wait = 0;
15512        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15513        let crate::cache::AcquireOutcome::Acquired(held) =
15514            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15515        else {
15516            panic!("cache must be free")
15517        };
15518        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15519            from_run: "earlier".into(),
15520            generation: 1,
15521            mode: crate::recovery::Mode::VerifyRepair,
15522            reasons: Vec::new(),
15523            reviewed_head: None,
15524            rounds: Vec::new(),
15525            open_findings: Vec::new(),
15526            evidence: None,
15527            criteria_inherited: true,
15528            repair: crate::recovery::Repair::NotStarted,
15529        });
15530        runner.recovery_repair(&winner).await.unwrap();
15531        assert!(matches!(
15532            runner.state.recovery.as_ref().unwrap().repair,
15533            crate::recovery::Repair::WaitingForRestore { .. }
15534        ));
15535        drop(held);
15536        runner.state.resource_block = None;
15537        runner.state.config.graph.timeout_resource_wait = 1;
15538        runner.recovery_repair(&winner).await.unwrap();
15539        assert!(matches!(
15540            runner.state.recovery.as_ref().unwrap().repair,
15541            crate::recovery::Repair::Done { .. }
15542        ));
15543        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15544    }
15545
15546    #[tokio::test]
15547    #[cfg(unix)]
15548    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15549        use std::os::fd::AsRawFd as _;
15550        for graft in [false, true] {
15551            let tmp = tempfile::tempdir().unwrap();
15552            let mut runner = registered_runner(tmp.path()).await;
15553            runner.state.config.graph.timeout_resource_wait = 1;
15554            let winner = runner.state.candidates[0].clone();
15555            let marker = tmp.path().join("fixer-started");
15556            let mut fixer = spec("fixer");
15557            fixer.command = vec![
15558                "sh".into(),
15559                "-c".into(),
15560                format!("echo started >> '{}'; echo done", marker.display()),
15561            ];
15562            runner.roles.fixer = Some(vec![fixer]);
15563            if graft {
15564                let mut loser = winner.clone();
15565                loser.label = 'B';
15566                loser.index = 1;
15567                runner.state.candidates.push(loser);
15568                runner.state.config.graph.graft_runner_up = true;
15569                runner.state.tally = Some(Tally {
15570                    first_choice: BTreeMap::new(),
15571                    borda: BTreeMap::new(),
15572                    winner: winner.label,
15573                    rankings: 1,
15574                    unanimous_initial: true,
15575                    deliberated: false,
15576                    changed_votes: 0,
15577                    unanimous_final: true,
15578                    tie_break: None,
15579                    judges: 1,
15580                    present: 1,
15581                    quorum: 1,
15582                    met_quorum: true,
15583                    uncontested: None,
15584                });
15585                runner.state.judgements.push(crate::run::Judgement {
15586                    judge: 1,
15587                    seat: "judge-1".into(),
15588                    agent: "judge".into(),
15589                    ranking: vec![winner.label, 'B'],
15590                    reasons: BTreeMap::new(),
15591                    confidence: None,
15592                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15593                    order: vec![0, 1],
15594                    failed: None,
15595                    duration_ms: 0,
15596                });
15597            } else {
15598                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15599                    from_run: "earlier".into(),
15600                    generation: 1,
15601                    mode: crate::recovery::Mode::VerifyRepair,
15602                    reasons: Vec::new(),
15603                    reviewed_head: None,
15604                    rounds: Vec::new(),
15605                    open_findings: Vec::new(),
15606                    evidence: None,
15607                    criteria_inherited: true,
15608                    repair: crate::recovery::Repair::NotStarted,
15609                });
15610            }
15611            let reader = crate::repo_lock::SeatLease::for_checkout(
15612                &winner.worktree,
15613                false,
15614                crate::config::test_coordination().as_ref(),
15615            )
15616            .await
15617            .unwrap();
15618            let pause = runner.pause.clone();
15619            let (result, ()) = tokio::join!(
15620                async {
15621                    if graft {
15622                        runner.graft().await
15623                    } else {
15624                        runner.recovery_repair(&winner).await
15625                    }
15626                },
15627                async {
15628                    tokio::time::sleep(Duration::from_millis(100)).await;
15629                    pause.park();
15630                }
15631            );
15632            result.unwrap();
15633            assert!(!marker.exists(), "a blocked seat must not spawn");
15634            // Exercise the persisted state, as a binary replacement/resume does.
15635            runner.state = RunState::load(&runner.state.id).unwrap();
15636            if graft {
15637                assert_eq!(
15638                    runner.state.graft.as_ref().unwrap().outcome,
15639                    GraftOutcome::WaitingForRestore
15640                );
15641            } else {
15642                assert!(matches!(
15643                    runner.state.recovery.as_ref().unwrap().repair,
15644                    crate::recovery::Repair::WaitingForRestore { .. }
15645                ));
15646            }
15647            drop(reader);
15648            runner.pause = Pause::new();
15649            runner.state.resource_block = None;
15650            // Deferred restoration must still respect an external lock owner.
15651            let external =
15652                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15653            assert_eq!(
15654                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15655                0
15656            );
15657            let leftover = winner.worktree.join("leftover");
15658            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15659            let result = if graft {
15660                runner.graft().await
15661            } else {
15662                runner.recovery_repair(&winner).await
15663            };
15664            assert!(
15665                result
15666                    .unwrap_err()
15667                    .is::<crate::repo_lock::ResourceBlocked>()
15668            );
15669            assert!(leftover.exists());
15670            assert!(!marker.exists());
15671            drop(external);
15672            runner.state.resource_block = None;
15673            let result = if graft {
15674                runner.graft().await
15675            } else {
15676                runner.recovery_repair(&winner).await
15677            };
15678            result.unwrap();
15679            assert!(!leftover.exists(), "restore must precede retry");
15680            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15681            if graft {
15682                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15683            } else {
15684                assert!(matches!(
15685                    runner.state.recovery.as_ref().unwrap().repair,
15686                    crate::recovery::Repair::Done { .. }
15687                ));
15688            }
15689        }
15690    }
15691
15692    #[tokio::test]
15693    #[cfg(unix)]
15694    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15695        use std::os::fd::AsRawFd as _;
15696        let tmp = tempfile::tempdir().unwrap();
15697        let mut runner = registered_runner(tmp.path()).await;
15698        runner.state.config.graph.timeout_resource_wait = 1;
15699        let winner = runner.state.candidates[0].clone();
15700        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15701        runner.state.tally = Some(Tally {
15702            first_choice: BTreeMap::new(),
15703            borda: BTreeMap::new(),
15704            winner: winner.label,
15705            rankings: 0,
15706            unanimous_initial: false,
15707            deliberated: false,
15708            changed_votes: 0,
15709            unanimous_final: false,
15710            tie_break: None,
15711            judges: 0,
15712            present: 0,
15713            quorum: 0,
15714            met_quorum: true,
15715            uncontested: Some("fixture".into()),
15716        });
15717        runner.state.graft = Some(GraftRecord {
15718            pre: pre.clone(),
15719            post: None,
15720            lines: None,
15721            limit: None,
15722            agent: None,
15723            outcome: GraftOutcome::Running,
15724            requested: Vec::new(),
15725            adoption: None,
15726            adoption_error: None,
15727        });
15728        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15729        git::commit_all(&winner.worktree, "unfinished graft")
15730            .await
15731            .unwrap();
15732        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15733        let leftover = winner.worktree.join("leftover");
15734        std::fs::write(&leftover, "untrusted edits").unwrap();
15735        let path = runner.state.repo.join(".git/updater.lock");
15736        let external = std::fs::File::create(&path).unwrap();
15737        assert_eq!(
15738            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15739            0
15740        );
15741        assert!(
15742            runner
15743                .graft()
15744                .await
15745                .unwrap_err()
15746                .is::<crate::repo_lock::ResourceBlocked>()
15747        );
15748        assert!(matches!(
15749            runner.state.graft.as_ref().unwrap().outcome,
15750            GraftOutcome::Running
15751        ));
15752        assert_eq!(
15753            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15754            unfinished
15755        );
15756        assert!(leftover.exists());
15757        drop(external);
15758        std::fs::remove_file(&path).unwrap();
15759        std::fs::create_dir(&path).unwrap();
15760        assert!(runner.graft().await.is_err());
15761        assert!(matches!(
15762            runner.state.graft.as_ref().unwrap().outcome,
15763            GraftOutcome::Running
15764        ));
15765        assert_eq!(
15766            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15767            unfinished
15768        );
15769        assert!(leftover.exists());
15770        std::fs::remove_dir(&path).unwrap();
15771        runner.graft().await.unwrap();
15772        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15773        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15774        assert!(!leftover.exists());
15775    }
15776
15777    #[tokio::test]
15778    #[cfg(unix)]
15779    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15780        use std::os::fd::AsRawFd as _;
15781        let tmp = tempfile::tempdir().unwrap();
15782        let mut runner = registered_runner(tmp.path()).await;
15783        runner.state.prep_complete = Some(false);
15784        runner.state.config.graph.timeout_resource_wait = 1;
15785        runner.state.save().unwrap();
15786        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15787        assert_eq!(
15788            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15789            0
15790        );
15791        runner.execute().await.unwrap();
15792        let disk = RunState::load(&runner.state.id).unwrap();
15793        assert!(disk.driver_exited);
15794        assert_eq!(disk.driver_pid, None);
15795        assert_eq!(runner.state.status, RunStatus::Blocked);
15796        assert_eq!(
15797            runner.state.resource_block.as_ref().unwrap().kind,
15798            "repository coordination"
15799        );
15800        assert!(runner.state.prep_failure.is_none());
15801        assert!(runner.state.seats.is_empty());
15802        runner.pause.park();
15803        // Include headroom for Git subprocesses under parallel test load;
15804        // the repository contention deadline itself remains one second.
15805        tokio::time::timeout(Duration::from_secs(10), runner.execute())
15806            .await
15807            .unwrap()
15808            .unwrap();
15809        assert!(runner.state.parked);
15810        assert!(runner.state.prep_failure.is_none());
15811        let disk = RunState::load(&runner.state.id).unwrap();
15812        assert!(disk.driver_exited);
15813        assert_eq!(disk.driver_pid, None);
15814    }
15815
15816    #[tokio::test]
15817    #[cfg(unix)]
15818    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
15819        use std::os::fd::AsRawFd as _;
15820        let tmp = tempfile::tempdir().unwrap();
15821        let mut runner = registered_runner(tmp.path()).await;
15822        runner.state.prep_complete = Some(false);
15823        runner.state.config.graph.timeout_resource_wait = 30;
15824        runner.state.save().unwrap();
15825        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15826        assert_eq!(
15827            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15828            0
15829        );
15830        assert!(
15831            tokio::time::timeout(Duration::from_millis(100), runner.execute())
15832                .await
15833                .is_err()
15834        );
15835        let disk = RunState::load(&runner.state.id).unwrap();
15836        assert!(disk.driver_exited);
15837        assert_eq!(disk.driver_pid, None);
15838        assert!(disk.status.resumable());
15839        assert!(runner.state.driver_exited);
15840        assert_eq!(runner.state.driver_pid, None);
15841        runner.state.save().unwrap();
15842        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
15843    }
15844
15845    #[tokio::test]
15846    #[cfg(unix)]
15847    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
15848        let tmp = tempfile::tempdir().unwrap();
15849        let mut runner = registered_runner(tmp.path()).await;
15850        let winner = runner.state.candidates[0].clone();
15851        let cache = tmp.path().join("cache");
15852        let started = tmp.path().join("pre-gate-started");
15853        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
15854        runner.state.config.verify.gate =
15855            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
15856        let home = crate::run::home();
15857        let owner =
15858            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
15859        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
15860            crate::cache::AcquireOutcome::Acquired(g) => g,
15861            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
15862        };
15863        let mut gate = Box::pin(runner.run_gate(&winner));
15864        assert!(
15865            tokio::time::timeout(Duration::from_millis(150), &mut gate)
15866                .await
15867                .is_err()
15868        );
15869        assert!(!started.exists(), "pre-gate must wait for the cache too");
15870        // Simulate the wave that already owns the cache entering invoke.
15871        // It must obtain the editor reservation and finish without waiting
15872        // for the gate that is queued behind its cache.
15873        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
15874        let editor = crate::repo_lock::SeatLease::checkout_with(
15875            &winner.worktree,
15876            true,
15877            crate::config::test_coordination().as_ref(),
15878            &wait,
15879        )
15880        .await
15881        .unwrap();
15882        drop(editor);
15883        guard.release();
15884        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15885            .await
15886            .unwrap()
15887            .unwrap();
15888        drop(gate);
15889        assert!(outcomes.iter().all(CommandOutcome::ok));
15890        assert!(started.exists());
15891    }
15892
15893    #[tokio::test]
15894    #[cfg(unix)]
15895    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
15896        use std::os::fd::AsRawFd as _;
15897
15898        ask_test_home();
15899        let tmp = tempfile::tempdir().unwrap();
15900        let repo = tmp.path().join("repo");
15901        std::fs::create_dir_all(&repo).unwrap();
15902        init_repo(&repo);
15903        let common = repo.join(".git");
15904        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
15905        let mut runner = runner_at(RunStatus::Prep);
15906        runner.state.repo = repo.clone();
15907        runner.state.config.coordination = crate::config::test_coordination();
15908        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15909        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
15910        runner.state.config.graph.advise = false;
15911        runner.roles.implementers = vec![spec("implement")];
15912        runner.roles.judges = vec![spec("judge")];
15913        runner.prep().await.unwrap();
15914        let winner = runner.state.candidates[0].clone();
15915        // Emulate edits already left by a completed seat. The fixture CLI
15916        // only reports completion; it performs no repository operations.
15917        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
15918        let completed = tmp.path().join("seat-completed");
15919        runner.roles.implementers[0].command = vec![
15920            "sh".into(),
15921            "-c".into(),
15922            format!("touch '{}'; echo completed", completed.display()),
15923        ];
15924        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
15925        assert_eq!(
15926            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15927            0
15928        );
15929        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15930        let mut implement = Box::pin(runner.implement());
15931        tokio::select! {
15932            result = &mut implement => panic!("rescue must wait: {result:?}"),
15933            result = tokio::time::timeout(Duration::from_secs(10), async {
15934                while !completed.exists() {
15935                    tokio::time::sleep(Duration::from_millis(20)).await;
15936                }
15937            }) => result.unwrap(),
15938        }
15939        assert!(
15940            tokio::time::timeout(Duration::from_millis(200), &mut implement)
15941                .await
15942                .is_err()
15943        );
15944        assert_eq!(
15945            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15946            before
15947        );
15948        assert_eq!(
15949            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15950            0
15951        );
15952        tokio::time::timeout(Duration::from_secs(10), &mut implement)
15953            .await
15954            .unwrap()
15955            .unwrap();
15956        drop(implement);
15957        assert_ne!(
15958            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15959            before
15960        );
15961        assert!(git::is_clean(&winner.worktree).await.unwrap());
15962
15963        let started = tmp.path().join("pre-gate-started");
15964        let proceed = tmp.path().join("pre-gate-proceed");
15965        let checked = tmp.path().join("gate-ran");
15966        runner.state.config.verify.pre_gate = vec![format!(
15967            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
15968            started.display(),
15969            proceed.display()
15970        )];
15971        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
15972        assert_eq!(
15973            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15974            0
15975        );
15976        let mut gate = Box::pin(runner.run_gate(&winner));
15977        assert!(
15978            tokio::time::timeout(Duration::from_millis(200), &mut gate)
15979                .await
15980                .is_err()
15981        );
15982        assert!(!started.exists());
15983        assert!(!checked.exists());
15984        assert!(git::is_clean(&winner.worktree).await.unwrap());
15985        assert_eq!(
15986            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15987            0
15988        );
15989        tokio::select! {
15990            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
15991            result = tokio::time::timeout(Duration::from_secs(10), async {
15992                while !started.exists() {
15993                    tokio::time::sleep(Duration::from_millis(20)).await;
15994                }
15995            }) => result.unwrap(),
15996        }
15997        assert_eq!(
15998            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15999            -1,
16000            "mechanical edits must hold the real lock"
16001        );
16002        std::fs::write(proceed, "ready").unwrap();
16003        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16004            .await
16005            .unwrap()
16006            .unwrap();
16007        drop(gate);
16008        assert!(outcomes.iter().all(CommandOutcome::ok));
16009        assert!(checked.exists());
16010        assert!(runner.state.pre_gate_commit.is_some());
16011        assert!(git::is_clean(&winner.worktree).await.unwrap());
16012        assert_eq!(
16013            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16014            0,
16015            "gate completion must release coordination"
16016        );
16017        drop(outsider);
16018        std::fs::remove_file(common.join("updater.lock")).unwrap();
16019        std::fs::create_dir(common.join("updater.lock")).unwrap();
16020        std::fs::remove_file(&started).unwrap();
16021        std::fs::remove_file(&checked).unwrap();
16022        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16023        let error = runner.run_gate(&winner).await.unwrap_err();
16024        assert!(
16025            error
16026                .to_string()
16027                .contains("acquire mandatory repository lock")
16028        );
16029        assert!(
16030            !started.exists(),
16031            "failed acquisition must prevent pre-gate"
16032        );
16033        assert!(!checked.exists(), "failed acquisition must prevent gate");
16034        assert!(git::is_clean(&winner.worktree).await.unwrap());
16035        assert_eq!(
16036            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16037            head
16038        );
16039    }
16040
16041    #[tokio::test]
16042    #[cfg(unix)]
16043    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16044        use std::os::fd::AsRawFd as _;
16045        use std::time::Duration;
16046
16047        ask_test_home();
16048        let tmp = tempfile::tempdir().unwrap();
16049        let repo = tmp.path().join("repo");
16050        std::fs::create_dir_all(&repo).unwrap();
16051        init_repo(&repo);
16052        let common = repo.join(".git");
16053        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16054        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16055        assert_eq!(
16056            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16057            0
16058        );
16059        let mut runner = runner_at(RunStatus::Prep);
16060        runner.state.repo = repo.clone();
16061        runner.state.config.coordination = crate::config::test_coordination();
16062        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16063        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16064        runner.state.config.graph.advise = true;
16065        runner.state.config.graph.advisors = 1;
16066        runner.roles.implementers = vec![spec("implement")];
16067        runner.roles.judges = vec![spec("judge")];
16068        let root = runner.state.worktree_root();
16069        let started = tmp.path().join("setup-started");
16070        let proceed = tmp.path().join("setup-proceed");
16071        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16072            run: Some(format!(
16073                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16074                started.display(),
16075                proceed.display()
16076            )),
16077            ..Default::default()
16078        }];
16079        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16080        let config = git::git(&repo, &["config", "--local", "--list"])
16081            .await
16082            .unwrap();
16083        let mut prep = Box::pin(runner.prep());
16084        assert!(
16085            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16086                .await
16087                .is_err()
16088        );
16089        assert!(
16090            !root.exists(),
16091            "contention must prevent even checkout creation"
16092        );
16093        assert!(!started.exists(), "contention must prevent setup");
16094        assert_eq!(
16095            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16096            branches
16097        );
16098        assert_eq!(
16099            git::git(&repo, &["config", "--local", "--list"])
16100                .await
16101                .unwrap(),
16102            config
16103        );
16104        drop(lock);
16105        tokio::select! {
16106            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16107            result = tokio::time::timeout(Duration::from_secs(10), async {
16108                while !started.exists() {
16109                    tokio::time::sleep(Duration::from_millis(20)).await;
16110                }
16111            }) => result.unwrap(),
16112        }
16113        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16114        assert_eq!(
16115            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16116            -1
16117        );
16118        assert!(
16119            tokio::time::timeout(
16120                Duration::from_millis(100),
16121                crate::repo_lock::SeatLease::for_checkout(
16122                    &repo,
16123                    true,
16124                    crate::config::test_coordination().as_ref()
16125                )
16126            )
16127            .await
16128            .is_err(),
16129            "preparation must also exclude local editors"
16130        );
16131        std::fs::write(proceed, "ready").unwrap();
16132        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16133            .await
16134            .unwrap()
16135            .unwrap();
16136        drop(prep);
16137        assert_eq!(runner.state.prep_complete, Some(true));
16138        assert!(root.join("judge-1").exists());
16139        assert!(root.join("advisor-1").exists());
16140        assert_eq!(
16141            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16142            0
16143        );
16144    }
16145
16146    #[tokio::test]
16147    #[cfg(unix)]
16148    async fn preparation_lock_failure_prevents_repository_changes() {
16149        ask_test_home();
16150        let tmp = tempfile::tempdir().unwrap();
16151        let repo = tmp.path().join("repo");
16152        std::fs::create_dir_all(&repo).unwrap();
16153        init_repo(&repo);
16154        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16155        // A directory at the required lock path makes opening the real lock
16156        // fail, rather than merely exercising an invalid registration.
16157        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16158        let mut runner = runner_at(RunStatus::Prep);
16159        runner.state.repo = repo.clone();
16160        runner.state.config.coordination = crate::config::test_coordination();
16161        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16162        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16163        runner.roles.implementers = vec![spec("implement")];
16164        let error = runner.prep().await.unwrap_err();
16165        assert!(
16166            error
16167                .to_string()
16168                .contains("acquire mandatory repository lock")
16169        );
16170        assert!(!runner.state.worktree_root().exists());
16171        assert!(runner.state.candidates.is_empty());
16172        assert!(!repo.join(".git/config.worktree").exists());
16173        assert_eq!(
16174            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16175            "* main"
16176        );
16177    }
16178
16179    #[tokio::test]
16180    async fn preparation_records_creation_intent_before_git_can_fail() {
16181        ask_test_home();
16182        let tmp = tempfile::tempdir().unwrap();
16183        let repo = tmp.path().join("repo");
16184        std::fs::create_dir_all(&repo).unwrap();
16185        init_repo(&repo);
16186        let mut runner = runner_at(RunStatus::Prep);
16187        runner.state.repo = repo.clone();
16188        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16189        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16190        runner.state.config.blind.commit_msg_hook = false;
16191        runner.roles.implementers = vec![spec("one")];
16192        let label = blind::assign_labels(1, runner.state.seed)[0];
16193        let branch = runner.state.branch_for(label);
16194        // A conflicting branch makes Git refuse creation before a candidate
16195        // can be registered. The durable intent must still identify it.
16196        git::git(&repo, &["branch", &branch]).await.unwrap();
16197        assert!(runner.prep().await.is_err());
16198        let saved = RunState::load(&runner.state.id).unwrap();
16199        assert!(saved.candidates.is_empty());
16200        let event = saved
16201            .events
16202            .iter()
16203            .find(|e| e.node == "prep-intent")
16204            .unwrap();
16205        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16206        assert_eq!(intent["branch"], branch);
16207        assert_eq!(intent["start"], runner.state.base_commit);
16208        assert_eq!(
16209            intent["worktree"],
16210            runner
16211                .state
16212                .worktree_root()
16213                .join(format!("cand-{label}"))
16214                .to_string_lossy()
16215                .as_ref()
16216        );
16217        assert_eq!(intent["picks"], serde_json::json!([]));
16218    }
16219
16220    #[tokio::test]
16221    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16222        ask_test_home();
16223        let tmp = tempfile::tempdir().unwrap();
16224        let repo = tmp.path().join("repo");
16225        std::fs::create_dir_all(&repo).unwrap();
16226        init_repo(&repo);
16227        let mut runner = runner_at(RunStatus::Prep);
16228        runner.state.repo = repo.clone();
16229        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16230        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16231        runner.state.sources.pick_commits.push(refs::Input {
16232            token: "missing".into(),
16233            sha: "0".repeat(40),
16234            provenance: refs::Provenance::ExplicitCli,
16235        });
16236        assert!(runner.prep().await.is_err());
16237        assert!(runner.state.candidates.is_empty());
16238        assert!(!runner.state.worktree_root().exists());
16239    }
16240
16241    #[tokio::test]
16242    async fn prose_and_legacy_inference_never_import_into_candidates() {
16243        ask_test_home();
16244        let tmp = tempfile::tempdir().unwrap();
16245        let repo = tmp.path().join("repo");
16246        std::fs::create_dir_all(&repo).unwrap();
16247        init_repo(&repo);
16248        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16249        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16250            .await
16251            .unwrap();
16252        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16253        git::git(&repo, &["add", "."]).await.unwrap();
16254        git::git(&repo, &["commit", "-m", "historical implementation"])
16255            .await
16256            .unwrap();
16257        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16258        git::git(&repo, &["checkout", "main"]).await.unwrap();
16259        for instruction in [
16260            format!("Example: magi/history/A at {source}"),
16261            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16262            format!("Never import magi/history/A or {source}"),
16263            format!("Conversation answer: I mentioned {source} only as background"),
16264        ] {
16265            let mut runner = runner_at(RunStatus::Prep);
16266            runner.state.repo = repo.clone();
16267            runner.state.base_commit = base.clone();
16268            runner.state.instruction = instruction.clone();
16269            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16270            runner.state.config.blind.commit_msg_hook = false;
16271            runner.state.seeds = vec![refs::Seed {
16272                token: "magi/history/A".into(),
16273                sha: source.clone(),
16274                kind: refs::SeedKind::Unmerged,
16275                branch: true,
16276                detail: String::new(),
16277            }];
16278            runner.roles.implementers = vec![spec("one")];
16279            assert_eq!(seeded_instruction(&runner.state), instruction);
16280            // Model an old record with inferred seeds but no structured input field.
16281            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16282            legacy.as_object_mut().unwrap().remove("sources");
16283            runner.state = serde_json::from_value(legacy).unwrap();
16284            assert_eq!(runner.state.sources, refs::Sources::default());
16285            runner.state.save().unwrap();
16286            runner.state = RunState::load(&runner.state.id).unwrap();
16287            runner.prep().await.unwrap();
16288            for candidate in &runner.state.candidates {
16289                assert_eq!(
16290                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16291                    base
16292                );
16293                assert!(!candidate.worktree.join("unwanted").exists());
16294            }
16295        }
16296    }
16297
16298    #[tokio::test]
16299    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16300        ask_test_home();
16301        let tmp = tempfile::tempdir().unwrap();
16302        let repo = tmp.path().join("repo");
16303        std::fs::create_dir_all(&repo).unwrap();
16304        init_repo(&repo);
16305        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16306        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16307        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16308        git::git(&repo, &["add", "."]).await.unwrap();
16309        git::git(&repo, &["commit", "-m", "required seed"])
16310            .await
16311            .unwrap();
16312        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16313        git::git(&repo, &["checkout", "main"]).await.unwrap();
16314        let mut runner = runner_at(RunStatus::Prep);
16315        runner.state.repo = repo.clone();
16316        runner.state.base_commit = base.clone();
16317        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16318        runner.state.config.graph.advise = false;
16319        runner.state.config.blind.commit_msg_hook = false;
16320        runner.state.sources =
16321            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16322                .await
16323                .unwrap();
16324        runner.roles.implementers = vec![spec("one"), spec("two")];
16325        runner.roles.judges = vec![spec("judge")];
16326        let label = blind::assign_labels(2, runner.state.seed)[0];
16327        let branch = runner.state.branch_for(label);
16328        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16329        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16330            .await
16331            .unwrap();
16332        runner.state.candidates.push(Candidate {
16333            index: 0,
16334            label,
16335            agent: "one".into(),
16336            branch,
16337            worktree,
16338            summary: String::new(),
16339            stat: String::new(),
16340            files: 0,
16341            commits: 0,
16342            empty: false,
16343            failed: None,
16344            verified_noop: None,
16345            duration_ms: 0,
16346            folded: false,
16347        });
16348        runner.state.save().unwrap();
16349        // Reload the checkpoint immediately before its first cherry-pick.
16350        runner.state = RunState::load(&runner.state.id).unwrap();
16351        assert_eq!(runner.state.prep_complete, Some(false));
16352        runner.prep().await.unwrap();
16353        assert_eq!(runner.state.prep_complete, Some(true));
16354        assert_eq!(runner.state.candidates.len(), 2);
16355        for candidate in &runner.state.candidates {
16356            assert_eq!(
16357                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16358                git::tree_of(&repo, &seed).await.unwrap()
16359            );
16360            assert_eq!(
16361                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16362                "required commit"
16363            );
16364        }
16365        assert!(runner.state.worktree_root().join("judge-1").exists());
16366        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16367        runner.prep().await.unwrap();
16368        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16369
16370        runner.state.prep_complete = Some(false);
16371        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16372            run: Some(format!(
16373                "test -f '{}'",
16374                tmp.path().join("dependency-ready").display()
16375            )),
16376            ..Default::default()
16377        }];
16378        assert!(runner.prep().await.is_err());
16379        assert!(runner.state.prep_failure.is_some());
16380        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16381        runner.state = RunState::load(&runner.state.id).unwrap();
16382        assert!(
16383            runner.prep().await.is_err(),
16384            "correcting the cause alone must not auto-retry"
16385        );
16386        let failed_at = runner.state.events.last().unwrap().at;
16387        assert!(
16388            runner.retry_preparation(failed_at).is_err(),
16389            "old approvals cannot unlock the hold"
16390        );
16391        let mut task = crate::queue::Task::new(
16392            "retry".into(),
16393            "retry setup".into(),
16394            repo.clone(),
16395            crate::queue::Source::Human,
16396        );
16397        task.start(runner.state.id.clone());
16398        task.hold_machine(Some("setup failed".into()));
16399        task.release_operator("cli", None);
16400        runner
16401            .retry_preparation(task.resumption.as_ref().unwrap().at)
16402            .unwrap();
16403        runner.prep().await.unwrap();
16404        assert!(runner.state.prep_failure.is_none());
16405        assert_eq!(runner.state.prep_complete, Some(true));
16406        assert_eq!(runner.state.candidates.len(), 2);
16407        assert!(runner.state.worktree_root().join("judge-1").exists());
16408        for candidate in &runner.state.candidates {
16409            assert_eq!(
16410                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16411                git::tree_of(&repo, &seed).await.unwrap()
16412            );
16413        }
16414    }
16415
16416    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16417        let mut heads = Vec::new();
16418        for candidate in candidates {
16419            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16420        }
16421        heads
16422    }
16423
16424    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16425        ask_test_home();
16426        let tmp = tempfile::tempdir().unwrap();
16427        let repo = tmp.path().join("repo");
16428        std::fs::create_dir(&repo).unwrap();
16429        init_repo(&repo);
16430        let mut runner = runner_at(RunStatus::Reviewing);
16431        runner.state.repo = repo.clone();
16432        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16433        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16434        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16435            let branch = format!("candidate-{label}");
16436            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16437            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16438                .await
16439                .unwrap();
16440            if label == 'B' {
16441                std::fs::write(worktree.join("change"), "winner").unwrap();
16442                git::rescue_commit(&worktree, "candidate change")
16443                    .await
16444                    .unwrap();
16445            }
16446            runner.state.candidates.push(Candidate {
16447                index,
16448                label,
16449                agent: "alpha".into(),
16450                branch,
16451                worktree,
16452                summary: "completed reply".into(),
16453                stat: String::new(),
16454                files: usize::from(label == 'B'),
16455                commits: usize::from(label == 'B'),
16456                empty: label == 'A',
16457                failed: None,
16458                verified_noop: None,
16459                duration_ms: 1,
16460                folded: false,
16461            });
16462        }
16463        runner.state.judge_skipped = true;
16464        runner.state.tally = Some(Tally {
16465            first_choice: BTreeMap::new(),
16466            borda: BTreeMap::new(),
16467            winner: 'B',
16468            rankings: 0,
16469            unanimous_initial: false,
16470            deliberated: false,
16471            changed_votes: 0,
16472            unanimous_final: false,
16473            tie_break: None,
16474            judges: 0,
16475            present: 0,
16476            quorum: 0,
16477            met_quorum: true,
16478            uncontested: Some("only B produced a change".into()),
16479        });
16480        runner.state.save().unwrap();
16481        (tmp, runner)
16482    }
16483
16484    #[tokio::test]
16485    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16486        let (_tmp, mut runner) = preservation_resume_fixture().await;
16487        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16488        runner.state.config.disk.cache_limit_bytes = 0;
16489        runner.state.config.graph.advise = true;
16490        runner.state.config.graph.advisors = 1;
16491        let advisor = runner.state.worktree_root().join("advisor-1");
16492        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16493            .await
16494            .unwrap();
16495        let home = crate::run::home();
16496        let loser =
16497            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16498        let winner =
16499            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16500        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16501        for target in [&loser, &winner, &advisor] {
16502            std::fs::write(target.join("build-output"), "compiled").unwrap();
16503        }
16504
16505        runner.fold_losers().await.unwrap();
16506
16507        assert!(!loser.join("build-output").exists());
16508        assert!(!advisor.join("build-output").exists());
16509        assert!(winner.join("build-output").is_file());
16510    }
16511
16512    #[tokio::test]
16513    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16514        let (_tmp, mut runner) = preservation_resume_fixture().await;
16515        runner.state.candidates[0].folded = true;
16516        runner.state.config.graph.advise = true;
16517        runner.state.config.graph.advisors = 2;
16518        let repo = runner.state.repo.clone();
16519        let root = runner.state.worktree_root();
16520        let discarded = root.join("advisor-1");
16521        git::worktree_add_detached(&repo, &discarded, "main")
16522            .await
16523            .unwrap();
16524        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16525        let protected = root.join("advisor-2");
16526        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16527            .await
16528            .unwrap();
16529        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16530        runner.state.save().unwrap();
16531
16532        assert!(runner.fold_losers().await.is_err());
16533        assert!(!discarded.exists());
16534        assert!(protected.join("keep").exists());
16535        let saved = RunState::load(&runner.state.id).unwrap();
16536        assert!(saved.events.iter().any(|event| {
16537            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16538        }));
16539    }
16540
16541    #[tokio::test]
16542    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16543        let (tmp, mut runner) = preservation_resume_fixture().await;
16544        let repo = runner.state.repo.clone();
16545        let root = runner.state.worktree_root();
16546        for name in ["advisor-3", "judge-1", "review-2"] {
16547            let path = root.join(name);
16548            git::worktree_add_detached(&repo, &path, "main")
16549                .await
16550                .unwrap();
16551            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16552            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16553            remove_read_seat_worktree(&mut runner.state, &path)
16554                .await
16555                .unwrap();
16556            assert!(!path.exists());
16557        }
16558        let outside = tmp.path().join("advisor-1");
16559        let unknown = root.join("unknown");
16560        let attached = root.join("advisor-4");
16561        git::worktree_add_detached(&repo, &outside, "main")
16562            .await
16563            .unwrap();
16564        git::worktree_add_detached(&repo, &unknown, "main")
16565            .await
16566            .unwrap();
16567        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16568            .await
16569            .unwrap();
16570        let foreign = tmp.path().join("foreign");
16571        std::fs::create_dir(&foreign).unwrap();
16572        init_repo(&foreign);
16573        let wrong_repo = root.join("judge-2");
16574        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16575            .await
16576            .unwrap();
16577        let candidate = runner.state.candidates[0].worktree.clone();
16578        for path in [outside, unknown, attached, wrong_repo, candidate] {
16579            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16580            assert!(
16581                remove_read_seat_worktree(&mut runner.state, &path)
16582                    .await
16583                    .is_err()
16584            );
16585            assert_eq!(
16586                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16587                "keep"
16588            );
16589        }
16590    }
16591
16592    #[tokio::test]
16593    #[cfg(unix)]
16594    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16595        for (solo, failed_checkpoint) in
16596            [(true, false), (false, false), (true, true), (false, true)]
16597        {
16598            let (_tmp, mut runner) = preservation_resume_fixture().await;
16599            if solo {
16600                runner.state.candidates.retain(|c| c.label == 'A');
16601            }
16602            runner.state.candidates[0].empty = false;
16603            runner.state.candidates[0].summary.clear();
16604            runner.state.tally = None;
16605            runner.state.judge_skipped = false;
16606            runner.state.status = RunStatus::Implementing;
16607            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16608            let mut implementer = spec("alpha");
16609            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16610            runner.roles.implementers = vec![implementer];
16611            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16612            if failed_checkpoint {
16613                std::fs::create_dir_all(&patch).unwrap();
16614            }
16615            runner.state.save().unwrap();
16616            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16617            drop(pressure);
16618            runner.state = RunState::load(&runner.state.id).unwrap();
16619            assert_eq!(runner.state.status, RunStatus::Blocked);
16620            assert!(runner.state.interrupted_implementations.contains(&'A'));
16621            assert_eq!(runner.state.candidates[0].commits, 0);
16622            assert!(!runner.state.candidates[0].empty);
16623            assert!(runner.state.candidates[0].failed.is_none());
16624            if failed_checkpoint {
16625                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16626                std::fs::remove_dir(patch).unwrap();
16627            }
16628            runner.state.resource_block = None;
16629            runner.state.config.disk.min_free_bytes = 0;
16630            runner.roles.implementers[0].command = vec![
16631                "sh".into(),
16632                "-c".into(),
16633                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16634            ];
16635            runner.implement().await.unwrap();
16636            assert!(runner.state.interrupted_implementations.is_empty());
16637            assert!(runner.state.candidate_preservation.is_empty());
16638            assert_eq!(runner.state.candidates[0].commits, 1);
16639            assert!(!runner.state.candidates[0].empty);
16640            assert!(
16641                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16642                    .unwrap()
16643                    .contains("retried empty interrupted seat")
16644            );
16645            if !solo {
16646                assert_eq!(runner.state.candidates[1].commits, 1);
16647            }
16648        }
16649    }
16650
16651    #[tokio::test]
16652    #[cfg(unix)]
16653    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16654        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16655            let (_tmp, mut runner) = preservation_resume_fixture().await;
16656            runner.state.candidates.retain(|c| c.label == 'A');
16657            runner.state.candidates[0].empty = false;
16658            runner.state.candidates[0].summary.clear();
16659            runner.state.tally = None;
16660            runner.state.judge_skipped = false;
16661            runner.state.status = RunStatus::Implementing;
16662            // Force only the real post-spawn watchdog, without failing the
16663            // separate admission check. Existing edits predate its measurement.
16664            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16665            let wt = runner.state.candidates[0].worktree.clone();
16666            std::fs::write(
16667                wt.join("interrupted-source"),
16668                "retain implementation work\n",
16669            )
16670            .unwrap();
16671            if committed {
16672                git::rescue_commit(&wt, "implementation checkpoint")
16673                    .await
16674                    .unwrap();
16675            }
16676            let lock = git::git(
16677                &wt,
16678                &[
16679                    "rev-parse",
16680                    "--path-format=absolute",
16681                    "--git-path",
16682                    "index.lock",
16683                ],
16684            )
16685            .await
16686            .unwrap();
16687            if block_rescue {
16688                std::fs::write(&lock, "fixture-owned lock").unwrap();
16689            }
16690            let mut implementer = spec("alpha");
16691            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16692            runner.roles.implementers = vec![implementer];
16693            runner.state.save().unwrap();
16694            let result = runner.implement().await;
16695            drop(pressure);
16696            assert_eq!(result.is_err(), block_rescue);
16697            assert_eq!(
16698                runner.state.resource_block.as_ref().unwrap().kind,
16699                "disk pressure"
16700            );
16701            assert!(
16702                runner
16703                    .state
16704                    .events
16705                    .iter()
16706                    .any(|e| e.message.contains("agent execution interrupted"))
16707            );
16708            assert!(
16709                runner
16710                    .state
16711                    .dir()
16712                    .join("artifacts/candidate-A-recovery/staged.patch")
16713                    .exists()
16714            );
16715            if block_rescue {
16716                let saved = RunState::load(&runner.state.id).unwrap();
16717                assert!(saved.candidate_preservation.contains_key(&'A'));
16718                assert!(!saved.candidates[0].empty);
16719                assert_eq!(
16720                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16721                    "retain implementation work\n"
16722                );
16723                std::fs::remove_file(lock).unwrap();
16724                runner.state = saved;
16725            } else {
16726                assert_eq!(runner.state.status, RunStatus::Blocked);
16727                assert_eq!(runner.state.candidates[0].commits, 1);
16728            }
16729            // Recovery must save the candidate before deciding whether another
16730            // implementation is needed. No implementer is available on retry.
16731            runner.roles.implementers.clear();
16732            runner.state.config.disk.min_free_bytes = 0;
16733            runner.state.resource_block = None;
16734            runner.implement().await.unwrap();
16735            assert!(runner.state.candidate_preservation.is_empty());
16736            assert_eq!(runner.state.candidates[0].commits, 1);
16737            assert!(!runner.state.candidates[0].empty);
16738            assert!(git::is_clean(&wt).await.unwrap());
16739            assert!(
16740                crate::run::read_artifact(&runner.state, "cand-A.patch")
16741                    .unwrap()
16742                    .contains("retain implementation work")
16743            );
16744        }
16745    }
16746
16747    #[tokio::test]
16748    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16749        let (_tmp, mut runner) = preservation_resume_fixture().await;
16750        // Schema 15 already confirmed the unfolded no-change result.
16751        runner.implement().await.unwrap();
16752        assert!(runner.state.candidate_preservation.is_empty());
16753        assert!(
16754            !runner
16755                .state
16756                .dir()
16757                .join("artifacts/candidate-A-recovery")
16758                .exists()
16759        );
16760        runner.fold_losers().await.unwrap();
16761        assert!(!runner.state.candidates[0].worktree.exists());
16762        for schema in [14, crate::run::SCHEMA] {
16763            runner.state.schema = schema;
16764            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16765            runner.state.save().unwrap();
16766            runner.state = RunState::load(&runner.state.id).unwrap();
16767            runner.implement().await.unwrap();
16768            assert!(runner.state.candidate_preservation.is_empty());
16769            assert!(runner.state.candidates[0].folded);
16770            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16771        }
16772    }
16773
16774    #[tokio::test]
16775    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16776        let (_tmp, mut runner) = preservation_resume_fixture().await;
16777        runner.state.candidates.retain(|c| c.label == 'A');
16778        runner.state.tally = None;
16779        runner.state.judge_skipped = false;
16780        let candidate = &mut runner.state.candidates[0];
16781        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16782        candidate.failed = Some("deployment validation unavailable".into());
16783        std::fs::write(
16784            candidate.worktree.join("repair"),
16785            "future launcher policy\n",
16786        )
16787        .unwrap();
16788        runner
16789            .state
16790            .candidate_preservation
16791            .insert('A', "awaiting persistence".into());
16792        runner.persist_candidates().await.unwrap();
16793        let candidate = &runner.state.candidates[0];
16794        assert!(!candidate.empty);
16795        assert_eq!(candidate.commits, 1);
16796        assert_eq!(candidate.files, 1);
16797        assert!(candidate.failed.is_none());
16798        assert!(candidate.summary.contains("EPERM"));
16799        assert!(
16800            crate::run::read_artifact(&runner.state, "cand-A.patch")
16801                .unwrap()
16802                .contains("future launcher policy")
16803        );
16804        assert!(runner.state.candidate_preservation.is_empty());
16805    }
16806
16807    #[tokio::test]
16808    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
16809        let (_tmp, mut runner) = preservation_resume_fixture().await;
16810        let wt = runner.state.candidates[0].worktree.clone();
16811        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
16812        runner.state.schema = 14;
16813        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16814        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16815        let tally = serde_json::to_value(&runner.state.tally).unwrap();
16816        for _ in 0..2 {
16817            assert!(runner.implement().await.is_err());
16818            assert_eq!(runner.state.status, RunStatus::Blocked);
16819            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16820            assert!(
16821                runner.state.candidates[0].empty,
16822                "old verdict must remain unusable"
16823            );
16824            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
16825            assert!(runner.state.judge_skipped);
16826            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
16827            assert!(
16828                crate::run::read_artifact(&runner.state, "cand-A.patch")
16829                    .unwrap()
16830                    .contains("owned edits")
16831            );
16832            assert!(wt.exists());
16833            assert_eq!(
16834                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
16835                    .await
16836                    .unwrap(),
16837                1
16838            );
16839            runner.state = RunState::load(&runner.state.id).unwrap();
16840        }
16841    }
16842
16843    #[tokio::test]
16844    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
16845        let (_tmp, mut runner) = preservation_resume_fixture().await;
16846        let wt = runner.state.candidates[0].worktree.clone();
16847        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
16848        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
16849        let index_lock = PathBuf::from(
16850            git::git(
16851                &wt,
16852                &[
16853                    "rev-parse",
16854                    "--path-format=absolute",
16855                    "--git-path",
16856                    "index.lock",
16857                ],
16858            )
16859            .await
16860            .unwrap(),
16861        );
16862        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16863        runner.state.schema = 14;
16864        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16865        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16866        assert!(runner.implement().await.is_err());
16867        assert!(runner.after_implement().is_err());
16868        assert!(runner.fold_losers().await.is_err());
16869        assert_eq!(
16870            std::fs::read_to_string(wt.join("recovered")).unwrap(),
16871            "failed seat edits"
16872        );
16873        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16874        runner.state = RunState::load(&runner.state.id).unwrap();
16875        std::fs::remove_file(index_lock).unwrap();
16876        // Recovery finds changes that the old uncontested result never judged.
16877        assert!(runner.implement().await.is_err());
16878        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16879        assert!(runner.state.candidates[0].empty);
16880        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16881        assert!(
16882            crate::run::read_artifact(&runner.state, "cand-A.patch")
16883                .unwrap()
16884                .contains("failed seat edits")
16885        );
16886        assert!(wt.exists());
16887    }
16888
16889    #[tokio::test]
16890    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
16891        let (_tmp, mut runner) = preservation_resume_fixture().await;
16892        let repo = runner.state.repo.clone();
16893        let common = git::git(
16894            &repo,
16895            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
16896        )
16897        .await
16898        .unwrap();
16899        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
16900        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
16901        assert!(runner.fold_losers().await.is_err());
16902        assert!(!runner.state.candidates[0].worktree.exists());
16903        assert!(!runner.state.candidates[0].folded);
16904        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
16905        runner.state = RunState::load(&runner.state.id).unwrap();
16906        std::fs::remove_file(branch_lock).unwrap();
16907        let judge = runner.state.worktree_root().join("judge-1");
16908        git::worktree_add_detached(&repo, &judge, "main")
16909            .await
16910            .unwrap();
16911        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
16912        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
16913            .await
16914            .unwrap();
16915        runner.roles.judges = vec![spec("judge")];
16916        assert!(runner.fold_losers().await.is_err());
16917        runner.state = RunState::load(&runner.state.id).unwrap();
16918        assert!(
16919            runner.state.candidates[0].folded,
16920            "candidate progress saved before judge failure"
16921        );
16922        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
16923        assert!(judge.join("uncommitted").exists());
16924        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
16925            .await
16926            .unwrap();
16927        runner.fold_losers().await.unwrap();
16928        assert!(!judge.exists());
16929        runner.fold_losers().await.unwrap();
16930    }
16931
16932    #[tokio::test]
16933    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
16934        let (_tmp, mut runner) = preservation_resume_fixture().await;
16935        runner.state.candidates.retain(|c| c.label == 'B');
16936        runner.state.tally = None;
16937        runner.state.judge_skipped = false;
16938        runner.state.prep_complete = Some(true);
16939        runner.state.config.graph.advise = false;
16940        runner.state.config.graph.selected_implementer = Some("alpha".into());
16941        let wt = runner.state.candidates[0].worktree.clone();
16942        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
16943        runner
16944            .state
16945            .candidate_preservation
16946            .insert('B', "awaiting persistence".into());
16947        let index_lock = git::git(
16948            &wt,
16949            &[
16950                "rev-parse",
16951                "--path-format=absolute",
16952                "--git-path",
16953                "index.lock",
16954            ],
16955        )
16956        .await
16957        .unwrap();
16958        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16959        runner.state.save().unwrap();
16960        assert!(runner.execute_graph().await.is_err());
16961        assert_eq!(runner.state.status, RunStatus::Blocked);
16962        assert!(runner.state.candidate_preservation.contains_key(&'B'));
16963        std::fs::remove_file(index_lock).unwrap();
16964        // Park at the next graph boundary: this tests the real selected-seat
16965        // hold guard without dispatching reviewers or publishing anything.
16966        for _ in 0..2 {
16967            runner.state = RunState::load(&runner.state.id).unwrap();
16968            runner.pause.park();
16969            runner.execute_graph().await.unwrap();
16970            assert_eq!(runner.state.status, RunStatus::Implementing);
16971            assert!(runner.state.candidate_preservation.is_empty());
16972            assert_eq!(runner.state.candidates[0].commits, 2);
16973            assert!(runner.state.tally.is_none());
16974        }
16975        runner.implement().await.unwrap();
16976        assert_eq!(runner.state.status, RunStatus::Judging);
16977        // A genuine selected-implementer hold must still require release.
16978        runner.state.status = RunStatus::Blocked;
16979        runner.state.candidates[0].failed = Some("implementation failed".into());
16980        runner.state.save().unwrap();
16981        let error = runner.execute_graph().await.unwrap_err();
16982        assert!(
16983            error
16984                .to_string()
16985                .contains("selected implementation is held")
16986        );
16987    }
16988
16989    #[tokio::test]
16990    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
16991        let (_tmp, mut runner) = preservation_resume_fixture().await;
16992        let repo = runner.state.repo.clone();
16993        let candidate = runner.state.candidates[0].clone();
16994        // Remove only the disposable fixture directory, leaving Git's linked
16995        // worktree registration and branch intact, as in a vanished checkout.
16996        let registered = git::worktree_holding(&repo, &candidate.branch)
16997            .await
16998            .unwrap()
16999            .unwrap();
17000        assert_eq!(
17001            registered.canonicalize().unwrap(),
17002            candidate.worktree.canonicalize().unwrap()
17003        );
17004        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17005        assert_eq!(
17006            git::worktree_holding(&repo, &candidate.branch)
17007                .await
17008                .unwrap(),
17009            Some(registered)
17010        );
17011        assert!(
17012            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17013            "the stale registration initially keeps the branch checked out"
17014        );
17015        runner.fold_losers().await.unwrap();
17016        assert!(runner.state.candidates[0].folded);
17017        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17018        assert_eq!(
17019            git::worktree_holding(&repo, &candidate.branch)
17020                .await
17021                .unwrap(),
17022            None
17023        );
17024        runner.state = RunState::load(&runner.state.id).unwrap();
17025        runner.fold_losers().await.unwrap();
17026    }
17027
17028    #[tokio::test]
17029    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17030        let (_tmp, mut runner) = preservation_resume_fixture().await;
17031        let repo = runner.state.repo.clone();
17032        let candidate = runner.state.candidates[0].clone();
17033        let winner = runner.state.candidates[1].clone();
17034        let registered = git::worktree_holding(&repo, &candidate.branch)
17035            .await
17036            .unwrap()
17037            .unwrap();
17038        assert_eq!(
17039            registered.canonicalize().unwrap(),
17040            candidate.worktree.canonicalize().unwrap()
17041        );
17042        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17043        assert_eq!(
17044            git::worktree_holding(&repo, &candidate.branch)
17045                .await
17046                .unwrap(),
17047            Some(registered)
17048        );
17049        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17050
17051        for _ in 0..2 {
17052            fold_run(&mut runner.state, false, &crate::run::home())
17053                .await
17054                .unwrap();
17055            runner.state = RunState::load(&runner.state.id).unwrap();
17056            assert!(runner.state.candidates[0].folded);
17057            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17058            assert_eq!(
17059                git::worktree_holding(&repo, &candidate.branch)
17060                    .await
17061                    .unwrap(),
17062                None
17063            );
17064            assert!(!runner.state.candidates[1].folded);
17065            assert!(winner.worktree.exists());
17066            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17067        }
17068    }
17069    #[tokio::test]
17070    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17071        for sidecar in [false, true] {
17072            let tmp = tempfile::tempdir().unwrap();
17073            let home = tmp.path().join("home");
17074            let repo = tmp.path().join("repo");
17075            std::fs::create_dir(&repo).unwrap();
17076            init_repo(&repo);
17077            let mut state = runner_at(RunStatus::Superseded).state;
17078            state.repo = repo.clone();
17079            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17080            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17081            state.driver_exited = true;
17082            state.reserve_under(&home).unwrap();
17083            git::git(
17084                &repo,
17085                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17086            )
17087            .await
17088            .unwrap();
17089            let wt = state.worktree_root().join("cand-A");
17090            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17091                .await
17092                .unwrap();
17093            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17094            git::commit_all(&wt, "fixture: independent source")
17095                .await
17096                .unwrap();
17097            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17098            state.candidates.push(Candidate {
17099                index: 0,
17100                label: 'A',
17101                agent: "fixture".into(),
17102                branch: "candidate".into(),
17103                worktree: wt.clone(),
17104                summary: String::new(),
17105                stat: String::new(),
17106                files: 0,
17107                commits: 0,
17108                empty: false,
17109                failed: None,
17110                verified_noop: None,
17111                duration_ms: 0,
17112                folded: false,
17113            });
17114            let mut task = crate::queue::Task::new(
17115                "task".into(),
17116                "task".into(),
17117                repo.clone(),
17118                crate::queue::Source::Human,
17119            );
17120            task.runs.push(state.id.clone());
17121            crate::queue::Queue::at(home.join("queue"))
17122                .put(&mut task)
17123                .unwrap();
17124            if sidecar {
17125                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17126            }
17127            state.save_under(&home).unwrap();
17128            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17129            assert!(
17130                fold_run(&mut state, true, &home)
17131                    .await
17132                    .unwrap_err()
17133                    .to_string()
17134                    .contains(&reason)
17135            );
17136            let mut disk = state.config.disk.clone();
17137            disk.fold_grace_secs = 0;
17138            assert_eq!(
17139                crate::clean::fold_due(
17140                    &home.join("runs"),
17141                    &home,
17142                    &state.worktree_root(),
17143                    &disk,
17144                    Timestamp::now() + std::time::Duration::from_secs(10),
17145                )
17146                .await
17147                .unwrap(),
17148                (0, 0)
17149            );
17150            assert!(wt.exists());
17151            state.status = RunStatus::Blocked;
17152            state.save_under(&home).unwrap();
17153            assert!(
17154                fold_run_overriding_recovery_retention(&mut state, true, &home)
17155                    .await
17156                    .is_err()
17157            );
17158            state.status = RunStatus::Superseded;
17159            state.driver_exited = false;
17160            state.driver_claimed = None;
17161            state.save_under(&home).unwrap();
17162            assert!(
17163                fold_run_overriding_recovery_retention(&mut state, true, &home)
17164                    .await
17165                    .is_err()
17166            );
17167            state.driver_pid = Some(std::process::id());
17168            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17169            state.save_under(&home).unwrap();
17170            assert!(
17171                fold_run_overriding_recovery_retention(&mut state, true, &home)
17172                    .await
17173                    .is_err()
17174            );
17175            state.driver_exited = true;
17176            state.driver_pid = None;
17177            state.driver_started_at = None;
17178            state.save_under(&home).unwrap();
17179            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17180            assert!(
17181                fold_run_overriding_recovery_retention(&mut state, true, &home)
17182                    .await
17183                    .is_err()
17184            );
17185            drop(lease);
17186            #[cfg(unix)]
17187            {
17188                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17189                assert!(
17190                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17191                        .await
17192                        .is_err()
17193                );
17194                drop(output);
17195            }
17196            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17197            assert!(
17198                fold_run_overriding_recovery_retention(&mut state, true, &home)
17199                    .await
17200                    .is_err()
17201            );
17202            drop(owner);
17203            let checkpoint = git::git(
17204                &wt,
17205                &[
17206                    "rev-parse",
17207                    "--path-format=absolute",
17208                    "--git-path",
17209                    "CHERRY_PICK_HEAD",
17210                ],
17211            )
17212            .await
17213            .unwrap();
17214            std::fs::write(&checkpoint, &head).unwrap();
17215            assert!(
17216                fold_run_overriding_recovery_retention(&mut state, true, &home)
17217                    .await
17218                    .is_err()
17219            );
17220            std::fs::remove_file(checkpoint).unwrap();
17221            std::fs::write(wt.join("dirty"), "keep").unwrap();
17222            assert!(
17223                fold_run_overriding_recovery_retention(&mut state, true, &home)
17224                    .await
17225                    .is_err()
17226            );
17227            assert!(wt.join("dirty").exists());
17228            std::fs::remove_file(wt.join("dirty")).unwrap();
17229            let evidence = home
17230                .join("runs")
17231                .join(&state.id)
17232                .join("artifacts/fold-evidence");
17233            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17234            std::fs::write(&evidence, "blocked archive").unwrap();
17235            assert!(
17236                fold_run_overriding_recovery_retention(&mut state, true, &home)
17237                    .await
17238                    .is_err()
17239            );
17240            assert!(wt.exists());
17241            assert!(
17242                !RunState::load_under(&state.id, &home)
17243                    .unwrap()
17244                    .events
17245                    .iter()
17246                    .any(|event| event.message.contains("--override-recovery-retention"))
17247            );
17248            std::fs::remove_file(&evidence).unwrap();
17249            fold_run_overriding_recovery_retention(&mut state, true, &home)
17250                .await
17251                .unwrap();
17252            assert!(!wt.exists());
17253            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17254            assert!(
17255                git::worktree_holding(&repo, "candidate")
17256                    .await
17257                    .unwrap()
17258                    .is_none()
17259            );
17260            assert!(
17261                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17262                    .unwrap()
17263                    .contains("retained implementation")
17264            );
17265            assert!(evidence.join(format!("{head}.index")).is_file());
17266            let saved = RunState::load_under(&state.id, &home).unwrap();
17267            assert_eq!(saved.status, RunStatus::Superseded);
17268            assert!(saved.candidates[0].folded);
17269            assert!(saved.events.iter().any(|event| {
17270                event.message.contains("--override-recovery-retention")
17271                    && event.message.contains(&state.id)
17272                    && event.message.contains(&reason)
17273            }));
17274            assert_eq!(
17275                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17276                sidecar
17277            );
17278        }
17279    }
17280
17281    #[tokio::test]
17282    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17283        ask_test_home();
17284        let tmp = tempfile::tempdir().unwrap();
17285        let repo = tmp.path().join("repo");
17286        std::fs::create_dir(&repo).unwrap();
17287        init_repo(&repo);
17288        let mut runner = runner_at(RunStatus::Implementing);
17289        runner.state.repo = repo.clone();
17290        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17291        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17292        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17293            let branch = format!("candidate-{label}");
17294            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17295            git::worktree_add_branch(&repo, &wt, &branch, "main")
17296                .await
17297                .unwrap();
17298            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17299            git::git(&wt, &["add", "README.md"]).await.unwrap();
17300            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17301            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17302            runner.state.candidates.push(Candidate {
17303                index,
17304                label,
17305                agent: "alpha".to_owned(),
17306                branch,
17307                worktree: wt,
17308                summary: "completed implementation".to_owned(),
17309                stat: String::new(),
17310                files: 0,
17311                commits: 0,
17312                empty: false,
17313                failed: None,
17314                verified_noop: None,
17315                duration_ms: 42,
17316                folded: false,
17317            });
17318            runner
17319                .state
17320                .candidate_preservation
17321                .insert(label, "awaiting persistence".to_owned());
17322        }
17323        let wt = runner.state.candidates[0].worktree.clone();
17324        let index_lock = git::git(
17325            &wt,
17326            &[
17327                "rev-parse",
17328                "--path-format=absolute",
17329                "--git-path",
17330                "index.lock",
17331            ],
17332        )
17333        .await
17334        .unwrap();
17335        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17336        runner.state.save().unwrap();
17337        assert!(runner.persist_candidates().await.is_err());
17338        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17339        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17340        assert_eq!(
17341            runner.state.candidates[1].commits, 1,
17342            "other results are still collected"
17343        );
17344        assert!(
17345            !runner.state.candidates[0].empty,
17346            "failed rescue is not no change"
17347        );
17348        assert_eq!(
17349            runner.state.candidates[0].summary,
17350            "completed implementation"
17351        );
17352        assert!(runner.after_implement().is_err());
17353        let home = tmp.path().join("fold-home");
17354        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17355        assert!(wt.join("new-file").exists());
17356        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17357        assert!(recovery.join("staged.patch").exists());
17358        assert!(recovery.join("unstaged.patch").exists());
17359        assert_eq!(
17360            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17361            "untracked edits\n"
17362        );
17363        runner.state.begin_pass();
17364        runner.state.end_pass_parked(ParkCause::Upgrade {
17365            from: "1.0".into(),
17366            to: Some("1.1".into()),
17367        });
17368        runner.state.save().unwrap();
17369        runner.state = RunState::load(&runner.state.id).unwrap();
17370        assert!(matches!(
17371            runner.state.passes.last().unwrap().end,
17372            Some(crate::run::PassEnd::Parked {
17373                cause: ParkCause::Upgrade { .. }
17374            })
17375        ));
17376        std::fs::remove_file(index_lock).unwrap();
17377        // No implementer is configured: a persistence retry cannot dispatch a seat.
17378        runner.implement().await.unwrap();
17379        assert!(runner.state.candidate_preservation.is_empty());
17380        assert!(
17381            runner
17382                .state
17383                .candidates
17384                .iter()
17385                .all(|c| c.commits == 1 && !c.empty)
17386        );
17387        assert!(git::is_clean(&wt).await.unwrap());
17388        assert!(
17389            crate::run::read_artifact(&runner.state, "cand-A.patch")
17390                .unwrap()
17391                .contains("later tracked edits")
17392        );
17393    }
17394
17395    #[tokio::test]
17396    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17397        ask_test_home();
17398        let tmp = tempfile::tempdir().unwrap();
17399        let repo = tmp.path().join("repo");
17400        std::fs::create_dir(&repo).unwrap();
17401        init_repo(&repo);
17402        let wt = tmp.path().join("candidate");
17403        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17404            .await
17405            .unwrap();
17406        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17407        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17408        assert!(wt.join("uncommitted").exists());
17409        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17410        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17411        let mut runner = runner_at(RunStatus::Implementing);
17412        runner.state.repo = repo.clone();
17413        runner.state.base_commit = "missing-base".to_owned();
17414        runner.state.candidates.push(Candidate {
17415            index: 0,
17416            label: 'A',
17417            agent: "alpha".into(),
17418            branch: "candidate".into(),
17419            worktree: wt.clone(),
17420            summary: "completed".into(),
17421            stat: String::new(),
17422            files: 0,
17423            commits: 0,
17424            empty: false,
17425            failed: None,
17426            verified_noop: None,
17427            duration_ms: 1,
17428            folded: false,
17429        });
17430        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17431        assert!(
17432            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17433                .await
17434                .is_err()
17435        );
17436        assert!(!runner.state.candidates[0].folded);
17437        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17438        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17439        runner
17440            .state
17441            .candidate_preservation
17442            .insert('A', "pending".into());
17443        assert!(runner.persist_candidates().await.is_err());
17444        assert!(!runner.state.candidates[0].empty);
17445        assert!(!runner.state.candidates[0].folded);
17446        assert!(wt.exists());
17447        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17448        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17449        std::fs::create_dir_all(&patch_path).unwrap();
17450        assert!(
17451            runner.persist_candidates().await.is_err(),
17452            "artifact failure stays pending"
17453        );
17454        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17455        assert!(!runner.state.candidates[0].empty);
17456        std::fs::remove_dir(patch_path).unwrap();
17457        runner.persist_candidates().await.unwrap();
17458        assert!(
17459            runner.state.candidates[0].empty,
17460            "only successful inspection confirms no change"
17461        );
17462    }
17463
17464    fn init_repo(dir: &Path) {
17465        let run = |args: &[&str]| {
17466            let out = std::process::Command::new("git")
17467                .args(args)
17468                .current_dir(dir)
17469                .quiet()
17470                .output()
17471                .expect("spawn git");
17472            assert!(
17473                out.status.success(),
17474                "git {args:?} failed: {}",
17475                String::from_utf8_lossy(&out.stderr)
17476            );
17477        };
17478        run(&["init", "-b", "main"]);
17479        run(&["config", "user.name", "magi test"]);
17480        run(&["config", "user.email", "magi@example.com"]);
17481        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17482        run(&["add", "-A"]);
17483        run(&["commit", "-m", "init"]);
17484    }
17485
17486    // `settle_questions` is what closes the ghost the phone showed: a run's
17487    // seat asked something, the run then ended, and nothing was left to
17488    // abandon the question it left `open`. `HOME` is a process-wide
17489    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17490    // first time it runs in the binary — every test below still reaches the
17491    // same directory whichever call won, and each gets its own run id from
17492    // `RunState::new`, so they never collide there.
17493    fn ask_test_home() {
17494        crate::run::pin_test_home();
17495    }
17496
17497    #[test]
17498    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17499        ask_test_home();
17500        let mut runner = runner_at(RunStatus::Prep);
17501        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17502        // A blocked temporary output path makes the terminal save fail while
17503        // preserving the already published reservation.
17504        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17505        let error = guard
17506            .finish(
17507                &mut runner.state,
17508                Err(
17509                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17510                        .into(),
17511                ),
17512            )
17513            .unwrap_err();
17514        assert_eq!(
17515            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17516            std::io::ErrorKind::PermissionDenied
17517        );
17518        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17519        let message = format!("{error:#}");
17520        assert!(message.contains("original refusal"));
17521        assert!(!message.contains("could not save terminal"));
17522        assert_eq!(
17523            error.chain().count(),
17524            2,
17525            "only startup attribution wraps the original error"
17526        );
17527        let saved = RunState::load(&runner.state.id).unwrap();
17528        assert_eq!(saved.status, RunStatus::Blocked);
17529        assert!(!saved.startup.unwrap().complete);
17530    }
17531
17532    #[test]
17533    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17534        ask_test_home();
17535        let mut runner = runner_at(RunStatus::Prep);
17536        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17537        let id = runner.state.id.clone();
17538        drop(guard);
17539        let saved = RunState::load(&id).unwrap();
17540        assert_eq!(saved.status, RunStatus::Blocked);
17541        assert!(!saved.startup.as_ref().unwrap().complete);
17542        assert!(
17543            saved
17544                .startup
17545                .unwrap()
17546                .failure
17547                .unwrap()
17548                .contains("interrupted")
17549        );
17550        assert!(Runner::resume(&id).is_err());
17551    }
17552
17553    #[test]
17554    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17555        ask_test_home();
17556        let mut runner = runner_at(RunStatus::Prep);
17557        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17558        let error = guard
17559            .finish(
17560                &mut runner.state,
17561                Err(
17562                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17563                        .into(),
17564                ),
17565            )
17566            .unwrap_err();
17567        assert_eq!(
17568            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17569            std::io::ErrorKind::PermissionDenied
17570        );
17571        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17572        let mut task = crate::queue::Task::new(
17573            "review".into(),
17574            "criteria".into(),
17575            runner.state.repo.clone(),
17576            crate::queue::Source::Human,
17577        );
17578        task.record_startup_failure(failure.clone());
17579        task.record_startup_failure(failure.clone());
17580        assert_eq!(task.startup_failures.len(), 1);
17581        assert!(task.runs.is_empty());
17582        assert_eq!(task.attempts, 0);
17583    }
17584
17585    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17586        ask_test_home();
17587        let tmp = tempfile::tempdir().unwrap();
17588        let repo = tmp.path().join("repo");
17589        std::fs::create_dir(&repo).unwrap();
17590        init_repo(&repo);
17591        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17592        let origin = tmp.path().join("origin.git");
17593        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17594            .await
17595            .unwrap();
17596        git::git(
17597            &repo,
17598            &["remote", "add", "origin", origin.to_str().unwrap()],
17599        )
17600        .await
17601        .unwrap();
17602        git::git(&repo, &["checkout", "-b", "fix/retained"])
17603            .await
17604            .unwrap();
17605        std::fs::write(repo.join("retained"), "retained change").unwrap();
17606        git::git(&repo, &["add", "."]).await.unwrap();
17607        git::git(&repo, &["commit", "-m", "retained implementation"])
17608            .await
17609            .unwrap();
17610        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17611        git::git(&repo, &["checkout", "main"]).await.unwrap();
17612        std::fs::write(repo.join("base-change"), "new base").unwrap();
17613        git::git(&repo, &["add", "."]).await.unwrap();
17614        git::git(&repo, &["commit", "-m", "base moved"])
17615            .await
17616            .unwrap();
17617        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17618        git::git(&repo, &["checkout", "fix/retained"])
17619            .await
17620            .unwrap();
17621        let mut runner = runner_at(RunStatus::Voting);
17622        runner.state.repo = repo.clone();
17623        runner.state.base_commit = base;
17624        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17625        runner.state.config.disk.min_free_bytes = 0;
17626        runner.state.config.graph.review_rounds = 1;
17627        runner.state.config.verify.e2e = vec!["true".into()];
17628        runner.state.config.verify.gate = vec!["true".into()];
17629        runner.state.candidates = vec![Candidate {
17630            index: 0,
17631            label: 'A',
17632            agent: "fixture".into(),
17633            branch: "fix/retained".into(),
17634            worktree: repo.clone(),
17635            summary: String::new(),
17636            stat: String::new(),
17637            files: 1,
17638            commits: 1,
17639            empty: false,
17640            failed: None,
17641            verified_noop: None,
17642            duration_ms: 0,
17643            folded: false,
17644        }];
17645        runner.state.tally = Some(Tally {
17646            first_choice: BTreeMap::new(),
17647            borda: BTreeMap::new(),
17648            winner: 'A',
17649            rankings: 0,
17650            unanimous_initial: true,
17651            deliberated: false,
17652            changed_votes: 0,
17653            unanimous_final: true,
17654            tie_break: None,
17655            judges: 0,
17656            present: 0,
17657            quorum: 0,
17658            met_quorum: true,
17659            uncontested: Some("review-only".into()),
17660        });
17661        let mut task = crate::queue::Task::new(
17662            "fixture".into(),
17663            "fixture".into(),
17664            repo,
17665            crate::queue::Source::Human,
17666        );
17667        task.link_run(&runner.state.id);
17668        crate::queue::Queue::open().put(&mut task).unwrap();
17669        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17670        runner.state.base_sync = Some(BaseSync {
17671            tip: String::new(),
17672            behind: 1,
17673            attempts: BASE_SYNC_ROUNDS,
17674            conflict: None,
17675            already_in: None,
17676        });
17677        runner.sync_to_base().await.unwrap();
17678        assert_eq!(runner.state.status, RunStatus::Blocked);
17679        (tmp, runner, head, task.id)
17680    }
17681
17682    #[tokio::test]
17683    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17684        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17685        runner.state.status = RunStatus::Voting;
17686        runner.state.base_sync = None;
17687        runner.state.base_sync_recovery = Default::default();
17688        let scratch = runner.state.dir().join("base-sync");
17689        std::fs::create_dir_all(&scratch).unwrap();
17690        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17691        runner.sync_to_base().await.unwrap();
17692        assert!(runner.state.resource_block.is_some());
17693        assert!(!runner.state.base_sync_blocked());
17694        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 0);
17695        assert_eq!(runner.state.base_episode_used(), 0);
17696        assert!(runner.state.base_sync_recovery.operations.is_empty());
17697        assert!(runner.state.rebase_fixes.is_empty());
17698        assert_eq!(
17699            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17700            head
17701        );
17702        std::fs::remove_dir_all(&scratch).unwrap();
17703        runner.state.resource_block = None;
17704        runner.sync_to_base().await.unwrap();
17705        assert!(!runner.state.base_sync_blocked());
17706        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17707        assert_eq!(runner.state.base_episode_used(), 1);
17708        assert!(runner.state.base_sync_recovery.operations[0].finished);
17709        assert!(runner.state.rebase_fixes.is_empty());
17710        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17711        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17712    }
17713
17714    #[cfg(unix)]
17715    #[tokio::test]
17716    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
17717        for routed in [false, true] {
17718            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17719            let home = crate::run::home();
17720            let queue = crate::queue::Queue::open();
17721            let task = queue.get(&owner).unwrap();
17722            runner.state.task_instruction = Some(task.instruction.clone());
17723            runner.state.driver_exited = true;
17724            runner.state.save().unwrap();
17725            let questions = crate::ask::Questions::at(home.join("questions"));
17726            let mut q = crate::ask::Question::new(
17727                runner.state.id.clone(),
17728                "base-recovery".into(),
17729                "owner".into(),
17730                "Recover bounded base movement?".into(),
17731                String::new(),
17732                vec!["recover".into()],
17733            );
17734            q.actions.insert(
17735                "recover".into(),
17736                crate::ask::ChoiceAction::RecoverBase {
17737                    run: runner.state.id.clone(),
17738                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
17739                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
17740                },
17741            );
17742            q.routed_task = Some(owner.clone());
17743            q.answer(crate::ask::Answer::Choice("recover".into()))
17744                .unwrap();
17745            questions.put(&mut q).unwrap();
17746            crate::base_recovery_control::recover(
17747                &queue,
17748                &home,
17749                crate::base_recovery_control::Request {
17750                    run: runner.state.id.clone(),
17751                    head: head.clone(),
17752                    actor: "decisions".into(),
17753                    request: q.id.clone(),
17754                    decision: Some((owner.clone(), q.answered_at.unwrap())),
17755                    expected_stop: Some((
17756                        runner.state.base_sync_recovery.stop.clone().unwrap(),
17757                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
17758                    )),
17759                },
17760            )
17761            .await
17762            .unwrap();
17763            if routed {
17764                questions
17765                    .update(&q.id, |q| {
17766                        q.routed_task = Some("another-owner".into());
17767                        Ok(())
17768                    })
17769                    .unwrap();
17770            } else {
17771                let mut task = queue.get(&owner).unwrap();
17772                task.hold_manual(Some("new owner decision".into()));
17773                // Keep the generation to exercise the separate owner-decision binding.
17774                task.status = crate::queue::TaskStatus::Queued;
17775                queue.put(&mut task).unwrap();
17776            }
17777            runner.state = RunState::load(&runner.state.id).unwrap();
17778            runner.sync_to_base().await.unwrap();
17779            let approval = runner
17780                .state
17781                .base_sync_recovery
17782                .authorizations
17783                .last()
17784                .unwrap();
17785            assert!(approval.consumed);
17786            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
17787                "routing"
17788            } else {
17789                "owner decision"
17790            }));
17791            assert_eq!(
17792                runner.state.base_sync.as_ref().unwrap().attempts,
17793                BASE_SYNC_ROUNDS
17794            );
17795            assert_eq!(
17796                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17797                head
17798            );
17799        }
17800    }
17801
17802    #[cfg(unix)]
17803    #[tokio::test]
17804    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
17805        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
17806        if std::env::var_os(CHILD).is_none() {
17807            let home = tempfile::tempdir().unwrap();
17808            let output = std::process::Command::new(std::env::current_exe().unwrap())
17809                .args([
17810                    "--exact",
17811                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
17812                    "--nocapture",
17813                ])
17814                .env(CHILD, "1")
17815                .env("MAGI_HOME", home.path())
17816                .env("MAGI_WORKER_HOME", home.path())
17817                .env("MAGI_WORKER_ID", "abcdef")
17818                .output()
17819                .unwrap();
17820            assert!(
17821                output.status.success()
17822                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17823                "{}\n{}",
17824                String::from_utf8_lossy(&output.stdout),
17825                String::from_utf8_lossy(&output.stderr)
17826            );
17827            return;
17828        }
17829        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
17830        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17831        let home = crate::run::home();
17832        let queue = crate::queue::Queue::open();
17833        let mut owner = queue.get(&task).unwrap();
17834        owner.release_operator("test-release", None);
17835        owner.start(runner.state.id.clone());
17836        queue.put(&mut owner).unwrap();
17837        runner.state.driver_exited = true;
17838        runner.state.task_instruction = Some(owner.instruction.clone());
17839        runner.state.save().unwrap();
17840        let _claim = queue.claim(&task).unwrap();
17841        let reserve = |id: &str| {
17842            let directory = home.join("workers/jobs").join(id);
17843            std::fs::create_dir_all(&directory).unwrap();
17844            let job = crate::worker::Job {
17845                id: id.into(),
17846                sequence: 1,
17847                kind: "task".into(),
17848                key: format!("task:{task}"),
17849                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
17850                generation: "fixture-generation".into(),
17851                version: None,
17852                status: crate::worker::Status::Running,
17853                result: None,
17854                pid: Some(std::process::id()),
17855                created_at: 0,
17856                finished_at: None,
17857            };
17858            std::fs::write(
17859                directory.join("job.json"),
17860                serde_json::to_vec(&job).unwrap(),
17861            )
17862            .unwrap();
17863            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
17864        };
17865        let _own = reserve("abcdef");
17866        let other = reserve("fedcba");
17867        assert!(
17868            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17869                .await
17870                .is_err()
17871        );
17872        assert!(
17873            RunState::load(&runner.state.id)
17874                .unwrap()
17875                .base_sync_recovery
17876                .authorizations
17877                .is_empty()
17878        );
17879        drop(other);
17880        assert!(crate::daemon::is_working_on(
17881            &home,
17882            &runner.state.id,
17883            Timestamp::now()
17884        ));
17885        assert!(
17886            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
17887        );
17888        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17889            .await
17890            .unwrap();
17891        assert!(
17892            RunState::load(&runner.state.id)
17893                .unwrap()
17894                .base_recovery_pending()
17895        );
17896    }
17897
17898    #[cfg(unix)]
17899    #[tokio::test]
17900    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
17901        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17902        let home = crate::run::home();
17903        runner.state.driver_pid = Some(std::process::id());
17904        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
17905        runner.state.driver_exited = false;
17906        runner.state.begin_pass();
17907        runner.state.save().unwrap();
17908        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
17909        driver.record(&runner.state).unwrap();
17910        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
17911        // Preserve the durable claim as if the process died before Drop saved.
17912        drop(driver);
17913        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
17914        assert_eq!(
17915            runner.state.liveness_under(&home, false),
17916            crate::run::Liveness::Dead
17917        );
17918        let queue = crate::queue::Queue::open();
17919        let _claim = queue.claim(&task).unwrap();
17920        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17921            .await
17922            .unwrap();
17923        let disk = RunState::load(&runner.state.id).unwrap();
17924        assert!(!disk.driver_exited);
17925        assert!(disk.base_recovery_pending());
17926    }
17927
17928    #[cfg(unix)]
17929    #[tokio::test]
17930    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
17931        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
17932        if std::env::var_os(CHILD).is_none() {
17933            use std::os::unix::fs::PermissionsExt;
17934            let tmp = tempfile::tempdir().unwrap();
17935            let gh = tmp.path().join("gh");
17936            std::fs::write(&gh, r#"#!/bin/sh
17937case "$1 $2" in
17938  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
17939  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
17940  *) exit 2 ;;
17941esac
17942"#).unwrap();
17943            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
17944            let mut paths = vec![tmp.path().to_path_buf()];
17945            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
17946            let output = std::process::Command::new(std::env::current_exe().unwrap())
17947                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
17948                .env(CHILD, "1")
17949                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
17950                .env("PATH", std::env::join_paths(paths).unwrap())
17951                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
17952                .output().unwrap();
17953            assert!(
17954                output.status.success()
17955                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17956                "{}\n{}",
17957                String::from_utf8_lossy(&output.stdout),
17958                String::from_utf8_lossy(&output.stderr)
17959            );
17960            return;
17961        }
17962        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
17963        let repo = runner.state.repo.clone();
17964        git::git(&repo, &["checkout", "main"]).await.unwrap();
17965        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
17966        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17967        git::git(&repo, &["checkout", "fix/retained"])
17968            .await
17969            .unwrap();
17970        runner.state.pr = Some(crate::run::PrRecord {
17971            url: "https://example.test/project/pull/1".into(),
17972            number: 1,
17973            state: "open".into(),
17974            checks: "unknown".into(),
17975            round: 0,
17976            rounds: 1,
17977            red_at_merge: Vec::new(),
17978        });
17979        runner.sync_to_base().await.unwrap();
17980        assert_eq!(runner.state.status, RunStatus::Blocked);
17981        assert_eq!(
17982            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
17983            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
17984        );
17985        assert!(runner.state.base_sync_closure_pending());
17986        assert!(crate::handover::can_resume(&runner.state));
17987        let queue = crate::queue::Queue::open();
17988        assert!(!crate::base_sync_recovery::held_task(
17989            &queue,
17990            &queue.get(&task).unwrap()
17991        ));
17992        assert!(runner.state.authorize_base_sync(&task).is_err());
17993        // Legacy closure stops have no typed stop but must retain the checkpoint.
17994        runner.state.base_sync_recovery.stop = None;
17995        runner.state.status = RunStatus::Voting;
17996        runner.state.gate_ran = true;
17997        runner.state.config.graph.review_rounds = 0;
17998        runner.state.save().unwrap();
17999        assert!(crate::handover::can_resume(&runner.state));
18000        runner.state = RunState::load(&runner.state.id).unwrap();
18001        runner.execute_graph().await.unwrap();
18002        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18003        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18004        assert_eq!(
18005            runner.state.base_sync.as_ref().unwrap().attempts,
18006            BASE_SYNC_ROUNDS
18007        );
18008        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18009        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18010        assert!(runner.state.reviews.is_empty());
18011        assert!(runner.state.gate.is_empty());
18012    }
18013
18014    #[cfg(unix)]
18015    #[tokio::test]
18016    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18017        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18018        runner.state.driver_exited = true;
18019        runner.state.save().unwrap();
18020        let home = crate::run::home();
18021        let queue = crate::queue::Queue::open();
18022        let _claim = queue.claim(&task).unwrap();
18023        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18024        assert!(
18025            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18026                .await
18027                .is_err()
18028        );
18029        drop(lease);
18030        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18031        assert!(
18032            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18033                .await
18034                .is_err()
18035        );
18036        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18037        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18038            .await
18039            .unwrap();
18040        let disk = RunState::load(&runner.state.id).unwrap();
18041        assert!(disk.base_recovery_pending());
18042        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18043        assert!(
18044            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18045                .await
18046                .is_err()
18047        );
18048        assert_eq!(
18049            RunState::load(&runner.state.id)
18050                .unwrap()
18051                .base_sync_recovery
18052                .authorizations
18053                .len(),
18054            1
18055        );
18056        let mut owner = queue.get(&task).unwrap();
18057        owner.runs.push("20260101-000000-ffff".into());
18058        queue.put(&mut owner).unwrap();
18059        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18060            .await
18061            .unwrap_err();
18062        assert!(error.to_string().contains("run task ownership changed"));
18063    }
18064
18065    #[cfg(unix)]
18066    #[tokio::test]
18067    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18068        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18069        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18070        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18071        legacy["status"] = serde_json::json!("voting");
18072        runner.state = serde_json::from_value(legacy).unwrap();
18073        runner.state.save().unwrap();
18074        for _ in 0..3 {
18075            runner.execute_graph().await.unwrap();
18076            assert_eq!(runner.state.status, RunStatus::Blocked);
18077            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18078            assert!(!crate::handover::can_resume(&runner.state));
18079            assert_eq!(
18080                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18081                head
18082            );
18083            assert!(runner.state.reviews.is_empty());
18084            assert!(!runner.state.gate_ran);
18085        }
18086        let notice = crate::notices::run_ended(&runner.state).unwrap();
18087        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18088        runner.state.begin_pass();
18089        runner.state.status = RunStatus::Voting;
18090        runner.deliberate().await.unwrap();
18091        runner.vote().await.unwrap();
18092        runner.finish_after_tally().await.unwrap();
18093        assert_eq!(runner.state.status, RunStatus::Blocked);
18094        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18095        assert_eq!(
18096            crate::notices::run_ended(&runner.state).unwrap().since,
18097            notice.since
18098        );
18099    }
18100
18101    #[cfg(unix)]
18102    #[tokio::test]
18103    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18104        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18105        for detail in [
18106            "fix/retained conflicts with origin/main and did not rebase: conflict",
18107            "rebased fix/retained locally but origin refused the push",
18108            "unknown failure",
18109        ] {
18110            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18111            runner.state.record_base_sync_stop(&head);
18112            assert!(runner.state.authorize_base_sync(&task).is_err());
18113            runner.state.status = RunStatus::Voting;
18114            runner.execute_graph().await.unwrap();
18115            assert_eq!(runner.state.status, RunStatus::Blocked);
18116            assert!(!crate::handover::can_resume(&runner.state));
18117            assert_eq!(
18118                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18119                head
18120            );
18121        }
18122    }
18123
18124    #[cfg(unix)]
18125    #[tokio::test]
18126    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18127        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18128        runner.state.authorize_base_sync(&task).unwrap();
18129        assert!(runner.state.consume_base_recovery(&head));
18130        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18131        runner.state.reserve_base_operation(&head, &tip);
18132        runner.state.save().unwrap();
18133        runner.state = RunState::load(&runner.state.id).unwrap();
18134        assert!(!runner.state.consume_base_recovery(&head));
18135        runner.sync_to_base().await.unwrap();
18136        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18137        assert_eq!(runner.state.base_episode_used(), 1);
18138        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18139        assert!(
18140            runner
18141                .state
18142                .base_sync_recovery
18143                .operations
18144                .last()
18145                .unwrap()
18146                .finished
18147        );
18148        assert!(!runner.state.base_sync_blocked());
18149        runner.sync_to_base().await.unwrap();
18150        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18151    }
18152
18153    #[cfg(unix)]
18154    #[tokio::test]
18155    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18156        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18157        // Both historical diagnostic spellings retain an exhaustion identity.
18158        let original = runner
18159            .state
18160            .base_sync
18161            .as_ref()
18162            .unwrap()
18163            .conflict
18164            .clone()
18165            .unwrap();
18166        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18167            original
18168                .replace("synchronization(s)", "rebase(s)")
18169                .replace("synchronizing", "rebasing"),
18170        );
18171        runner.state.base_sync_recovery = Default::default();
18172        runner.state.record_base_sync_stop(&head);
18173        assert_eq!(
18174            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18175            crate::base_sync_recovery::StopKind::Exhausted
18176        );
18177        runner.state.authorize_base_sync(&task).unwrap();
18178        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18179        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18180            .as_object_mut()
18181            .unwrap();
18182        auth.remove("interval");
18183        auth.remove("scope");
18184        runner.state = serde_json::from_value(legacy).unwrap();
18185        assert!(runner.state.consume_base_recovery(&head));
18186        assert_eq!(runner.state.base_episode_used(), 3);
18187        runner.sync_to_base().await.unwrap();
18188        assert_eq!(runner.state.base_episode_used(), 4);
18189        runner.state.resource_block = Some(crate::run::ResourceBlock {
18190            node: "gate".into(),
18191            kind: "cache".into(),
18192            detail: "legacy wait".into(),
18193            at: Timestamp::now(),
18194            cause: crate::run::ResourceBlockCause::Unrecorded,
18195        });
18196        runner.state.save().unwrap();
18197        assert!(
18198            runner
18199                .state
18200                .base_sync_recovery
18201                .episodes
18202                .last()
18203                .unwrap()
18204                .boundary
18205                .is_none()
18206        );
18207        runner.state.resource_block = None;
18208        advance_base_fixture(&runner).await;
18209        runner.sync_to_base().await.unwrap();
18210        assert!(runner.state.base_sync_blocked());
18211        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18212    }
18213
18214    #[cfg(unix)]
18215    async fn advance_base_fixture(runner: &Runner) {
18216        let repo = &runner.state.repo;
18217        for args in [
18218            vec!["checkout", "main"],
18219            vec!["commit", "--allow-empty", "-m", "base advanced"],
18220            vec!["push", "origin", "main"],
18221            vec!["checkout", "fix/retained"],
18222        ] {
18223            git::git(repo, &args).await.unwrap();
18224        }
18225    }
18226
18227    #[cfg(unix)]
18228    fn fresh_base_interval_fixture(runner: &mut Runner) {
18229        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18230        runner.state.base_sync.as_mut().unwrap().conflict = None;
18231        runner.state.base_sync_recovery = Default::default();
18232        runner.state.status = RunStatus::Voting;
18233    }
18234
18235    #[cfg(unix)]
18236    #[tokio::test]
18237    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18238        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18239        fresh_base_interval_fixture(&mut runner);
18240        runner.state.begin_pass();
18241        runner.sync_to_base().await.unwrap();
18242        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18243        runner.state.resource_block = Some(crate::run::ResourceBlock {
18244            node: "gate".into(),
18245            kind: "build cache".into(),
18246            detail: "busy".into(),
18247            at: Timestamp::now(),
18248            cause: crate::run::ResourceBlockCause::Timeout {
18249                waited_secs: 1,
18250                limit_secs: 1,
18251            },
18252        });
18253        runner.state.save().unwrap();
18254        let queue = crate::queue::Queue::open();
18255        let mut owner = queue.get(&task).unwrap();
18256        runner.state.task_instruction = Some(owner.instruction.clone());
18257        owner.release_operator("fixture-owner", None);
18258        queue.put(&mut owner).unwrap();
18259        let approval = owner.resumption.clone().unwrap();
18260        runner.state.resource_block = None;
18261        runner.state.save().unwrap();
18262        runner.state = RunState::load(&runner.state.id).unwrap();
18263        advance_base_fixture(&runner).await;
18264        runner.sync_to_base().await.unwrap();
18265        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18266        assert_eq!(runner.state.base_episode_used(), 1);
18267        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18268        assert!(
18269            runner.state.base_sync_recovery.episodes[0]
18270                .boundary
18271                .as_ref()
18272                .unwrap()
18273                .consumed
18274        );
18275        assert!(
18276            !runner
18277                .state
18278                .renew_base_episode(&task, &approval, &head, "base")
18279        );
18280        for _ in 0..3 {
18281            owner.release_operator("fixture-owner", None);
18282            queue.put(&mut owner).unwrap();
18283            runner.state = RunState::load(&runner.state.id).unwrap();
18284            runner.state.begin_pass();
18285            runner.sync_to_base().await.unwrap();
18286            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18287            assert_eq!(runner.state.base_episode_used(), 1);
18288        }
18289        runner.state.resource_block = Some(crate::run::ResourceBlock {
18290            node: "gate".into(),
18291            kind: "disk pressure".into(),
18292            detail: "free space required".into(),
18293            at: Timestamp::now(),
18294            cause: crate::run::ResourceBlockCause::Other,
18295        });
18296        runner.state.end_pass_parked(ParkCause::Interrupt {
18297            reason: "disk pressure".into(),
18298        });
18299        runner.state.save().unwrap();
18300        owner.release_operator("fixture-owner-after-disk", None);
18301        queue.put(&mut owner).unwrap();
18302        runner.state.resource_block = None;
18303        advance_base_fixture(&runner).await;
18304        runner.sync_to_base().await.unwrap();
18305        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18306        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18307        assert_eq!(runner.state.base_episode_used(), 1);
18308        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18309    }
18310
18311    #[cfg(unix)]
18312    #[tokio::test]
18313    async fn base_recovery_continuous_advancement_stops_at_four() {
18314        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18315        fresh_base_interval_fixture(&mut runner);
18316        for spent in 1..=BASE_SYNC_ROUNDS {
18317            runner.sync_to_base().await.unwrap();
18318            assert!(!runner.state.base_sync_blocked());
18319            assert_eq!(runner.state.base_episode_used(), spent);
18320            advance_base_fixture(&runner).await;
18321        }
18322        runner.sync_to_base().await.unwrap();
18323        assert_eq!(
18324            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18325            crate::base_sync_recovery::StopKind::Exhausted
18326        );
18327        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18328        assert!(stop.unverified_sync);
18329        let action = runner.state.base_sync_next_action();
18330        assert!(action.contains("never reached its gate"));
18331        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18332        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18333        runner.state = RunState::load(&runner.state.id).unwrap();
18334        runner.sync_to_base().await.unwrap();
18335        assert_eq!(runner.state.base_episode_used(), 4);
18336        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18337    }
18338
18339    #[cfg(unix)]
18340    #[tokio::test]
18341    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18342        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18343        runner.state.ensure_base_episode();
18344        // Verification progress alone is not evidence of a successful sync.
18345        runner.state.record_base_progress(&head);
18346        runner.state.base_sync_recovery.stop = None;
18347        runner.state.record_base_sync_stop(&head);
18348        assert!(
18349            !runner
18350                .state
18351                .base_sync_recovery
18352                .stop
18353                .as_ref()
18354                .unwrap()
18355                .unverified_sync
18356        );
18357
18358        runner.state.finish_base_operation(Some(&head));
18359        // A gate for another head cannot verify this synchronization.
18360        runner.state.gate_ran = true;
18361        runner.state.gate_head = Some("older-head".into());
18362        runner.state.base_sync_recovery.stop = None;
18363        runner.state.record_base_sync_stop(&head);
18364        runner.state.save().unwrap();
18365        runner.state = RunState::load(&runner.state.id).unwrap();
18366        assert!(
18367            runner
18368                .state
18369                .base_sync_recovery
18370                .stop
18371                .as_ref()
18372                .unwrap()
18373                .unverified_sync
18374        );
18375
18376        runner.state.gate_head = Some(head.clone());
18377        runner.state.base_sync_recovery.stop = None;
18378        runner.state.record_base_sync_stop(&head);
18379        assert!(
18380            !runner
18381                .state
18382                .base_sync_recovery
18383                .stop
18384                .as_ref()
18385                .unwrap()
18386                .unverified_sync
18387        );
18388        assert!(
18389            !runner
18390                .state
18391                .base_sync_next_action()
18392                .contains("never reached its gate")
18393        );
18394
18395        // Historical records cannot establish the missing synchronization evidence.
18396        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18397        legacy["base_sync_recovery"]["stop"]
18398            .as_object_mut()
18399            .unwrap()
18400            .remove("unverified_sync");
18401        legacy["base_sync_recovery"]["episodes"][0]
18402            .as_object_mut()
18403            .unwrap()
18404            .remove("last_sync_head");
18405        runner.state = serde_json::from_value(legacy).unwrap();
18406        assert!(
18407            !runner
18408                .state
18409                .base_sync_recovery
18410                .stop
18411                .as_ref()
18412                .unwrap()
18413                .unverified_sync
18414        );
18415        assert!(
18416            runner.state.base_sync_recovery.episodes[0]
18417                .last_sync_head
18418                .is_none()
18419        );
18420    }
18421
18422    #[cfg(unix)]
18423    #[tokio::test]
18424    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18425        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18426        runner.state.authorize_base_sync(&task).unwrap();
18427        assert!(
18428            runner
18429                .state
18430                .base_sync_next_action()
18431                .contains("Approval recorded")
18432        );
18433        assert!(
18434            runner
18435                .state
18436                .base_sync_next_action()
18437                .contains("4/4 in episode 0, 4 lifetime")
18438        );
18439        assert!(runner.state.consume_base_recovery(&head));
18440        assert!(
18441            runner
18442                .state
18443                .base_sync_next_action()
18444                .contains("0/4 in episode 1, 4 lifetime")
18445        );
18446    }
18447
18448    #[cfg(unix)]
18449    #[tokio::test]
18450    async fn base_recovery_changed_head_invalidates_without_spending() {
18451        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18452        runner.state.authorize_base_sync(&task).unwrap();
18453        git::git(
18454            &runner.state.repo,
18455            &["commit", "--allow-empty", "-m", "external head change"],
18456        )
18457        .await
18458        .unwrap();
18459        runner.sync_to_base().await.unwrap();
18460        let a = runner
18461            .state
18462            .base_sync_recovery
18463            .authorizations
18464            .last()
18465            .unwrap();
18466        assert!(a.consumed);
18467        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18468        runner.state = RunState::load(&runner.state.id).unwrap();
18469        assert!(
18470            runner
18471                .state
18472                .base_sync_next_action()
18473                .contains("Approval invalidated")
18474        );
18475        assert!(!runner.state.base_recovery_pending());
18476        assert!(runner.state.base_sync_blocked());
18477        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18478    }
18479
18480    #[cfg(unix)]
18481    #[tokio::test]
18482    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18483        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18484        runner.state.driver_exited = true;
18485        runner.state.save().unwrap();
18486        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18487            .await
18488            .unwrap();
18489        runner.state = RunState::load(&runner.state.id).unwrap();
18490        advance_base_fixture(&runner).await;
18491        runner.sync_to_base().await.unwrap();
18492        let a = runner
18493            .state
18494            .base_sync_recovery
18495            .authorizations
18496            .last()
18497            .unwrap();
18498        assert!(
18499            a.consumed
18500                && a.invalidated
18501                    .as_deref()
18502                    .unwrap()
18503                    .contains("fetched base changed")
18504        );
18505        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18506        assert_eq!(
18507            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18508            head
18509        );
18510        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18511            .await
18512            .unwrap();
18513        runner.state = RunState::load(&runner.state.id).unwrap();
18514        runner.sync_to_base().await.unwrap();
18515        assert!(!runner.state.base_sync_blocked());
18516        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18517    }
18518
18519    #[cfg(unix)]
18520    #[tokio::test]
18521    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18522        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18523        runner.state.authorize_base_sync(&task).unwrap();
18524        assert!(runner.state.consume_base_recovery(&head));
18525        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18526        runner.state.reserve_base_operation(&head, &tip);
18527        runner.state.save().unwrap();
18528        let scratch = runner.state.dir().join("base-sync");
18529        assert_eq!(
18530            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18531                .await
18532                .unwrap(),
18533            crate::rebase::Rebased::Applied
18534        );
18535        runner.state = RunState::load(&runner.state.id).unwrap();
18536        runner.sync_to_base().await.unwrap();
18537        assert!(
18538            runner
18539                .state
18540                .base_sync_recovery
18541                .operations
18542                .last()
18543                .unwrap()
18544                .finished
18545        );
18546        assert_eq!(runner.state.base_episode_used(), 1);
18547        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18548        assert!(!runner.state.base_sync_blocked());
18549    }
18550
18551    #[cfg(unix)]
18552    #[tokio::test]
18553    async fn base_recovery_crash_preserves_untracked_files() {
18554        for ignored in [false, true] {
18555            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18556            runner.state.authorize_base_sync(&task).unwrap();
18557            assert!(runner.state.consume_base_recovery(&head));
18558            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18559            runner.state.reserve_base_operation(&head, &tip);
18560            runner.state.save().unwrap();
18561            let scratch = runner.state.dir().join("base-sync");
18562            assert_eq!(
18563                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18564                    .await
18565                    .unwrap(),
18566                crate::rebase::Rebased::Applied
18567            );
18568            let repo = &runner.state.repo;
18569            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18570            assert_ne!(result, head);
18571            if ignored {
18572                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18573                    .await
18574                    .unwrap();
18575                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18576            }
18577            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18578            assert!(
18579                git::git_raw(repo, &["diff", "--quiet", &head])
18580                    .await
18581                    .unwrap()
18582                    .ok()
18583            );
18584            // Resume after the branch moved, before its checkout was reset.
18585            runner.state = RunState::load(&runner.state.id).unwrap();
18586            runner.sync_to_base().await.unwrap();
18587            assert!(runner.state.base_sync_blocked());
18588            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18589            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18590            assert_eq!(
18591                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18592                result
18593            );
18594            assert_eq!(
18595                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18596                "retained work\n"
18597            );
18598            assert!(
18599                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18600                    .await
18601                    .unwrap()
18602                    .ok()
18603            );
18604        }
18605    }
18606
18607    #[cfg(unix)]
18608    #[tokio::test]
18609    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18610        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18611        runner.state.authorize_base_sync(&task).unwrap();
18612        assert!(runner.state.consume_base_recovery(&head));
18613        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18614        runner.state.reserve_base_operation(&head, &tip);
18615        runner.state.save().unwrap();
18616        let scratch = runner.state.dir().join("base-sync");
18617        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18618            .await
18619            .unwrap();
18620        git::sync_to_head(&runner.state.repo).await.unwrap();
18621        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18622        git::git(&runner.state.repo, &["add", "foreign"])
18623            .await
18624            .unwrap();
18625        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18626            .await
18627            .unwrap();
18628        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18629        runner.state = RunState::load(&runner.state.id).unwrap();
18630        runner.sync_to_base().await.unwrap();
18631        assert!(runner.state.base_sync_blocked());
18632        assert!(
18633            !runner
18634                .state
18635                .base_sync_recovery
18636                .operations
18637                .last()
18638                .unwrap()
18639                .finished
18640        );
18641        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18642        assert_eq!(
18643            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18644            foreign_head
18645        );
18646    }
18647
18648    #[cfg(unix)]
18649    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18650    {
18651        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18652        fresh_base_interval_fixture(&mut runner);
18653        let repo = &runner.state.repo;
18654        git::git(repo, &["checkout", "main"]).await.unwrap();
18655        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18656        git::git(repo, &["add", "retained"]).await.unwrap();
18657        git::git(repo, &["commit", "-m", "upstream retained change"])
18658            .await
18659            .unwrap();
18660        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18661        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18662        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18663        let scratch = runner.state.dir().join("base-sync");
18664        assert!(matches!(
18665            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18666                .await
18667                .unwrap(),
18668            git::RebaseStart::Conflicted(_)
18669        ));
18670        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18671            agent: "fixture".into(),
18672            paths: vec!["retained".into()],
18673            from: Some(head.clone()),
18674            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18675            index_outside: None,
18676            finished: false,
18677            error: None,
18678            launcher: None,
18679            infra: None,
18680            outage: None,
18681        });
18682        (tmp, runner, head, tip, scratch)
18683    }
18684
18685    #[cfg(unix)]
18686    #[tokio::test]
18687    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18688        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18689        // A resource stop from before reservations existed, with resolved
18690        // contents left for the launcher's ordinary staging continuation.
18691        std::fs::write(
18692            scratch.join("retained"),
18693            "upstream and retained resolution\n",
18694        )
18695        .unwrap();
18696        runner.state.resource_block = Some(crate::run::ResourceBlock {
18697            node: "rebase".into(),
18698            kind: "repository coordination".into(),
18699            detail: "busy".into(),
18700            at: Timestamp::now(),
18701            cause: crate::run::ResourceBlockCause::Other,
18702        });
18703        runner.state.save().unwrap();
18704        // Advance the remote without moving either checkout participating
18705        // in the standing rebase.
18706        let newer = git::git(
18707            &runner.state.repo,
18708            &[
18709                "commit-tree",
18710                "main^{tree}",
18711                "-p",
18712                "main",
18713                "-m",
18714                "base advanced during wait",
18715            ],
18716        )
18717        .await
18718        .unwrap();
18719        git::git(
18720            &runner.state.repo,
18721            &[
18722                "push",
18723                "origin",
18724                &format!("{}:refs/heads/main", newer.trim()),
18725            ],
18726        )
18727        .await
18728        .unwrap();
18729        runner.state = RunState::load(&runner.state.id).unwrap();
18730        runner.state.resource_block = None;
18731        runner.sync_to_base().await.unwrap();
18732        assert!(!runner.state.base_sync_blocked());
18733        let op = &runner.state.base_sync_recovery.operations[0];
18734        assert_eq!(op.head, head);
18735        assert_eq!(op.tip, tip);
18736        assert!(op.finished);
18737        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18738        assert_eq!(runner.state.rebase_fixes.len(), 1);
18739        let latest = git::rev_parse(&runner.state.repo, "origin/main")
18740            .await
18741            .unwrap();
18742        assert_ne!(latest, tip);
18743        runner.state = RunState::load(&runner.state.id).unwrap();
18744        runner.sync_to_base().await.unwrap();
18745        assert!(!runner.state.base_sync_blocked());
18746        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
18747        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
18748        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18749    }
18750
18751    #[cfg(unix)]
18752    #[tokio::test]
18753    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
18754        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18755        runner.state.reserve_base_operation(&head, &tip);
18756        runner.state.save().unwrap();
18757        std::fs::write(
18758            scratch.join("retained"),
18759            "upstream and retained resolution\n",
18760        )
18761        .unwrap();
18762        git::git(&scratch, &["add", "retained"]).await.unwrap();
18763        git::git(
18764            &scratch,
18765            &["-c", "core.editor=true", "rebase", "--continue"],
18766        )
18767        .await
18768        .unwrap();
18769        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18770        assert!(
18771            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18772                .await
18773                .unwrap()
18774                .is_empty()
18775        );
18776        assert_eq!(
18777            crate::rebase::finish(
18778                &mut runner.state,
18779                &scratch,
18780                "fix/retained",
18781                &head,
18782                &tip,
18783                &["retained".into()],
18784                ""
18785            )
18786            .await
18787            .unwrap(),
18788            crate::rebase::Rebased::Applied
18789        );
18790        assert!(!scratch.exists());
18791        // Simulate losing the caller before finish_base_operation/save.
18792        runner.state = RunState::load(&runner.state.id).unwrap();
18793        let op = &runner.state.base_sync_recovery.operations[0];
18794        assert!(!op.finished);
18795        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
18796        runner.sync_to_base().await.unwrap();
18797        assert!(!runner.state.base_sync_blocked());
18798        assert!(runner.state.base_sync_recovery.operations[0].finished);
18799        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18800        assert_eq!(runner.state.rebase_fixes.len(), 1);
18801        let winner = runner.state.winner().unwrap().clone();
18802        let wait = runner.repository_wait();
18803        assert!(
18804            verify_current_head(&mut runner.state, &winner, &wait)
18805                .await
18806                .unwrap()
18807        );
18808        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18809    }
18810
18811    #[cfg(unix)]
18812    #[tokio::test]
18813    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
18814        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
18815            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18816            runner.state.reserve_base_operation(&head, &tip);
18817            runner.state.save().unwrap();
18818            std::fs::write(
18819                scratch.join("retained"),
18820                "upstream and retained resolution\n",
18821            )
18822            .unwrap();
18823            git::git(&scratch, &["add", "retained"]).await.unwrap();
18824            git::git(
18825                &scratch,
18826                &["-c", "core.editor=true", "rebase", "--continue"],
18827            )
18828            .await
18829            .unwrap();
18830            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18831            assert!(!git::rebase_in_progress(&scratch).await);
18832            assert!(
18833                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18834                    .await
18835                    .unwrap()
18836                    .is_empty()
18837            );
18838            match damage {
18839                Some("record") => {
18840                    let path =
18841                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
18842                            .await
18843                            .unwrap();
18844                    std::fs::write(scratch.join(path), "").unwrap();
18845                }
18846                Some("foreign") => {
18847                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
18848                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
18849                    git::git(&scratch, &["commit", "-m", "foreign work"])
18850                        .await
18851                        .unwrap();
18852                }
18853                Some("dirty") => {
18854                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
18855                }
18856                _ => {}
18857            }
18858            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18859            // Crash immediately after Git continuation, before finish runs.
18860            runner.state = RunState::load(&runner.state.id).unwrap();
18861            assert!(
18862                runner.state.base_sync_recovery.operations[0]
18863                    .validated_head
18864                    .is_none()
18865            );
18866            runner.sync_to_base().await.unwrap();
18867            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18868            assert_eq!(runner.state.base_episode_used(), 1);
18869            assert_eq!(runner.state.rebase_fixes.len(), 1);
18870            assert_eq!(
18871                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18872                retained_head
18873            );
18874            if damage.is_some() {
18875                assert!(runner.state.base_sync_blocked());
18876                assert!(scratch.exists());
18877                assert!(!runner.state.base_sync_recovery.operations[0].finished);
18878                assert!(
18879                    runner.state.base_sync_recovery.operations[0]
18880                        .validated_head
18881                        .is_none()
18882                );
18883            } else {
18884                assert!(!runner.state.base_sync_blocked());
18885                assert!(!scratch.exists());
18886                assert!(runner.state.base_sync_recovery.operations[0].finished);
18887                assert_eq!(
18888                    runner.state.base_sync_recovery.operations[0]
18889                        .validated_head
18890                        .as_deref(),
18891                    Some(result.as_str())
18892                );
18893                let winner = runner.state.winner().unwrap().clone();
18894                let wait = runner.repository_wait();
18895                assert!(
18896                    verify_current_head(&mut runner.state, &winner, &wait)
18897                        .await
18898                        .unwrap()
18899                );
18900                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18901                runner.state = RunState::load(&runner.state.id).unwrap();
18902                runner.sync_to_base().await.unwrap();
18903                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18904            }
18905        }
18906    }
18907
18908    #[cfg(unix)]
18909    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
18910        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18911        // This is an ordinary gate stop, not an authorized base-budget recovery.
18912        runner.state.prep_complete = Some(true);
18913        runner.state.base_sync = None;
18914        runner.state.base_sync_recovery = Default::default();
18915        runner.state.config.graph.gate_fix_rounds = 1;
18916        let mut review = review_round(true, 0, 1, 1, false, true);
18917        review.head = head.clone();
18918        review.verified_head = Some(head.clone());
18919        runner.state.reviews = vec![review];
18920        runner.state.gate = vec![CommandOutcome {
18921            command: "old gate".into(),
18922            code: Some(1),
18923            output_tail: "old failure".into(),
18924            duration_ms: 0,
18925            resource_blocked: false,
18926        }];
18927        runner.state.gate_head = Some(head.clone());
18928        runner.state.gate_ran = true;
18929        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
18930            agent: "fixture".into(),
18931            failed: runner.state.gate.clone(),
18932            notes: "spent".into(),
18933            committed: false,
18934            error: None,
18935        }];
18936        runner.state.land_approval = Some(crate::run::LandApproval {
18937            question: "old approval".into(),
18938            head: head.clone(),
18939        });
18940        runner.state.status = RunStatus::Blocked;
18941        (tmp, runner, head)
18942    }
18943
18944    #[cfg(unix)]
18945    #[tokio::test]
18946    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
18947        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
18948            let (tmp, mut runner, old) = resumed_gate_fixture().await;
18949            let phases = tmp.path().join("phases");
18950            runner.state.config.verify.e2e = vec![format!(
18951                "echo e2e >> '{}'; {}",
18952                phases.display(),
18953                if e2e_ok {
18954                    "true"
18955                } else {
18956                    "echo new-e2e-failure; false"
18957                }
18958            )];
18959            runner.state.config.verify.gate = vec![format!(
18960                "echo gate >> '{}'; {}",
18961                phases.display(),
18962                if gate_ok {
18963                    "true"
18964                } else {
18965                    "echo new-gate-failure; false"
18966                }
18967            )];
18968            runner.state.save().unwrap();
18969            runner.state = RunState::load(&runner.state.id).unwrap();
18970            runner.sync_to_base().await.unwrap();
18971            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18972            assert_ne!(head, old);
18973            // Reentry after Git updated but before verification was invalidated.
18974            runner.state = RunState::load(&runner.state.id).unwrap();
18975            runner.execute_graph().await.unwrap();
18976            assert_eq!(runner.state.gate_fixes.len(), 1);
18977            assert_eq!(runner.state.reviews.len(), 1);
18978            assert_eq!(runner.state.reviews[0].head, old);
18979            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
18980            assert_eq!(runner.state.verification_history.len(), 1);
18981            let history = &runner.state.verification_history[0];
18982            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
18983            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
18984            assert!(history.archived_at.is_some());
18985            assert_eq!(history.fixes_spent, Some(1));
18986            assert_eq!(history.gate[0].output_tail, "old failure");
18987            let archive_events: Vec<_> = runner
18988                .state
18989                .events
18990                .iter()
18991                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
18992                .collect();
18993            assert_eq!(archive_events.len(), 1);
18994            assert!(archive_events[0].message.contains(&short(&old)));
18995            assert!(archive_events[0].message.contains(&short(&head)));
18996            assert!(
18997                archive_events[0]
18998                    .message
18999                    .contains("1 gate-fix round(s) already spent stay spent")
19000            );
19001            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19002            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19003            if e2e_ok {
19004                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19005                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19006            } else {
19007                assert!(!runner.state.gate_ran);
19008            }
19009            assert_eq!(
19010                runner.state.status,
19011                if e2e_ok && gate_ok {
19012                    RunStatus::Ready
19013                } else {
19014                    RunStatus::Blocked
19015                }
19016            );
19017            if !e2e_ok || !gate_ok {
19018                let cause = runner.state.verification_blocking_cause().unwrap();
19019                assert!(cause.contains(&head));
19020                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19021                // A later successful progress event must not become the cause.
19022                runner.state.event("land", "rebased successfully");
19023                let notice = crate::notices::run_ended(&runner.state).unwrap();
19024                assert!(!format!("{notice:?}").contains("rebased successfully"));
19025                assert!(runner.state.merge.is_none());
19026            }
19027            let before = std::fs::read_to_string(&phases).unwrap();
19028            runner.state.save().unwrap();
19029            runner.state = RunState::load(&runner.state.id).unwrap();
19030            runner.review_loop().await.unwrap();
19031            runner.gate().await.unwrap();
19032            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19033            assert_eq!(runner.state.verification_history.len(), 1);
19034            let history = &runner.state.verification_history[0];
19035            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19036            assert!(history.archived_at.is_some());
19037            assert_eq!(history.fixes_spent, Some(1));
19038        }
19039    }
19040
19041    #[cfg(unix)]
19042    #[tokio::test]
19043    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19044        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19045        let marker = tmp.path().join("gate-ran");
19046        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19047        runner.review_loop().await.unwrap();
19048        runner.gate().await.unwrap();
19049        assert_eq!(runner.state.status, RunStatus::Blocked);
19050        assert!(!marker.exists());
19051        assert!(runner.state.verification_history.is_empty());
19052        runner.state.gate_head = None;
19053        runner.gate().await.unwrap();
19054        assert!(marker.exists());
19055        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19056        assert_eq!(runner.state.verification_history.len(), 1);
19057        assert_eq!(runner.state.gate_fixes.len(), 1);
19058    }
19059
19060    #[cfg(unix)]
19061    #[tokio::test]
19062    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19063        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19064        runner.sync_to_base().await.unwrap();
19065        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19066        runner.state.reconcile_verification_head(&head);
19067        // Both crash-before-command and resource wait are unresolved evidence.
19068        for outcomes in [
19069            Vec::new(),
19070            vec![CommandOutcome {
19071                command: "true".into(),
19072                code: None,
19073                output_tail: "cache unavailable".into(),
19074                duration_ms: 0,
19075                resource_blocked: true,
19076            }],
19077        ] {
19078            runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19079                head: head.clone(),
19080                passed: false,
19081                outcomes,
19082            });
19083            runner.state.gate_ran = false;
19084            runner.state.gate.clear();
19085            runner.state.save().unwrap();
19086            runner.state = RunState::load(&runner.state.id).unwrap();
19087            runner.merge().await.unwrap();
19088            assert!(runner.state.merge.is_none());
19089            runner.review_loop().await.unwrap();
19090            runner.gate().await.unwrap();
19091            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19092            assert!(runner.state.gate_allows_progress());
19093            assert_eq!(runner.state.gate_fixes.len(), 1);
19094            assert!(runner.state.merge.is_none());
19095        }
19096        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19097        git::git(
19098            &runner.state.repo,
19099            &["commit", "--allow-empty", "-m", "external update"],
19100        )
19101        .await
19102        .unwrap();
19103        runner.merge().await.unwrap();
19104        assert!(runner.state.merge.is_none());
19105        assert_eq!(runner.state.status, RunStatus::Blocked);
19106    }
19107
19108    #[cfg(unix)]
19109    #[tokio::test]
19110    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19111        for waiting_on_gate in [false, true] {
19112            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19113            runner.sync_to_base().await.unwrap();
19114            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19115            runner.state.reconcile_verification_head(&head);
19116            if waiting_on_gate {
19117                runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19118                    head: head.clone(),
19119                    passed: true,
19120                    outcomes: Vec::new(),
19121                });
19122            }
19123            let cache = tmp.path().join("cache");
19124            runner.state.config.verify.e2e =
19125                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19126            runner.state.config.verify.gate = vec!["true".into()];
19127            runner.state.config.graph.timeout_resource_wait = 1;
19128            let owner =
19129                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19130            let guard =
19131                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19132                    crate::cache::AcquireOutcome::Acquired(g) => g,
19133                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19134                };
19135            runner.review_loop().await.unwrap();
19136            runner.gate().await.unwrap();
19137            assert!(!runner.state.gate_ran);
19138            assert_eq!(runner.state.gate_fixes.len(), 1);
19139            assert!(runner.state.resource_block.is_some());
19140            runner.merge().await.unwrap();
19141            assert!(runner.state.merge.is_none());
19142            drop(guard);
19143            runner.state = RunState::load(&runner.state.id).unwrap();
19144            // The driver clears the previous pass's resource stop on resume.
19145            runner.state.resource_block = None;
19146            runner.review_loop().await.unwrap();
19147            runner.gate().await.unwrap();
19148            assert!(runner.state.gate_allows_progress());
19149            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19150            assert_eq!(runner.state.gate_fixes.len(), 1);
19151        }
19152    }
19153
19154    #[cfg(unix)]
19155    #[tokio::test]
19156    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19157        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19158        runner.sync_to_base().await.unwrap();
19159        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19160        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19161        // Verification passes before pre_gate and fails on the mechanically changed head.
19162        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19163        runner.review_loop().await.unwrap();
19164        runner.gate().await.unwrap();
19165        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19166        assert_ne!(before, after);
19167        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19168        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19169        assert!(!runner.state.gate_allows_progress());
19170        runner.merge().await.unwrap();
19171        assert!(runner.state.merge.is_none());
19172        assert!(
19173            runner
19174                .state
19175                .verification_history
19176                .iter()
19177                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19178        );
19179
19180        // An incomplete review is still an independent hold on a changed head.
19181        runner.state.reviews[0].clean = false;
19182        runner.state.reviews[0].answered = 0;
19183        runner.state.config.verify.e2e = vec!["true".into()];
19184        runner.review_loop().await.unwrap();
19185        runner.gate().await.unwrap();
19186        runner.merge().await.unwrap();
19187        assert_eq!(runner.state.status, RunStatus::Blocked);
19188        assert!(runner.state.merge.is_none());
19189        assert!(
19190            runner
19191                .state
19192                .verification_blocking_cause()
19193                .unwrap()
19194                .contains("review blocked")
19195        );
19196    }
19197
19198    #[cfg(unix)]
19199    #[tokio::test]
19200    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19201        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19202        runner.state.gate_head = None;
19203        runner.state.config.verify.gate =
19204            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19205        runner.review_loop().await.unwrap();
19206        runner.gate().await.unwrap();
19207        assert_ne!(
19208            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19209            old
19210        );
19211        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19212        assert!(!runner.state.gate_allows_progress());
19213        assert_eq!(runner.state.status, RunStatus::Blocked);
19214        runner.merge().await.unwrap();
19215        assert!(runner.state.merge.is_none());
19216    }
19217
19218    #[cfg(unix)]
19219    #[tokio::test]
19220    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19221        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19222        let mut old_review = review_round(true, 0, 1, 1, false, true);
19223        old_review.head = head.clone();
19224        old_review.verified_head = Some(head.clone());
19225        runner.state.reviews = vec![old_review];
19226        runner.state.gate = vec![CommandOutcome {
19227            command: "old gate".into(),
19228            code: None,
19229            output_tail: "timed out after 2400s".into(),
19230            duration_ms: 2_400_000,
19231            resource_blocked: false,
19232        }];
19233        runner.state.gate_ran = true;
19234        runner.state.gate_head = Some(head.clone());
19235        runner.state.land_approval = Some(crate::run::LandApproval {
19236            question: "old-head-approval".into(),
19237            head: head.clone(),
19238        });
19239        runner.state.authorize_base_sync(&task).unwrap();
19240        runner.sync_to_base().await.unwrap();
19241        assert!(!runner.state.base_sync_blocked());
19242        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19243        assert_ne!(head, fresh);
19244        assert_eq!(runner.state.reviews.len(), 1);
19245        assert!(!runner.state.gate_ran);
19246        let saved = &runner.state.base_sync_recovery.authorizations[0];
19247        assert_eq!(saved.reviews[0].head, head);
19248        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19249        assert!(saved.gate_ran);
19250        assert!(!saved.gate[0].ok());
19251        runner.review_loop().await.unwrap();
19252        runner.gate().await.unwrap();
19253        assert_eq!(runner.state.reviews[0].head, head);
19254        assert_eq!(
19255            runner.state.reviews[0].verified_head.as_deref(),
19256            Some(head.as_str())
19257        );
19258        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19259        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19260        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19261        assert!(runner.state.gate_ran);
19262        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19263        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19264        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19265        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19266        assert_eq!(
19267            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19268            "retained change"
19269        );
19270    }
19271
19272    #[cfg(unix)]
19273    #[tokio::test]
19274    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19275        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19276        let queue = crate::queue::Queue::open();
19277        let mut owner = queue.get(&task).unwrap();
19278        owner.release_operator("test-resume", None);
19279        queue.put(&mut owner).unwrap();
19280        let generation = owner.resumption.as_ref().unwrap().generation;
19281        runner.state.task_instruction = Some(owner.instruction.clone());
19282        runner.state.driver_exited = true;
19283        runner.state.save().unwrap();
19284        let home = crate::run::home();
19285        let _claim = queue.claim(&task).unwrap();
19286        owner.resumption.as_mut().unwrap().at =
19287            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19288        queue.put(&mut owner).unwrap();
19289        assert!(
19290            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19291                .await
19292                .is_err(),
19293            "an approval from before the stop grants nothing"
19294        );
19295        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19296        queue.put(&mut owner).unwrap();
19297        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19298            .await
19299            .unwrap();
19300        assert!(
19301            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19302                .await
19303                .is_err()
19304        );
19305        runner.state = RunState::load(&runner.state.id).unwrap();
19306        assert_eq!(
19307            runner.state.base_sync_recovery.authorizations[0].generation,
19308            Some(generation)
19309        );
19310        runner.sync_to_base().await.unwrap();
19311        let repo = runner.state.repo.clone();
19312        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19313        git::git(&repo, &["checkout", "main"]).await.unwrap();
19314        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19315        git::git(&repo, &["add", "."]).await.unwrap();
19316        git::git(&repo, &["commit", "-m", "move base again"])
19317            .await
19318            .unwrap();
19319        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19320        git::git(&repo, &["checkout", "fix/retained"])
19321            .await
19322            .unwrap();
19323        runner.sync_to_base().await.unwrap();
19324        assert!(!runner.state.base_sync_blocked());
19325        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19326        assert_eq!(runner.state.base_episode_used(), 2);
19327        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19328        assert_ne!(fresh, head);
19329        assert!(!runner.state.base_recovery_pending());
19330        // Even replaying the generation with a later timestamp grants nothing.
19331        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19332        queue.put(&mut owner).unwrap();
19333        assert!(
19334            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19335                .await
19336                .is_err()
19337        );
19338        runner.state = RunState::load(&runner.state.id).unwrap();
19339        runner.sync_to_base().await.unwrap();
19340        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19341        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19342        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19343    }
19344
19345    #[cfg(unix)]
19346    #[tokio::test]
19347    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19348        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19349        runner.state.base_sync = None;
19350        runner.state.status = RunStatus::Blocked;
19351        let mut second = runner.state.candidates[0].clone();
19352        second.label = 'B';
19353        runner.state.candidates.push(second);
19354        assert!(runner.state.votes.is_empty());
19355        assert!(runner.state.deliberation.is_empty());
19356        runner.deliberate().await.unwrap();
19357        runner.vote().await.unwrap();
19358        assert_eq!(runner.state.status, RunStatus::Blocked);
19359        assert!(runner.state.votes.is_empty());
19360        assert!(runner.state.deliberation.is_empty());
19361    }
19362
19363    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19364    /// reads nothing else off it.
19365    fn runner_at(status: RunStatus) -> Runner {
19366        let mut state = RunState::new(
19367            PathBuf::from("/nonexistent/repo"),
19368            "main".to_owned(),
19369            "deadbeef".to_owned(),
19370            "task".to_owned(),
19371            Config::default(),
19372        );
19373        // These fixtures test execution flow, independent of host disk capacity.
19374        state.config.disk.min_free_bytes = 0;
19375        // These fixtures share one home and save concurrently. Short clock
19376        // IDs can collide, making an ownership test read another test's run.
19377        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19378        state.id = format!(
19379            "20000101-000000-{:04x}",
19380            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19381        );
19382        state.status = status;
19383        Runner {
19384            state,
19385            roles: ResolvedRoles {
19386                implementers: Vec::new(),
19387                judges: Vec::new(),
19388                reviewers: Vec::new(),
19389                fixer: None,
19390                conductor: conductor(),
19391                implementer_roster: Vec::new(),
19392                judge_roster: Vec::new(),
19393                reviewer_roster: Vec::new(),
19394            },
19395            sem: Arc::new(Semaphore::new(1)),
19396            pause: Pause::new(),
19397            interrupt: Pause::new(),
19398        }
19399    }
19400
19401    #[tokio::test]
19402    async fn targeted_fix_refuses_independent_ownership_conflicts() {
19403        crate::run::pin_test_home();
19404        let home = crate::run::home();
19405        let mut runner = runner_at(RunStatus::Ready);
19406        runner.state.driver_exited = true;
19407        runner.state.save().unwrap();
19408        let id = runner.state.id.clone();
19409        let path = runner.state.dir().join("run.json");
19410        let ids = ["R1-1-1".into()];
19411        let lease = crate::driver::maintenance(&home, &id).unwrap();
19412        for (guard, expected) in [
19413            (Some(lease), "currently being worked on"),
19414            (None, "ownership is being updated"),
19415        ] {
19416            let owner = if guard.is_none() {
19417                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
19418            } else {
19419                None
19420            };
19421            let before = std::fs::read(&path).unwrap();
19422            let err = runner
19423                .fix_selected(&ids, "ownership conflict", false)
19424                .await
19425                .unwrap_err();
19426            assert!(format!("{err:#}").contains(expected), "{err:#}");
19427            assert_eq!(std::fs::read(&path).unwrap(), before);
19428            assert!(!runner.state.dir().join("fix.lock").exists());
19429            drop(owner);
19430            drop(guard);
19431        }
19432        let mut disk = RunState::load(&id).unwrap();
19433        disk.driver_exited = false;
19434        disk.driver_pid = Some(std::process::id());
19435        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
19436        disk.save().unwrap();
19437        assert_eq!(
19438            disk.liveness_under(&home, false),
19439            crate::run::Liveness::Live
19440        );
19441        let before = std::fs::read(&path).unwrap();
19442        let err = runner
19443            .fix_selected(&ids, "live driver", false)
19444            .await
19445            .unwrap_err();
19446        assert!(
19447            err.to_string().contains("currently being worked on"),
19448            "{err:#}"
19449        );
19450        assert_eq!(std::fs::read(&path).unwrap(), before);
19451        assert!(!runner.state.dir().join("fix.lock").exists());
19452        disk.driver_exited = true;
19453        disk.driver_pid = None;
19454        disk.driver_started_at = None;
19455        disk.status = RunStatus::Reviewing;
19456        disk.save().unwrap();
19457        let before = std::fs::read(&path).unwrap();
19458        let err = runner
19459            .fix_selected(&ids, "stale state", false)
19460            .await
19461            .unwrap_err();
19462        assert!(
19463            err.to_string().contains("run changed since it was loaded"),
19464            "{err:#}"
19465        );
19466        assert_eq!(std::fs::read(&path).unwrap(), before);
19467        assert!(!runner.state.dir().join("fix.lock").exists());
19468        assert!(runner.state.operator_fixes.is_empty());
19469    }
19470
19471    #[tokio::test]
19472    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
19473        use std::future::Future;
19474        use std::task::Poll;
19475
19476        crate::run::pin_test_home();
19477        let home = crate::run::home();
19478        let repo = tempfile::tempdir().unwrap();
19479        let mut runner = runner_at(RunStatus::Ready);
19480        runner.state.repo = repo.path().to_path_buf();
19481        runner.state.driver_exited = true;
19482        runner.state.candidates.push(Candidate {
19483            index: 0,
19484            label: 'A',
19485            agent: "mock".into(),
19486            branch: "magi/test/A".into(),
19487            worktree: repo.path().join("wt"),
19488            summary: String::new(),
19489            stat: String::new(),
19490            files: 0,
19491            commits: 0,
19492            empty: false,
19493            failed: None,
19494            verified_noop: None,
19495            duration_ms: 0,
19496            folded: false,
19497        });
19498        runner.state.tally = Some(Tally {
19499            first_choice: BTreeMap::from([('A', 1)]),
19500            borda: BTreeMap::new(),
19501            winner: 'A',
19502            rankings: 1,
19503            unanimous_initial: true,
19504            deliberated: false,
19505            changed_votes: 0,
19506            unanimous_final: true,
19507            tie_break: None,
19508            judges: 1,
19509            present: 1,
19510            quorum: 1,
19511            met_quorum: true,
19512            uncontested: None,
19513        });
19514        runner.state.save().unwrap();
19515        let id = runner.state.id.clone();
19516        let dir = runner.state.dir();
19517        let before = std::fs::read(dir.join("run.json")).unwrap();
19518        let ids = ["R1-1-1".into()];
19519        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
19520        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
19521            Poll::Pending => Poll::Ready(()),
19522            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
19523        })
19524        .await;
19525        assert!(FixClaim::acquire(&dir).is_err());
19526        assert!(crate::driver::maintenance(&home, &id).is_err());
19527        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
19528        drop(fix);
19529        assert!(FixClaim::acquire(&dir).is_ok());
19530        assert!(crate::driver::maintenance(&home, &id).is_ok());
19531        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
19532    }
19533
19534    #[tokio::test]
19535    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19536        crate::run::pin_test_home();
19537        let temp = tempfile::tempdir().unwrap();
19538        let root = temp.path().canonicalize().unwrap();
19539        let repo = root.join("repo");
19540        std::fs::create_dir(&repo).unwrap();
19541        init_repo(&repo);
19542        git::git(&repo, &["config", "core.autocrlf", "false"])
19543            .await
19544            .unwrap();
19545        let mut runner = runner_at(RunStatus::Blocked);
19546        runner.state.repo = repo.clone();
19547        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19548        runner.state.config.agents = vec![conductor()];
19549        runner.state.config.graph.selected_implementer = Some("conductor".into());
19550        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19551        let (shell, command, setup_output) = if cfg!(windows) {
19552            (
19553                vec!["cmd".into(), "/C".into()],
19554                "echo ready>seat-ready",
19555                "ready\r\n",
19556            )
19557        } else {
19558            (
19559                vec!["sh".into(), "-c".into()],
19560                "printf ready > seat-ready",
19561                "ready",
19562            )
19563        };
19564        runner.state.config.verify.shell = Some(shell);
19565        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19566            run: Some(command.into()),
19567            ..Default::default()
19568        }];
19569        runner.state.save().unwrap();
19570        let path = runner.state.worktree_root().join("judge-1");
19571        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19572            .await
19573            .unwrap();
19574        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19575        git::git(&path, &["add", "."]).await.unwrap();
19576        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19577        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19578            .await
19579            .unwrap();
19580        git::git(&path, &["checkout", "--detach", &head])
19581            .await
19582            .unwrap();
19583        let evidence = crate::fold_evidence::snapshot(
19584            &runner.state,
19585            &crate::run::home().canonicalize().unwrap(),
19586            &head,
19587            64 * 1024 * 1024,
19588        )
19589        .await
19590        .unwrap();
19591        let mut contents = BTreeMap::new();
19592        contents.insert(
19593            repo.join("logs/HEAD"),
19594            format!("{head} {head} fixture\n").into_bytes(),
19595        );
19596        let record = serde_json::json!({
19597            "version":1, "run":runner.state.id, "source":path, "head":head,
19598            "evidence":evidence, "admin":{}, "admin_contents":contents,
19599            "history":{head.clone():evidence}, "phase":"evicted"
19600        });
19601        std::fs::write(
19602            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19603            serde_json::to_vec(&record).unwrap(),
19604        )
19605        .unwrap();
19606        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19607        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19608            .await
19609            .unwrap();
19610        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19611        assert!(
19612            !git::git_raw(&repo, &["cat-file", "-e", &head])
19613                .await
19614                .unwrap()
19615                .ok()
19616        );
19617        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19618        let error = resumed.execute().await.unwrap_err();
19619        assert!(
19620            error
19621                .to_string()
19622                .contains("selected implementation is held"),
19623            "{error:#}"
19624        );
19625        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19626        assert_eq!(
19627            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19628            setup_output
19629        );
19630        assert_eq!(
19631            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19632            "unrelated seat"
19633        );
19634        let error = resumed.execute().await.unwrap_err();
19635        assert!(
19636            error
19637                .to_string()
19638                .contains("selected implementation is held"),
19639            "{error:#}"
19640        );
19641        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19642        git::git(&path, &["add", "."]).await.unwrap();
19643        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19644        let next = git::git(
19645            &path,
19646            &[
19647                "commit-tree",
19648                &next_tree,
19649                "-p",
19650                &head,
19651                "-m",
19652                "next review checkpoint",
19653            ],
19654        )
19655        .await
19656        .unwrap();
19657        git::git(&path, &["checkout", "--detach", &next])
19658            .await
19659            .unwrap();
19660        resumed.state.reviews.push(
19661            serde_json::from_value(serde_json::json!({
19662                "round":1, "head":next, "reviews":[]
19663            }))
19664            .unwrap(),
19665        );
19666        resumed.state.save().unwrap();
19667        let error = resumed.execute().await.unwrap_err();
19668        assert!(
19669            error
19670                .to_string()
19671                .contains("selected implementation is held"),
19672            "{error:#}"
19673        );
19674        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
19675    }
19676
19677    #[tokio::test]
19678    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
19679        crate::run::pin_test_home();
19680        let mut runner = runner_at(RunStatus::Gating);
19681        runner.state.save().unwrap();
19682        let id = runner.state.id.clone();
19683        let passes = runner.state.passes.len();
19684        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19685        let mut claiming = Box::pin(runner.claim_driver(None));
19686        std::future::poll_fn(|cx| {
19687            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
19688            std::task::Poll::Ready(())
19689        })
19690        .await;
19691        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
19692        drop(owner);
19693        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
19694            .await
19695            .unwrap()
19696            .unwrap();
19697        assert_eq!(execution.runner.state.passes.len(), passes + 1);
19698        assert!(execution.runner.state.resource_block.is_none());
19699        assert_eq!(
19700            execution.runner.state.liveness(false),
19701            crate::run::Liveness::Live
19702        );
19703        drop(execution);
19704        assert!(RunState::load(&id).unwrap().driver_exited);
19705    }
19706
19707    #[tokio::test]
19708    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
19709        crate::run::pin_test_home();
19710        let mut runner = runner_at(RunStatus::Gating);
19711        runner.state.save().unwrap();
19712        // run.json can commit, but the subsequent lease metadata write fails.
19713        // Cleanup must run after releasing the short ownership lock.
19714        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
19715        assert!(runner.claim_driver(None).await.is_err());
19716        assert!(runner.state.driver_exited);
19717        assert_eq!(runner.state.driver_pid, None);
19718        let disk = RunState::load(&runner.state.id).unwrap();
19719        assert!(disk.driver_exited);
19720        assert_eq!(disk.driver_pid, None);
19721        assert_eq!(disk.status, RunStatus::Gating);
19722    }
19723
19724    #[tokio::test]
19725    async fn an_early_graph_error_releases_its_driver() {
19726        crate::run::pin_test_home();
19727        let mut runner = runner_at(RunStatus::Blocked);
19728        runner.state.config.graph.selected_implementer = Some("selected".into());
19729        runner.state.save().unwrap();
19730        assert!(runner.execute().await.is_err());
19731        let disk = RunState::load(&runner.state.id).unwrap();
19732        assert!(disk.driver_exited);
19733        assert_eq!(disk.driver_pid, None);
19734        assert_eq!(disk.status, RunStatus::Blocked);
19735    }
19736
19737    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
19738        crate::run::MergeRepair {
19739            question: "repair-question".into(),
19740            head: "old-head".into(),
19741            pr: "https://github.com/o/r/pull/42".into(),
19742            reviews: vec![review_round(false, 1, 1, 1, false, true)],
19743            gate: vec![outcome(Some(0), false)],
19744            gate_head: Some("old-head".into()),
19745            gate_fixes: Vec::new(),
19746            pre_gate: Vec::new(),
19747            phase,
19748            failure: None,
19749        }
19750    }
19751
19752    #[tokio::test]
19753    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
19754        crate::run::pin_test_home();
19755        let mut runner = runner_at(RunStatus::Landing);
19756        runner.state.merge_repairs.push(merge_repair_request(
19757            crate::run::MergeRepairPhase::Requested,
19758        ));
19759        runner.state.save().unwrap();
19760        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
19761        assert!(
19762            runner
19763                .execute()
19764                .await
19765                .unwrap_err()
19766                .to_string()
19767                .contains("already running")
19768        );
19769        assert_eq!(
19770            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19771            crate::run::MergeRepairPhase::Requested
19772        );
19773        drop(claim);
19774        let mut disk = runner.state.clone();
19775        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
19776        disk.save().unwrap();
19777        assert!(
19778            runner
19779                .execute()
19780                .await
19781                .unwrap_err()
19782                .to_string()
19783                .contains("decision changed")
19784        );
19785        assert_eq!(
19786            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19787            crate::run::MergeRepairPhase::Complete
19788        );
19789    }
19790
19791    #[test]
19792    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
19793        crate::run::pin_test_home();
19794        let mut runner = runner_at(RunStatus::Landing);
19795        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
19796        runner.state.reviews = request.reviews.clone();
19797        runner.state.gate = request.gate.clone();
19798        runner.state.gate_ran = true;
19799        runner.state.land_approval = Some(crate::run::LandApproval {
19800            question: "old".into(),
19801            head: "old-head".into(),
19802        });
19803        runner.state.merge_repairs.push(request);
19804        runner.begin_merge_repair_review(0).unwrap();
19805        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
19806        assert!(!runner.state.gate_status().ok());
19807        assert!(runner.state.land_approval.is_none());
19808        let disk = RunState::load(&runner.state.id).unwrap();
19809        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
19810        assert!(disk.merge_repairs[0].gate[0].ok());
19811        assert_eq!(
19812            disk.merge_repairs[0].phase,
19813            crate::run::MergeRepairPhase::Reviewing
19814        );
19815        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
19816        assert!(disk.reviews.is_empty());
19817    }
19818
19819    #[tokio::test]
19820    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
19821        crate::run::pin_test_home();
19822        for phase in [
19823            crate::run::MergeRepairPhase::Fixing,
19824            crate::run::MergeRepairPhase::Requested,
19825        ] {
19826            let mut runner = runner_at(RunStatus::Landing);
19827            runner.state.config.graph.land_rounds = 0;
19828            runner.state.merge_repairs.push(merge_repair_request(phase));
19829            runner.state.save().unwrap();
19830            assert!(!runner.repair_merge_review().await.unwrap());
19831            assert_eq!(runner.state.status, RunStatus::Blocked);
19832            assert_eq!(
19833                runner.state.merge_repairs[0].phase,
19834                crate::run::MergeRepairPhase::Failed
19835            );
19836            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
19837            assert!(
19838                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
19839                    "interrupted"
19840                } else {
19841                    "budget exhausted"
19842                })
19843            );
19844            assert!(runner.state.merge.is_none());
19845        }
19846    }
19847
19848    /// `park_here` folding in the reason `Pause::park_because` recorded -
19849    /// this is what lets an operator reading a run's events tell an
19850    /// interrupt-driven park from an ordinary shutdown park.
19851    #[test]
19852    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
19853        crate::run::pin_test_home();
19854        let mut runner = runner_at(RunStatus::Implementing);
19855        let interrupt = Pause::new();
19856        runner.watch_interrupt(interrupt.clone());
19857
19858        interrupt.park_because("task a1b2 asked to run first");
19859
19860        assert!(runner.park_here().expect("park_here"));
19861        assert!(runner.state.parked);
19862        let last = runner.state.events.last().expect("a park event");
19863        assert_eq!(last.node, "park");
19864        assert!(
19865            last.message.contains("task a1b2 asked to run first"),
19866            "expected the interrupt reason in {:?}",
19867            last.message
19868        );
19869    }
19870
19871    /// The cause is stored on the pass when it parks, and the first cause a
19872    /// shared pause was given is the one that stays.
19873    #[test]
19874    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
19875        crate::run::pin_test_home();
19876        let mut runner = runner_at(RunStatus::Implementing);
19877        runner.state.begin_pass();
19878        let shutdown = Pause::new();
19879        runner.on_pause(shutdown.clone());
19880        let upgrade = ParkCause::Upgrade {
19881            from: "0.121.0".to_owned(),
19882            to: Some("0.121.1".to_owned()),
19883        };
19884        shutdown.park_for(upgrade.clone());
19885        shutdown.park_for(ParkCause::Operator);
19886
19887        assert!(runner.park_here().expect("park_here"));
19888        assert_eq!(
19889            runner.state.passes[0].end,
19890            Some(crate::run::PassEnd::Parked { cause: upgrade })
19891        );
19892        let last = runner.state.events.last().expect("a park event");
19893        assert!(last.message.contains("0.121.0"), "{}", last.message);
19894    }
19895
19896    #[tokio::test]
19897    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
19898        crate::run::pin_test_home();
19899        let mut runner = runner_at(RunStatus::Reviewing);
19900        runner.state.save().unwrap();
19901        let mut execution = runner.claim_driver(None).await.expect("first execution");
19902        assert_eq!(execution.runner.state.passes.len(), 1);
19903        execution
19904            .driver
19905            .finish(&mut execution.runner.state)
19906            .await
19907            .unwrap();
19908    }
19909
19910    #[tokio::test]
19911    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
19912        crate::run::pin_test_home();
19913        let mut runner = runner_at(RunStatus::Reviewing);
19914        runner.state.config.agents = vec![conductor()];
19915        runner.state.config.graph.timeout_resource_wait = 0;
19916        runner.state.save().unwrap();
19917        let id = runner.state.id.clone();
19918        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19919        assert!(runner.claim_driver(None).await.is_err());
19920        drop(owner);
19921        drop(runner);
19922        let mut resumed = Runner::resume(&id).unwrap();
19923        assert_eq!(resumed.state.driver_claimed, Some(false));
19924        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
19925        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
19926        let mut execution = resumed
19927            .claim_driver(None)
19928            .await
19929            .expect("retry initial claim after reload");
19930        assert_eq!(execution.runner.state.driver_claimed, Some(true));
19931        assert_eq!(execution.runner.state.passes.len(), 1);
19932        execution
19933            .driver
19934            .finish(&mut execution.runner.state)
19935            .await
19936            .unwrap();
19937    }
19938
19939    #[tokio::test]
19940    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
19941        crate::run::pin_test_home();
19942        let mut runner = runner_at(RunStatus::Reviewing);
19943        runner.state.config.agents = vec![conductor()];
19944        runner.state.save().unwrap();
19945        let id = runner.state.id.clone();
19946        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
19947        let mut resumed = Runner::resume(&id).unwrap();
19948        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
19949        assert!(resumed.claim_driver(None).await.is_err());
19950        assert!(RunState::load(&id).unwrap().passes.is_empty());
19951        drop(lease);
19952        let mut execution = resumed.claim_driver(None).await.unwrap();
19953        execution
19954            .driver
19955            .finish(&mut execution.runner.state)
19956            .await
19957            .unwrap();
19958    }
19959
19960    #[tokio::test]
19961    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
19962        crate::run::pin_test_home();
19963        let mut runner = runner_at(RunStatus::Reviewing);
19964        let state = &mut runner.state;
19965        state.config.agents = vec![conductor()];
19966        state.driver_claimed = None;
19967        state.driver_pid = Some(std::process::id());
19968        state.driver_started_at = None;
19969        state.begin_pass();
19970        state.save().unwrap();
19971        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
19972        std::fs::write(
19973            state.dir().join("driver.json"),
19974            serde_json::to_vec(&serde_json::json!({
19975                "pid": state.driver_pid, "started_at": null,
19976                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
19977            }))
19978            .unwrap(),
19979        )
19980        .unwrap();
19981        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
19982        drop(lease);
19983        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
19984        let mut resumed = Runner::resume(&state.id).unwrap();
19985        assert!(!resumed.state.driver_exited);
19986        let mut execution = resumed
19987            .claim_driver(None)
19988            .await
19989            .expect("lease proves previous execution ended");
19990        assert_eq!(execution.runner.state.passes.len(), 2);
19991        execution
19992            .driver
19993            .finish(&mut execution.runner.state)
19994            .await
19995            .unwrap();
19996    }
19997
19998    #[tokio::test]
19999    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20000        crate::run::pin_test_home();
20001        let mut runner = runner_at(RunStatus::Reviewing);
20002        let mut json = serde_json::to_value(&runner.state).unwrap();
20003        json.as_object_mut().unwrap().remove("driver_claimed");
20004        runner.state = serde_json::from_value(json).unwrap();
20005        assert_eq!(runner.state.driver_claimed, None);
20006        runner.state.save().unwrap();
20007        let mut execution = runner
20008            .claim_driver(None)
20009            .await
20010            .expect("the execution lease, not a missing marker, excludes a second driver");
20011        assert_eq!(execution.runner.state.passes.len(), 1);
20012        execution
20013            .driver
20014            .finish(&mut execution.runner.state)
20015            .await
20016            .unwrap();
20017    }
20018
20019    #[tokio::test]
20020    async fn driver_admission_refuses_a_proven_live_driver() {
20021        crate::run::pin_test_home();
20022        let mut runner = runner_at(RunStatus::Reviewing);
20023        let pid = std::process::id();
20024        runner.state.driver_pid = Some(pid);
20025        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20026        assert!(runner.state.driver_started_at.is_some());
20027        runner.state.save().unwrap();
20028        let error = runner
20029            .claim_driver(None)
20030            .await
20031            .err()
20032            .expect("a live driver must refuse");
20033        assert!(error.to_string().contains("live driver"), "{error:#}");
20034        let saved = RunState::load(&runner.state.id).unwrap();
20035        assert_eq!(saved.driver_pid, Some(pid));
20036        assert_eq!(saved.status, RunStatus::Reviewing);
20037        assert!(saved.passes.is_empty());
20038    }
20039
20040    #[test]
20041    fn parking_resource_halt_persists_the_pass_once() {
20042        crate::run::pin_test_home();
20043        let mut runner = runner_at(RunStatus::Reviewing);
20044        runner.state.begin_pass();
20045        runner.state.resource_block = Some(crate::run::ResourceBlock {
20046            node: "fix".into(),
20047            kind: "shared build cache".into(),
20048            detail: "cancelled".into(),
20049            at: Timestamp::now(),
20050            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20051        });
20052        let cause = ParkCause::Upgrade {
20053            from: "old".into(),
20054            to: Some("new".into()),
20055        };
20056        runner.pause.park_for(cause.clone());
20057        // Both direct fixer exits and graph resource boundaries must complete
20058        // parking, rather than returning a stale Reviewing record.
20059        runner.stop_for_resource().unwrap();
20060        assert!(runner.resource_halt().unwrap());
20061        assert!(runner.park_here().unwrap());
20062        let saved = RunState::load(&runner.state.id).unwrap();
20063        assert!(saved.parked);
20064        assert_eq!(saved.status, RunStatus::Reviewing);
20065        assert!(saved.passes[0].ended_at.is_some());
20066        assert_eq!(
20067            saved.passes[0].end,
20068            Some(crate::run::PassEnd::Parked {
20069                cause: cause.clone()
20070            })
20071        );
20072        assert_eq!(
20073            saved.resource_block.unwrap().cause,
20074            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20075        );
20076        assert_eq!(
20077            saved
20078                .events
20079                .iter()
20080                .filter(|event| event.node == "park")
20081                .count(),
20082            1
20083        );
20084    }
20085
20086    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20087    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20088    /// cleared) must not make a *different* run - one only watching its own,
20089    /// unshared interrupt `Pause` - see itself as parked. If a future change
20090    /// ever collapsed these back into one handle, the interrupt scheduler
20091    /// would park every run for the rest of the daemon's life, not just the
20092    /// one it meant to interrupt.
20093    #[test]
20094    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20095        crate::run::pin_test_home();
20096        let mut runner = runner_at(RunStatus::Implementing);
20097        let shutdown = Pause::new();
20098        runner.on_pause(shutdown.clone());
20099        let interrupt = Pause::new();
20100        runner.watch_interrupt(interrupt.clone());
20101
20102        // Nobody has asked for anything yet.
20103        assert!(!runner.park_here().expect("park_here"));
20104        assert!(!runner.state.parked);
20105
20106        // Only the interrupt handle fires; the shutdown handle stays clear.
20107        interrupt.park_because("test");
20108        assert!(!shutdown.parked());
20109        assert!(runner.park_here().expect("park_here"));
20110    }
20111
20112    /// The property every prior attempt at this feature failed to pin down:
20113    /// asking a run to park while one of its nodes has a real, in-flight
20114    /// async operation running (an agent call, in production) must not cut
20115    /// that operation short. `park_here` is only ever consulted *between*
20116    /// `execute`'s node calls - see its own doc - so nothing inside a node
20117    /// can observe a park request until the node itself returns. This proves
20118    /// that structurally, with real `tokio` concurrency and a channel
20119    /// handshake (never a sleep, which would only prove "usually", not
20120    /// "cannot"): the "node" below reports that it has genuinely started,
20121    /// and only then is the park requested; the node still has to be told to
20122    /// finish before `park_here` is ever called, exactly mirroring every
20123    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20124    /// in `execute`.
20125    #[tokio::test]
20126    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20127        crate::run::pin_test_home();
20128        let mut runner = runner_at(RunStatus::Implementing);
20129        let interrupt = Pause::new();
20130        runner.watch_interrupt(interrupt.clone());
20131
20132        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20133        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20134
20135        // Stands in for one node's in-flight agent call: it proves it has
20136        // genuinely started, then blocks - exactly as a spawned CLI process
20137        // does - until told to finish.
20138        let node = async move {
20139            started_tx.send(()).expect("send started");
20140            finish_rx.await.expect("recv finish");
20141            "node finished"
20142        };
20143
20144        let interrupter = async move {
20145            started_rx.await.expect("recv started");
20146            // The call is now genuinely in flight. Ask it to park.
20147            interrupt.park_because("higher-priority task waiting");
20148            // Nothing the node does can observe this yet - there is no
20149            // check inside it, by construction - so let the executor run
20150            // anything pending and then let the node finish on its own.
20151            tokio::task::yield_now().await;
20152            finish_tx.send(()).expect("send finish");
20153        };
20154
20155        let (node_result, ()) = tokio::join!(node, interrupter);
20156        assert_eq!(
20157            node_result, "node finished",
20158            "the in-flight call ran to completion"
20159        );
20160
20161        // Only now, at the boundary the real `execute` would check right
20162        // after this node, does the park take effect.
20163        assert!(runner.park_here().expect("park_here"));
20164        assert!(runner.state.parked);
20165    }
20166
20167    /// A run parked mid-competition carries every field it had accumulated
20168    /// through the exact same disk round-trip an ordinary resume uses -
20169    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20170    /// Nothing about parking for an interrupt is a special case of that path;
20171    /// this is what proves it rather than assuming it.
20172    #[test]
20173    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20174        crate::run::pin_test_home();
20175        let mut runner = runner_at(RunStatus::Judging);
20176        // `Runner::resume` re-resolves roles from the saved config, which
20177        // refuses an empty roster - give it the same minimal one `conductor`
20178        // itself uses.
20179        runner.state.config.agents = vec![conductor()];
20180        runner.state.candidates = vec![Candidate {
20181            index: 0,
20182            label: 'A',
20183            agent: "alpha".to_owned(),
20184            branch: "magi/x/A".to_owned(),
20185            worktree: PathBuf::from("/nonexistent/worktree"),
20186            summary: "did the thing".to_owned(),
20187            stat: "1 file changed".to_owned(),
20188            files: 1,
20189            commits: 1,
20190            empty: false,
20191            failed: None,
20192            verified_noop: None,
20193            duration_ms: 1234,
20194            folded: false,
20195        }];
20196        let run_id = runner.state.id.clone();
20197
20198        let interrupt = Pause::new();
20199        runner.watch_interrupt(interrupt.clone());
20200        interrupt.park_because("task c3d4 asked to run first");
20201        assert!(runner.park_here().expect("park_here"));
20202
20203        let resumed = Runner::resume(&run_id).expect("resume");
20204        assert_eq!(resumed.state.candidates.len(), 1);
20205        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20206        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20207        assert_eq!(resumed.state.status, runner.state.status);
20208        assert!(
20209            resumed.state.parked,
20210            "still parked until `execute` actually walks the graph again"
20211        );
20212        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20213    }
20214
20215    /// A fresh open question on `run`, stored and handed back for assertions.
20216    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20217        let mut q = ask::Question::new(
20218            run.to_owned(),
20219            "implement".to_owned(),
20220            "impl-A".to_owned(),
20221            "Which storage backend should the cache use?".to_owned(),
20222            String::new(),
20223            vec!["SQLite".to_owned(), "Redis".to_owned()],
20224        );
20225        store.put(&mut q).unwrap();
20226        q
20227    }
20228
20229    #[test]
20230    fn a_failed_runs_open_question_is_abandoned() {
20231        ask_test_home();
20232        let store = ask::Questions::open();
20233        let mut runner = runner_at(RunStatus::Failed);
20234        let run = runner.state.id.clone();
20235        let q = ask_open_question(&store, &run);
20236
20237        runner.settle_questions();
20238
20239        let back = store.get(&q.id).unwrap();
20240        assert!(
20241            !back.status.open(),
20242            "the seat that asked died with the run; nobody is left to read an answer"
20243        );
20244        assert!(
20245            back.detail.contains(&run) && back.detail.contains("failed"),
20246            "the reason names what the run became, not just that it is gone: {}",
20247            back.detail
20248        );
20249    }
20250
20251    #[test]
20252    fn a_merged_runs_open_question_is_abandoned_too() {
20253        ask_test_home();
20254        let store = ask::Questions::open();
20255        // A run that finishes cleanly still leaves nobody to read an answer -
20256        // this is not only a failure-path cleanup.
20257        for status in [RunStatus::Merged, RunStatus::Ready] {
20258            let mut runner = runner_at(status);
20259            let run = runner.state.id.clone();
20260            let q = ask_open_question(&store, &run);
20261
20262            runner.settle_questions();
20263
20264            let back = store.get(&q.id).unwrap();
20265            assert!(
20266                !back.status.open(),
20267                "{status:?} run's question must not outlive the run"
20268            );
20269        }
20270    }
20271
20272    #[test]
20273    fn a_still_resumable_runs_open_question_is_left_alone() {
20274        ask_test_home();
20275        let store = ask::Questions::open();
20276        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20277        // review round and the seat sessions are all still on disk — so a
20278        // question asked mid-round may yet get a real answer from a real
20279        // resume. Sweeping it here would be exactly the failure mode this
20280        // whole feature exists to avoid on the other side.
20281        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20282            let mut runner = runner_at(status);
20283            let run = runner.state.id.clone();
20284            let q = ask_open_question(&store, &run);
20285
20286            runner.settle_questions();
20287
20288            let back = store.get(&q.id).unwrap();
20289            assert!(
20290                back.status.open(),
20291                "{status:?} is still alive; the question must still be waiting"
20292            );
20293        }
20294    }
20295
20296    #[test]
20297    fn settle_questions_never_touches_an_already_answered_question() {
20298        ask_test_home();
20299        let store = ask::Questions::open();
20300        let mut runner = runner_at(RunStatus::Failed);
20301        let run = runner.state.id.clone();
20302        let mut q = ask_open_question(&store, &run);
20303        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20304            .unwrap();
20305        store.put(&mut q).unwrap();
20306
20307        // Called twice, the way a crash-recovered daemon reclaim and the
20308        // graph's own cleanup both can for the same run — `abandon_for_run`
20309        // only ever touches what is still open, so this must be inert both
20310        // times, not merely the second.
20311        runner.settle_questions();
20312        runner.settle_questions();
20313
20314        let back = store.get(&q.id).unwrap();
20315        assert_eq!(
20316            back.status,
20317            ask::QuestionStatus::Answered,
20318            "a real answer is a decision on record, never overwritten by a sweep"
20319        );
20320    }
20321
20322    #[tokio::test]
20323    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20324        let tmp = tempfile::tempdir().unwrap();
20325        let home = tmp.path().join("home");
20326        let repo = tmp.path().join("repo");
20327        std::fs::create_dir(&home).unwrap();
20328        std::fs::create_dir(&repo).unwrap();
20329        init_repo(&repo);
20330
20331        let mut config = Config::default();
20332        config.graph.worktree_root = Some(tmp.path().join("wt"));
20333        config.verify.build_cache = crate::config::BuildCache::Isolated;
20334        let mut state = RunState::new(
20335            repo.clone(),
20336            "main".into(),
20337            "base".into(),
20338            "fold fixture".into(),
20339            config,
20340        );
20341        let root = state.worktree_root();
20342        let mut outputs = Vec::new();
20343        for name in ["idle", "busy"] {
20344            let checkout = root.join(name);
20345            git::worktree_add_detached(&repo, &checkout, "main")
20346                .await
20347                .unwrap();
20348            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20349            let output = target.join("generated");
20350            std::fs::write(&output, name).unwrap();
20351            outputs.push((target, output));
20352        }
20353        let unknown = crate::build_target::root(&home)
20354            .join("00000000-0000-0000-0000-000000000000")
20355            .join("target");
20356        std::fs::create_dir_all(&unknown).unwrap();
20357        let unowned = unknown.join("generated");
20358        std::fs::write(&unowned, "keep").unwrap();
20359        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20360        let crate::cache::AcquireOutcome::Acquired(_lease) =
20361            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20362        else {
20363            panic!("fixture target must be free");
20364        };
20365
20366        fold_run(&mut state, true, &home).await.unwrap();
20367        assert!(!root.exists());
20368        assert!(!outputs[0].1.exists());
20369        assert!(outputs[1].1.is_file());
20370        assert!(unowned.is_file());
20371    }
20372
20373    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20374    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20375    /// without merging, whose winner is still the operator's answer to read.
20376    /// Nothing previously called `fold_run` itself with a real `tally`, so
20377    /// this is the first test to pin down the one distinction the whole
20378    /// automatic-fold feature depends on: the winner's worktree and branch
20379    /// must survive, everything else sharing the run's worktree bay - a
20380    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20381    /// second sweep treats every non-winner directory under the bay alike -
20382    /// must not.
20383    #[tokio::test]
20384    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20385        crate::run::pin_test_home();
20386        let tmp = tempfile::tempdir().expect("tempdir");
20387        let repo = tmp.path().join("repo");
20388        std::fs::create_dir_all(&repo).unwrap();
20389        init_repo(&repo);
20390
20391        let mut config = Config::default();
20392        config.graph.worktree_root = Some(tmp.path().join("wt"));
20393
20394        let mut state = RunState::new(
20395            repo.clone(),
20396            "main".to_owned(),
20397            "deadbeef".to_owned(),
20398            "task".to_owned(),
20399            config,
20400        );
20401        let root = state.worktree_root();
20402        let wt_a = root.join("cand-A");
20403        let wt_b = root.join("cand-B");
20404        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20405            .await
20406            .expect("worktree A");
20407        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20408            .await
20409            .expect("worktree B");
20410
20411        state.candidates = vec![
20412            Candidate {
20413                index: 0,
20414                label: 'A',
20415                agent: "alpha".to_owned(),
20416                branch: "magi/x/A".to_owned(),
20417                worktree: wt_a.clone(),
20418                summary: String::new(),
20419                stat: String::new(),
20420                files: 0,
20421                commits: 0,
20422                empty: false,
20423                failed: None,
20424                verified_noop: None,
20425                duration_ms: 0,
20426                folded: false,
20427            },
20428            Candidate {
20429                index: 1,
20430                label: 'B',
20431                agent: "beta".to_owned(),
20432                branch: "magi/x/B".to_owned(),
20433                worktree: wt_b.clone(),
20434                summary: String::new(),
20435                stat: String::new(),
20436                files: 0,
20437                commits: 0,
20438                empty: false,
20439                failed: None,
20440                verified_noop: None,
20441                duration_ms: 0,
20442                folded: false,
20443            },
20444        ];
20445        state.tally = Some(Tally {
20446            first_choice: BTreeMap::from([('A', 1)]),
20447            borda: BTreeMap::new(),
20448            winner: 'A',
20449            rankings: 1,
20450            unanimous_initial: true,
20451            deliberated: false,
20452            changed_votes: 0,
20453            unanimous_final: true,
20454            tie_break: None,
20455            judges: 1,
20456            present: 1,
20457            quorum: 1,
20458            met_quorum: true,
20459            uncontested: None,
20460        });
20461        state.status = RunStatus::Ready;
20462
20463        fold_run(&mut state, false, &crate::run::home())
20464            .await
20465            .expect("fold_run");
20466
20467        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20468        assert!(
20469            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20470            "the unmerged winner's branch survives"
20471        );
20472        assert!(
20473            !state.candidates[0].folded,
20474            "the winner is not marked folded"
20475        );
20476
20477        assert!(!wt_b.exists(), "the loser's worktree is removed");
20478        assert!(
20479            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20480            "the loser's branch is removed"
20481        );
20482        assert!(state.candidates[1].folded, "the loser is marked folded");
20483    }
20484
20485    #[tokio::test]
20486    #[cfg(unix)]
20487    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20488        use std::os::fd::AsRawFd as _;
20489        use std::time::Duration;
20490
20491        let tmp = tempfile::tempdir().unwrap();
20492        let repo = tmp.path().join("repo");
20493        std::fs::create_dir_all(&repo).unwrap();
20494        init_repo(&repo);
20495        let common = repo.join(".git");
20496        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20497        let home = tmp.path().join("home");
20498        let mut config = Config::default();
20499        config.coordination = crate::config::test_coordination();
20500        config.graph.worktree_root = Some(tmp.path().join("wt"));
20501        config.graph.timeout_resource_wait = 1;
20502        let mut state = RunState::new(
20503            repo.clone(),
20504            "main".into(),
20505            "deadbeef".into(),
20506            "task".into(),
20507            config,
20508        );
20509        let root = state.worktree_root();
20510        let candidate = root.join("cand-A");
20511        let reviewer = root.join("review-1");
20512        let branch = state.branch_for('A');
20513        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20514            .await
20515            .unwrap();
20516        git::worktree_add_detached(&repo, &reviewer, "main")
20517            .await
20518            .unwrap();
20519        git::acquire_worktree_config(&repo).await.unwrap();
20520        state.enabled_worktree_config = true;
20521        state.status = RunStatus::Ready;
20522        state.candidates.push(Candidate {
20523            index: 0,
20524            label: 'A',
20525            agent: "implement".into(),
20526            branch: branch.clone(),
20527            worktree: candidate.clone(),
20528            summary: String::new(),
20529            stat: String::new(),
20530            files: 0,
20531            commits: 0,
20532            empty: false,
20533            failed: None,
20534            verified_noop: None,
20535            duration_ms: 0,
20536            folded: false,
20537        });
20538        state.save_under(&home).unwrap();
20539        let config_before = std::fs::read(common.join("config")).unwrap();
20540        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20541            .await
20542            .unwrap();
20543        // A separate OS handle bypasses the launcher's local gate, exactly as
20544        // an external updater does, and must still prevent all folding work.
20545        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20546        assert_eq!(
20547            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20548            0
20549        );
20550        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20551        assert!(
20552            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20553                .await
20554                .is_err()
20555        );
20556        assert!(candidate.exists());
20557        assert!(reviewer.exists());
20558        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20559        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20560        assert_eq!(
20561            git::git(&repo, &["worktree", "list", "--porcelain"])
20562                .await
20563                .unwrap(),
20564            worktrees_before
20565        );
20566        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20567            .await
20568            .unwrap()
20569            .unwrap_err();
20570        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20571        drop(fold);
20572        assert!(candidate.exists() && reviewer.exists());
20573        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20574        assert_eq!(
20575            state.resource_block.as_ref().unwrap().kind,
20576            "repository coordination"
20577        );
20578        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20579        drop(external);
20580        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20581        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20582            .await
20583            .unwrap()
20584            .unwrap();
20585        drop(fold);
20586        assert!(removed.contains(&branch));
20587        assert!(!root.exists());
20588        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20589        assert!(state.candidates[0].folded);
20590        assert!(!state.enabled_worktree_config);
20591        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20592        let enabled = git::git_raw(
20593            &repo,
20594            &["config", "--local", "--get", "extensions.worktreeConfig"],
20595        )
20596        .await
20597        .unwrap();
20598        assert!(!enabled.ok(), "the last config reference was released");
20599    }
20600
20601    /// A branch handed to a later run is that run's (and its pull request's):
20602    /// folding the run that released it must not delete it.
20603    #[tokio::test]
20604    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20605        let tmp = tempfile::tempdir().expect("tempdir");
20606        let repo = tmp.path().join("repo");
20607        std::fs::create_dir_all(&repo).unwrap();
20608        init_repo(&repo);
20609        let home = tmp.path().join("home");
20610
20611        let mut config = Config::default();
20612        config.graph.worktree_root = Some(tmp.path().join("wt"));
20613        let mut state = RunState::new(
20614            repo.clone(),
20615            "main".to_owned(),
20616            "deadbeef".to_owned(),
20617            "task".to_owned(),
20618            config,
20619        );
20620        // The worktree is already gone (released); the branch survives.
20621        git::git(&repo, &["branch", "magi/x/A", "main"])
20622            .await
20623            .expect("branch");
20624        state.candidates = vec![Candidate {
20625            index: 0,
20626            label: 'A',
20627            agent: "alpha".to_owned(),
20628            branch: "magi/x/A".to_owned(),
20629            worktree: state.worktree_root().join("cand-A"),
20630            summary: String::new(),
20631            stat: String::new(),
20632            files: 0,
20633            commits: 0,
20634            empty: false,
20635            failed: None,
20636            verified_noop: None,
20637            duration_ms: 0,
20638            folded: true,
20639        }];
20640        state.released_to = Some("20260901-000000-new1".to_owned());
20641        state.released_branches = vec!["magi/x/A".to_owned()];
20642
20643        fold_run(&mut state, true, &home).await.expect("fold_run");
20644        state.status = RunStatus::Merged;
20645        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20646        state.merge = Some(crate::run::MergeOutcome {
20647            mode: MergeMode::Pr,
20648            ok: true,
20649            detail: "confirmed merged".into(),
20650            empty: false,
20651        });
20652        fold_run(&mut state, true, &home)
20653            .await
20654            .expect("merged fold");
20655
20656        assert!(
20657            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20658            "the handed-over branch survives a fold"
20659        );
20660    }
20661
20662    /// A winner with nothing ahead of the base is caught before `gh` is ever
20663    /// asked for a pull request, and the message carries what the task's
20664    /// references resolved to.
20665    #[tokio::test]
20666    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
20667        let tmp = tempfile::tempdir().expect("tempdir");
20668        let repo = tmp.path().join("repo");
20669        std::fs::create_dir_all(&repo).unwrap();
20670        init_repo(&repo);
20671        let run = |args: &[&str]| {
20672            let out = std::process::Command::new("git")
20673                .quiet()
20674                .args(args)
20675                .current_dir(&repo)
20676                .output()
20677                .expect("spawn git");
20678            assert!(out.status.success(), "git {args:?}");
20679        };
20680        run(&["branch", "magi/x/A"]);
20681        run(&["checkout", "-q", "-b", "magi/x/B"]);
20682        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
20683        run(&["add", "-A"]);
20684        run(&["commit", "-q", "-m", "work"]);
20685        run(&["checkout", "-q", "main"]);
20686
20687        // A pull request is compared against the remote's base, so the
20688        // fixture needs one. Before it exists nothing can be read, and the
20689        // answer must be "not empty".
20690        let probe = RunState::new(
20691            repo.clone(),
20692            "main".to_owned(),
20693            "deadbeef".to_owned(),
20694            "task".to_owned(),
20695            Config::default(),
20696        );
20697        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
20698        let bare = tmp.path().join("origin.git");
20699        let out = std::process::Command::new("git")
20700            .quiet()
20701            .args(["init", "-q", "--bare"])
20702            .arg(&bare)
20703            .output()
20704            .expect("spawn git");
20705        assert!(out.status.success(), "git init --bare");
20706        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
20707        run(&["push", "-q", "origin", "main"]);
20708
20709        let mut state = RunState::new(
20710            repo.clone(),
20711            "main".to_owned(),
20712            "deadbeef".to_owned(),
20713            "task".to_owned(),
20714            Config::default(),
20715        );
20716        state.seeds = vec![refs::Seed {
20717            token: "magi/27b2/A".to_owned(),
20718            kind: refs::SeedKind::Unresolved,
20719            sha: String::new(),
20720            branch: true,
20721            detail: "no branch or commit named magi/27b2/A".to_owned(),
20722        }];
20723
20724        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
20725        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
20726        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
20727        let detail = empty_candidate_detail(&state, "main");
20728        assert!(detail.starts_with("empty candidate"), "{detail}");
20729        assert!(!detail.contains("magi/27b2/A"), "{detail}");
20730        assert!(detail.contains("--start-from"), "{detail}");
20731    }
20732
20733    /// `status == Ready` used to be read as "this is the harmless
20734    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
20735    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
20736    /// run's PR was closed without merging — and reentering `merge` with
20737    /// `mode` still `Pr` does not know the difference, so it pushed and
20738    /// opened a second pull request. `mode == Local` reproduces the same
20739    /// blind spot without a network call: reentry must not attempt another
20740    /// git merge once this node has already recorded an outcome.
20741    #[tokio::test]
20742    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
20743        let tmp = tempfile::tempdir().expect("tempdir");
20744        let repo = tmp.path().join("repo");
20745        std::fs::create_dir_all(&repo).unwrap();
20746        init_repo(&repo);
20747
20748        let mut config = Config::default();
20749        config.merge.mode = MergeMode::Local;
20750
20751        let mut state = RunState::new(
20752            repo.clone(),
20753            "main".to_owned(),
20754            "deadbeef".to_owned(),
20755            "task".to_owned(),
20756            config,
20757        );
20758        state.candidates = vec![Candidate {
20759            index: 0,
20760            label: 'A',
20761            agent: "alpha".to_owned(),
20762            branch: "does-not-exist".to_owned(),
20763            worktree: repo.clone(),
20764            summary: String::new(),
20765            stat: String::new(),
20766            files: 0,
20767            commits: 0,
20768            empty: false,
20769            failed: None,
20770            verified_noop: None,
20771            duration_ms: 0,
20772            folded: false,
20773        }];
20774        state.tally = Some(Tally {
20775            first_choice: BTreeMap::from([('A', 1)]),
20776            borda: BTreeMap::new(),
20777            winner: 'A',
20778            rankings: 1,
20779            unanimous_initial: true,
20780            deliberated: false,
20781            changed_votes: 0,
20782            unanimous_final: true,
20783            tie_break: None,
20784            judges: 0,
20785            present: 0,
20786            quorum: 0,
20787            met_quorum: true,
20788            uncontested: Some("only candidate A produced a change".to_owned()),
20789        });
20790        state.reviews = vec![ReviewRound {
20791            round: 1,
20792            head: "deadbeef".to_owned(),
20793            verified_head: None,
20794            verified_at: None,
20795            reviews: Vec::new(),
20796            e2e: Vec::new(),
20797            fix: None,
20798            blocking: 0,
20799            answered: 0,
20800            expected: 0,
20801            clean: true,
20802            verify_retried: false,
20803            e2e_deferred: false,
20804            e2e_defer_reason: None,
20805            progressed: false,
20806            vote_split: false,
20807            reconsideration: Vec::new(),
20808            verdict: None,
20809        }];
20810        state.gate = vec![CommandOutcome {
20811            command: "test".to_owned(),
20812            code: Some(0),
20813            output_tail: String::new(),
20814            duration_ms: 0,
20815            resource_blocked: false,
20816        }];
20817        state.gate_ran = true;
20818        // Reached its conclusion already — e.g. `land` closing the PR without
20819        // merging it, which (like the honest `MergeMode::None` path) leaves
20820        // `status` at `Ready`. The recorded outcome is what actually marks
20821        // this node done.
20822        state.status = RunStatus::Ready;
20823        state.merge = Some(MergeOutcome {
20824            mode: MergeMode::Local,
20825            ok: false,
20826            detail: "already concluded".to_owned(),
20827            empty: false,
20828        });
20829
20830        let mut runner = Runner {
20831            state,
20832            roles: ResolvedRoles {
20833                implementers: Vec::new(),
20834                judges: Vec::new(),
20835                reviewers: Vec::new(),
20836                fixer: None,
20837                conductor: conductor(),
20838                implementer_roster: Vec::new(),
20839                judge_roster: Vec::new(),
20840                reviewer_roster: Vec::new(),
20841            },
20842            sem: Arc::new(Semaphore::new(1)),
20843            pause: Pause::new(),
20844            interrupt: Pause::new(),
20845        };
20846
20847        runner.merge().await.expect("merge");
20848
20849        assert_eq!(
20850            runner.state.status,
20851            RunStatus::Ready,
20852            "a concluded run's status must not change on reentry"
20853        );
20854        assert_eq!(
20855            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
20856            Some("already concluded"),
20857            "merge must not run again once the node already recorded an outcome"
20858        );
20859    }
20860
20861    /// `gate` leaves `state.gate_ran` false both before it has ever run and
20862    /// when its last attempt was resource-blocked (the shared build cache
20863    /// could not be acquired or confirmed fresh in time - see
20864    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
20865    /// `Vec` this also leaves behind used to read as "nothing failed" and let
20866    /// a run merge a tree the gate never actually checked - exactly the case
20867    /// a contended cache produces on every retry until it clears. `merge`
20868    /// must refuse until `gate` has actually recorded an attempt.
20869    #[tokio::test]
20870    async fn merge_refuses_a_gate_that_has_not_actually_run() {
20871        let tmp = tempfile::tempdir().expect("tempdir");
20872        let repo = tmp.path().join("repo");
20873        std::fs::create_dir_all(&repo).unwrap();
20874        init_repo(&repo);
20875
20876        let mut config = Config::default();
20877        config.merge.mode = MergeMode::Local;
20878
20879        let mut state = RunState::new(
20880            repo.clone(),
20881            "main".to_owned(),
20882            "deadbeef".to_owned(),
20883            "task".to_owned(),
20884            config,
20885        );
20886        state.candidates = vec![Candidate {
20887            index: 0,
20888            label: 'A',
20889            agent: "alpha".to_owned(),
20890            branch: "does-not-exist".to_owned(),
20891            worktree: repo.clone(),
20892            summary: String::new(),
20893            stat: String::new(),
20894            files: 0,
20895            commits: 0,
20896            empty: false,
20897            failed: None,
20898            verified_noop: None,
20899            duration_ms: 0,
20900            folded: false,
20901        }];
20902        state.tally = Some(Tally {
20903            first_choice: BTreeMap::from([('A', 1)]),
20904            borda: BTreeMap::new(),
20905            winner: 'A',
20906            rankings: 1,
20907            unanimous_initial: true,
20908            deliberated: false,
20909            changed_votes: 0,
20910            unanimous_final: true,
20911            tie_break: None,
20912            judges: 0,
20913            present: 0,
20914            quorum: 0,
20915            met_quorum: true,
20916            uncontested: Some("only candidate A produced a change".to_owned()),
20917        });
20918        state.reviews = vec![ReviewRound {
20919            round: 1,
20920            head: "deadbeef".to_owned(),
20921            verified_head: None,
20922            verified_at: None,
20923            reviews: Vec::new(),
20924            e2e: Vec::new(),
20925            fix: None,
20926            blocking: 0,
20927            answered: 0,
20928            expected: 0,
20929            clean: true,
20930            verify_retried: false,
20931            e2e_deferred: false,
20932            e2e_defer_reason: None,
20933            progressed: false,
20934            vote_split: false,
20935            reconsideration: Vec::new(),
20936            verdict: None,
20937        }];
20938        // The point: `gate` has not recorded anything yet.
20939        state.gate = Vec::new();
20940        state.gate_ran = false;
20941        state.status = RunStatus::Gating;
20942
20943        let mut runner = Runner {
20944            state,
20945            roles: ResolvedRoles {
20946                implementers: Vec::new(),
20947                judges: Vec::new(),
20948                reviewers: Vec::new(),
20949                fixer: None,
20950                conductor: conductor(),
20951                implementer_roster: Vec::new(),
20952                judge_roster: Vec::new(),
20953                reviewer_roster: Vec::new(),
20954            },
20955            sem: Arc::new(Semaphore::new(1)),
20956            pause: Pause::new(),
20957            interrupt: Pause::new(),
20958        };
20959
20960        runner.merge().await.expect("merge");
20961
20962        assert!(
20963            runner.state.merge.is_none(),
20964            "an empty gate must never be read as a passing one: {:?}",
20965            runner.state.merge
20966        );
20967    }
20968
20969    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
20970    /// commands configured and `merge.mode` is `none` (a review-only run).
20971    /// `gate` must still record a real attempt — zero commands, vacuously
20972    /// passed — rather than leaving `state.gate` empty in a way `merge`
20973    /// cannot tell apart from "never ran"; otherwise the run reaches
20974    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
20975    #[tokio::test]
20976    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
20977        let tmp = tempfile::tempdir().expect("tempdir");
20978        let repo = tmp.path().join("repo");
20979        std::fs::create_dir_all(&repo).unwrap();
20980        init_repo(&repo);
20981
20982        // Default config: `verify.gate` empty, `merge.mode` is `none`.
20983        let config = Config::default();
20984
20985        let mut state = RunState::new(
20986            repo.clone(),
20987            "main".to_owned(),
20988            "deadbeef".to_owned(),
20989            "task".to_owned(),
20990            config,
20991        );
20992        state.candidates = vec![Candidate {
20993            index: 0,
20994            label: 'A',
20995            agent: "alpha".to_owned(),
20996            branch: "does-not-exist".to_owned(),
20997            worktree: repo.clone(),
20998            summary: String::new(),
20999            stat: String::new(),
21000            files: 0,
21001            commits: 0,
21002            empty: false,
21003            failed: None,
21004            verified_noop: None,
21005            duration_ms: 0,
21006            folded: false,
21007        }];
21008        state.tally = Some(Tally {
21009            first_choice: BTreeMap::from([('A', 1)]),
21010            borda: BTreeMap::new(),
21011            winner: 'A',
21012            rankings: 1,
21013            unanimous_initial: true,
21014            deliberated: false,
21015            changed_votes: 0,
21016            unanimous_final: true,
21017            tie_break: None,
21018            judges: 0,
21019            present: 0,
21020            quorum: 0,
21021            met_quorum: true,
21022            uncontested: Some("only candidate A produced a change".to_owned()),
21023        });
21024        state.reviews = vec![ReviewRound {
21025            round: 1,
21026            head: "deadbeef".to_owned(),
21027            verified_head: None,
21028            verified_at: None,
21029            reviews: Vec::new(),
21030            e2e: Vec::new(),
21031            fix: None,
21032            blocking: 0,
21033            answered: 0,
21034            expected: 0,
21035            clean: true,
21036            verify_retried: false,
21037            e2e_deferred: false,
21038            e2e_defer_reason: None,
21039            progressed: false,
21040            vote_split: false,
21041            reconsideration: Vec::new(),
21042            verdict: None,
21043        }];
21044
21045        let mut runner = Runner {
21046            state,
21047            roles: ResolvedRoles {
21048                implementers: Vec::new(),
21049                judges: Vec::new(),
21050                reviewers: Vec::new(),
21051                fixer: None,
21052                conductor: conductor(),
21053                implementer_roster: Vec::new(),
21054                judge_roster: Vec::new(),
21055                reviewer_roster: Vec::new(),
21056            },
21057            sem: Arc::new(Semaphore::new(1)),
21058            pause: Pause::new(),
21059            interrupt: Pause::new(),
21060        };
21061
21062        runner.gate().await.expect("gate");
21063        assert!(
21064            runner.state.gate_ran,
21065            "zero configured commands is still a real attempt, not an unrun gate"
21066        );
21067        assert!(runner.state.gate.is_empty());
21068        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21069        assert_ne!(
21070            runner.state.status,
21071            RunStatus::Blocked,
21072            "a gate with nothing to check must not read as failed"
21073        );
21074
21075        runner.merge().await.expect("merge");
21076        assert_eq!(
21077            runner.state.status,
21078            RunStatus::Ready,
21079            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21080        );
21081    }
21082
21083    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21084    /// `verify.gate` (so the e2e leg and the final gate never build against
21085    /// different directories). With zero `verify.gate` commands but a
21086    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21087    /// that lease before discovering it had nothing to run - so a repo with
21088    /// no gate commands could come back `resource_blocked` (and therefore
21089    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21090    /// cache, exactly the contention this run's own zero commands could
21091    /// never have touched. `gate` must recognise there is nothing to check
21092    /// before it ever asks for the lease.
21093    #[tokio::test]
21094    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21095        crate::run::pin_test_home();
21096        let home = crate::run::home();
21097
21098        let tmp = tempfile::tempdir().expect("tempdir");
21099        let repo = tmp.path().join("repo");
21100        std::fs::create_dir_all(&repo).unwrap();
21101        init_repo(&repo);
21102        // Unique to this test, so holding its lease cannot collide with
21103        // another test sharing the same process-wide `home`.
21104        let cache_dir = tmp.path().join("target");
21105
21106        let mut config = Config::default();
21107        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21108        // `verify.gate` stays empty (the default). Any accidental cache
21109        // acquisition must report contention immediately, regardless of how
21110        // long unrelated Git subprocesses take under parallel test load.
21111        config.graph.timeout_verify = Some(2);
21112        config.graph.timeout_resource_wait = 0;
21113
21114        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21115        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21116            .expect("no io error acquiring directly")
21117        {
21118            crate::cache::AcquireOutcome::Acquired(g) => g,
21119            crate::cache::AcquireOutcome::Busy(b) => {
21120                panic!("expected the direct acquire to win the lease first: {b:?}")
21121            }
21122        };
21123
21124        let mut state = RunState::new(
21125            repo.clone(),
21126            "main".to_owned(),
21127            "deadbeef".to_owned(),
21128            "task".to_owned(),
21129            config,
21130        );
21131        state.candidates = vec![Candidate {
21132            index: 0,
21133            label: 'A',
21134            agent: "alpha".to_owned(),
21135            branch: "does-not-exist".to_owned(),
21136            worktree: repo.clone(),
21137            summary: String::new(),
21138            stat: String::new(),
21139            files: 0,
21140            commits: 0,
21141            empty: false,
21142            failed: None,
21143            verified_noop: None,
21144            duration_ms: 0,
21145            folded: false,
21146        }];
21147        state.tally = Some(Tally {
21148            first_choice: BTreeMap::from([('A', 1)]),
21149            borda: BTreeMap::new(),
21150            winner: 'A',
21151            rankings: 1,
21152            unanimous_initial: true,
21153            deliberated: false,
21154            changed_votes: 0,
21155            unanimous_final: true,
21156            tie_break: None,
21157            judges: 0,
21158            present: 0,
21159            quorum: 0,
21160            met_quorum: true,
21161            uncontested: Some("only candidate A produced a change".to_owned()),
21162        });
21163        state.reviews = vec![ReviewRound {
21164            round: 1,
21165            head: "deadbeef".to_owned(),
21166            verified_head: None,
21167            verified_at: None,
21168            reviews: Vec::new(),
21169            e2e: Vec::new(),
21170            fix: None,
21171            blocking: 0,
21172            answered: 0,
21173            expected: 0,
21174            clean: true,
21175            verify_retried: false,
21176            e2e_deferred: false,
21177            e2e_defer_reason: None,
21178            progressed: false,
21179            vote_split: false,
21180            reconsideration: Vec::new(),
21181            verdict: None,
21182        }];
21183
21184        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21185        state.reviews[0].e2e = vec![CommandOutcome {
21186            command: state.config.verify.e2e[0].clone(),
21187            code: Some(0),
21188            output_tail: String::new(),
21189            duration_ms: 0,
21190            resource_blocked: false,
21191        }];
21192        let mut runner = Runner {
21193            state,
21194            roles: ResolvedRoles {
21195                implementers: Vec::new(),
21196                judges: Vec::new(),
21197                reviewers: Vec::new(),
21198                fixer: None,
21199                conductor: conductor(),
21200                implementer_roster: Vec::new(),
21201                judge_roster: Vec::new(),
21202                reviewer_roster: Vec::new(),
21203            },
21204            sem: Arc::new(Semaphore::new(1)),
21205            pause: Pause::new(),
21206            interrupt: Pause::new(),
21207        };
21208
21209        runner.gate().await.expect("gate");
21210        assert!(runner.state.resource_block.is_none());
21211        assert!(
21212            !runner
21213                .state
21214                .events
21215                .iter()
21216                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21217            "a gate with nothing to run must never request the held cache lease"
21218        );
21219        assert!(
21220            runner.state.gate_ran,
21221            "zero commands is still a real, immediate attempt"
21222        );
21223        assert!(runner.state.gate.is_empty());
21224        assert_ne!(
21225            runner.state.status,
21226            RunStatus::Blocked,
21227            "must not read as resource-blocked on a lease it never asked for"
21228        );
21229    }
21230
21231    /// A separate process carries a live worker's environment throughout all
21232    /// verification entry points; the parallel harness never changes its env.
21233    #[cfg(unix)]
21234    #[tokio::test]
21235    async fn verification_is_standalone_inside_a_live_worker() {
21236        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21237        if std::env::var_os(CHILD).is_none() {
21238            let home = tempfile::tempdir().unwrap();
21239            let generation = crate::worker::pin_current(home.path()).unwrap();
21240            let output = std::process::Command::new(std::env::current_exe().unwrap())
21241                .args([
21242                    "--exact",
21243                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21244                    "--nocapture",
21245                ])
21246                .env(CHILD, "1")
21247                .env("MAGI_HOME", home.path())
21248                .env("MAGI_WORKER_HOME", home.path())
21249                .env("MAGI_WORKER_ID", "abcdef")
21250                .env("MAGI_WORKER_GENERATION", &generation.id)
21251                .env("MAGI_WORKER_EXE", &generation.executable)
21252                .env("MAGI_RUN", "verification-parent")
21253                .env("MAGI_NODE", "gate")
21254                .env("MAGI_SEAT", "worker-fixture")
21255                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21256                .env("MAGI_NO_AUTOUPDATE", "0")
21257                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21258                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21259                .env(
21260                    "VERIFY_EXPECT_TOOLCHAIN",
21261                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21262                )
21263                .env(
21264                    "VERIFY_EXPECT_CACHE",
21265                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21266                )
21267                .output()
21268                .unwrap();
21269            assert!(
21270                output.status.success()
21271                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21272                "{}\n{}",
21273                String::from_utf8_lossy(&output.stdout),
21274                String::from_utf8_lossy(&output.stderr)
21275            );
21276            return;
21277        }
21278        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21279        let home = crate::run::home();
21280        let directory = home.join("workers/jobs/abcdef");
21281        std::fs::create_dir_all(&directory).unwrap();
21282        let job = crate::worker::Job {
21283            id: "abcdef".into(),
21284            sequence: 1,
21285            kind: "task".into(),
21286            key: "task:verification".into(),
21287            payload: serde_json::json!({}),
21288            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21289            version: Some(env!("CARGO_PKG_VERSION").into()),
21290            status: crate::worker::Status::Running,
21291            result: None,
21292            pid: Some(std::process::id()),
21293            created_at: 0,
21294            finished_at: None,
21295        };
21296        std::fs::write(
21297            directory.join("job.json"),
21298            serde_json::to_vec(&job).unwrap(),
21299        )
21300        .unwrap();
21301        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21302        let assert_worker = || {
21303            assert_eq!(
21304                crate::worker::current_job(&home).unwrap().unwrap().id,
21305                job.id
21306            );
21307            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21308            assert_eq!(
21309                crate::worker::helper_executable(&home).unwrap(),
21310                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21311            );
21312            assert!(
21313                crate::updater::Checker::new(&crate::config::Update {
21314                    mode: crate::config::UpdateMode::Notify,
21315                    interval: None,
21316                    auto_restart: false,
21317                })
21318                .is_none(),
21319                "the driver remains pinned, even while tests are standalone"
21320            );
21321        };
21322        assert_worker();
21323        let repo = home.join("repo");
21324        std::fs::create_dir_all(&repo).unwrap();
21325        init_repo(&repo);
21326        // Keep storage, seat/control context, containment and tool lookup.
21327        // No inherited values (or credentials) are printed on success.
21328        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21329            test -z "${MAGI_WORKER_GENERATION+x}" &&
21330            test -z "${MAGI_WORKER_HOME+x}" &&
21331            test -z "${MAGI_WORKER_EXE+x}" &&
21332            test "$MAGI_HOME/repo" -ef . &&
21333            test "$MAGI_RUN" = verification-parent &&
21334            test "$MAGI_NODE" = gate &&
21335            test "$MAGI_SEAT" = worker-fixture &&
21336            test -n "$MAGI_PROCESS_OWNER" &&
21337            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21338            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21339            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21340            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21341        // Negative control: an ordinary child inherits the contamination.
21342        assert!(
21343            !std::process::Command::new("sh")
21344                .args(["-c", probe])
21345                .current_dir(&repo)
21346                .status()
21347                .unwrap()
21348                .success()
21349        );
21350        let unrelated_home = tempfile::tempdir().unwrap();
21351        assert!(
21352            crate::worker::current_job(unrelated_home.path()).is_err(),
21353            "an inherited worker id cannot be resolved in a unit fixture's home"
21354        );
21355        let mut runner = runner_at(RunStatus::Gating);
21356        runner.state.repo = repo.clone();
21357        runner.state.config.disk.min_free_bytes = 0;
21358        runner.state.config.coordination = crate::config::test_coordination();
21359        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21360        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21361        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21362        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21363        let winner = Candidate {
21364            index: 0,
21365            label: 'A',
21366            agent: "fixture".into(),
21367            branch: "main".into(),
21368            worktree: repo.clone(),
21369            summary: String::new(),
21370            stat: String::new(),
21371            files: 0,
21372            commits: 0,
21373            empty: false,
21374            failed: None,
21375            verified_noop: None,
21376            duration_ms: 0,
21377            folded: false,
21378        };
21379        let (e2e, retried, pids) = run_e2e_with_retry(
21380            &mut runner.state,
21381            &["sh".into(), "-c".into()],
21382            &[format!("{probe} && printf initial")],
21383            &repo,
21384            Duration::from_secs(10),
21385            "initial",
21386            None,
21387        )
21388        .await;
21389        assert!(!retried && pids.is_empty());
21390        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21391        assert_eq!(e2e[0].output_tail, "initial");
21392        let gate = runner.run_gate(&winner).await.unwrap();
21393        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21394        // An interrupted repair must recheck e2e from saved state. Landing
21395        // reuses that state and must run both pre-gate and gate again.
21396        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
21397            head: git::rev_parse(&repo, "HEAD").await.unwrap(),
21398            passed: false,
21399            outcomes: Vec::new(),
21400        });
21401        runner.state.save().unwrap();
21402        let mut resumed = RunState::load(&runner.state.id).unwrap();
21403        let wait = crate::repo_lock::WaitPolicy::default();
21404        assert!(matches!(
21405            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21406                .await
21407                .unwrap(),
21408            GateFix::Retry
21409        ));
21410        let saved = RunState::load(&resumed.id).unwrap();
21411        let repair = saved.gate_repair_e2e.unwrap();
21412        assert!(repair.passed);
21413        assert_eq!(repair.outcomes.len(), 1);
21414        assert!(repair.outcomes[0].ok());
21415        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21416            .await
21417            .unwrap();
21418        assert_eq!(landing.len(), 1);
21419        assert!(landing[0].ok(), "{landing:?}");
21420        assert_eq!(
21421            std::fs::read_to_string(repo.join("phases")).unwrap(),
21422            "pre\ngate\ne2e\npre\ngate\n"
21423        );
21424        assert_worker();
21425    }
21426
21427    #[cfg(unix)]
21428    #[tokio::test]
21429    async fn verification_keeps_the_panic_and_the_full_output() {
21430        crate::run::pin_test_home();
21431        let tmp = tempfile::tempdir().unwrap();
21432        let mut config = Config::default();
21433        config.disk.min_free_bytes = 0;
21434        let mut state = RunState::new(
21435            tmp.path().to_owned(),
21436            "main".into(),
21437            "base".into(),
21438            "verification evidence".into(),
21439            config,
21440        );
21441        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21442                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21443                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21444        let mut names = Vec::new();
21445        for _ in 0..2 {
21446            let (outcomes, _) = run_commands(
21447                &mut state,
21448                "gate",
21449                "gate",
21450                0,
21451                &["sh".into(), "-c".into()],
21452                &[script.into()],
21453                tmp.path(),
21454                Duration::from_secs(60),
21455            )
21456            .await;
21457            let tail = &outcomes[0].output_tail;
21458            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21459            assert!(tail.contains("boom assertion"));
21460            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21461            let line = tail.lines().next().unwrap();
21462            names.push(line.to_owned());
21463        }
21464        assert_ne!(names[0], names[1], "the second run must not overwrite");
21465        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21466        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21467        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21468
21469        // Storage failures are evidence too; preserve the command's verdict.
21470        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21471        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21472        let (outcomes, _) = run_commands(
21473            &mut state,
21474            "gate",
21475            "gate",
21476            0,
21477            &["sh".into(), "-c".into()],
21478            &["echo failure-output; exit 7".into()],
21479            tmp.path(),
21480            Duration::from_secs(10),
21481        )
21482        .await;
21483        assert_eq!(outcomes[0].code, Some(7));
21484        assert!(state.events.iter().any(|e| {
21485            e.node == "gate" && e.message.contains("could not save the full gate output:")
21486        }));
21487    }
21488
21489    #[cfg(unix)]
21490    #[tokio::test]
21491    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21492        crate::run::pin_test_home();
21493        let tmp = tempfile::tempdir().unwrap();
21494        let mut config = Config::default();
21495        config.disk.min_free_bytes = 0;
21496        let mut state = RunState::new(
21497            tmp.path().to_owned(),
21498            "main".into(),
21499            "base".into(),
21500            "verification evidence".into(),
21501            config,
21502        );
21503        let (outcomes, pids) = run_commands(
21504            &mut state,
21505            "gate",
21506            "gate",
21507            1,
21508            &["sh".into(), "-c".into()],
21509            &[
21510                "printf before-timeout; exec sleep 30".into(),
21511                "kill -TERM $$".into(),
21512                "exit 7".into(),
21513                "printf success".into(),
21514            ],
21515            tmp.path(),
21516            Duration::from_secs(1),
21517        )
21518        .await;
21519        wait_for_timed_out_children_to_die(&pids).await;
21520        assert_eq!(
21521            pids.len(),
21522            1,
21523            "unleased timeout retains its death-check PID"
21524        );
21525        assert_eq!(outcomes.len(), 4);
21526        assert_eq!(outcomes[0].code, None);
21527        assert!(outcomes[0].output_tail.contains("before-timeout"));
21528        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21529        assert_eq!(outcomes[1].code, None);
21530        assert!(outcomes[1].output_tail.contains("command terminated:"));
21531        assert!(!outcomes[1].output_tail.contains("timed out"));
21532        assert_eq!(outcomes[2].code, Some(7));
21533        assert!(!outcomes[2].output_tail.contains("timed out"));
21534        assert_eq!(outcomes[3].code, Some(0));
21535        assert_eq!(outcomes[3].output_tail, "success");
21536        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21537    }
21538
21539    /// The addendum's second gap: a `verify.gate` command running for real
21540    /// wall-clock time had nothing at all to show for it in `active` before
21541    /// `run_commands` learned to record it — a run could sit in `Gating` for
21542    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21543    /// what was actually happening. Proven with a genuinely still-running
21544    /// command, not just a before/after check on the final state: a poller
21545    /// task reads the same `run.json` `gate()` is writing, the same way the
21546    /// phone or `magi show` would, while the shell command is still blocked
21547    /// on its own release marker.
21548    #[tokio::test]
21549    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21550        crate::run::pin_test_home();
21551
21552        let tmp = tempfile::tempdir().expect("tempdir");
21553        let repo = tmp.path().join("repo");
21554        std::fs::create_dir_all(&repo).unwrap();
21555        init_repo(&repo);
21556
21557        let mut config = Config::default();
21558        config.disk.min_free_bytes = 0;
21559        config.verify.gate = vec![
21560            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21561             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21562                .to_owned(),
21563        ];
21564
21565        let mut state = RunState::new(
21566            repo.clone(),
21567            "main".to_owned(),
21568            "deadbeef".to_owned(),
21569            "task".to_owned(),
21570            config,
21571        );
21572        let run_id = state.id.clone();
21573        state.candidates = vec![Candidate {
21574            index: 0,
21575            label: 'A',
21576            agent: "alpha".to_owned(),
21577            branch: "does-not-exist".to_owned(),
21578            worktree: repo.clone(),
21579            summary: String::new(),
21580            stat: String::new(),
21581            files: 0,
21582            commits: 0,
21583            empty: false,
21584            failed: None,
21585            verified_noop: None,
21586            duration_ms: 0,
21587            folded: false,
21588        }];
21589        state.tally = Some(Tally {
21590            first_choice: BTreeMap::from([('A', 1)]),
21591            borda: BTreeMap::new(),
21592            winner: 'A',
21593            rankings: 1,
21594            unanimous_initial: true,
21595            deliberated: false,
21596            changed_votes: 0,
21597            unanimous_final: true,
21598            tie_break: None,
21599            judges: 0,
21600            present: 0,
21601            quorum: 0,
21602            met_quorum: true,
21603            uncontested: Some("only candidate A produced a change".to_owned()),
21604        });
21605        state.reviews = vec![ReviewRound {
21606            round: 1,
21607            head: "deadbeef".to_owned(),
21608            verified_head: None,
21609            verified_at: None,
21610            reviews: Vec::new(),
21611            e2e: Vec::new(),
21612            fix: None,
21613            blocking: 0,
21614            answered: 0,
21615            expected: 0,
21616            clean: true,
21617            verify_retried: false,
21618            e2e_deferred: false,
21619            e2e_defer_reason: None,
21620            progressed: false,
21621            vote_split: false,
21622            reconsideration: Vec::new(),
21623            verdict: None,
21624        }];
21625
21626        let mut runner = Runner {
21627            state,
21628            roles: ResolvedRoles {
21629                implementers: Vec::new(),
21630                judges: Vec::new(),
21631                reviewers: Vec::new(),
21632                fixer: None,
21633                conductor: conductor(),
21634                implementer_roster: Vec::new(),
21635                judge_roster: Vec::new(),
21636                reviewer_roster: Vec::new(),
21637            },
21638            sem: Arc::new(Semaphore::new(1)),
21639            pause: Pause::new(),
21640            interrupt: Pause::new(),
21641        };
21642
21643        let started_marker = repo.join("started.marker");
21644        let release_marker = repo.join("release.marker");
21645        let observe = async {
21646            loop {
21647                if started_marker.exists()
21648                    && let Ok(s) = crate::run::RunState::load(&run_id)
21649                    && let Some(a) = s.active.get("gate")
21650                {
21651                    std::fs::write(&release_marker, b"go").expect("release marker");
21652                    break a.clone();
21653                }
21654                tokio::time::sleep(Duration::from_millis(50)).await;
21655            }
21656        };
21657        let captured = {
21658            let gate = runner.gate();
21659            tokio::pin!(gate);
21660            let captured = tokio::select! {
21661                observed = observe => observed,
21662                result = &mut gate => panic!(
21663                    "gate exited before its in-flight entry was observed: {result:?}"
21664                ),
21665            };
21666            gate.await.expect("gate");
21667            captured
21668        };
21669
21670        assert_eq!(captured.task.as_deref(), Some("gate"));
21671        assert_eq!(captured.node, "gate");
21672        assert_eq!(captured.index, Some(1));
21673        assert_eq!(captured.total, Some(1));
21674        assert!(
21675            captured
21676                .command
21677                .as_deref()
21678                .is_some_and(|c| c.contains("started.marker")),
21679            "{captured:?}"
21680        );
21681
21682        assert!(
21683            runner.state.active.is_empty(),
21684            "the entry must be cleared once the command actually finished: {:?}",
21685            runner.state.active
21686        );
21687        assert!(runner.state.gate_ran);
21688        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
21689    }
21690
21691    /// The hand-off over a blocking finding a reviewer rejected on leaves a
21692    /// record for `land`; one with only a Minor, or no reject, leaves none.
21693    #[tokio::test]
21694    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
21695        use crate::verdict::{Finding, ReviewVote, Severity};
21696        crate::run::pin_test_home();
21697        let tmp = tempfile::tempdir().expect("tempdir");
21698        let repo = tmp.path().join("repo");
21699        std::fs::create_dir_all(&repo).unwrap();
21700        init_repo(&repo);
21701
21702        for (severity, vote, expect) in [
21703            (Severity::Major, ReviewVote::Reject, true),
21704            (Severity::Minor, ReviewVote::Reject, false),
21705            (Severity::Major, ReviewVote::Approve, false),
21706        ] {
21707            let mut round = review_round(false, 1, 1, 1, false, true);
21708            round.reviews = vec![ReviewRecord {
21709                reviewer: 1,
21710                agent: "alpha".to_owned(),
21711                summary: String::new(),
21712                findings: vec![Finding {
21713                    id: "R1-1-1".to_owned(),
21714                    severity,
21715                    file: None,
21716                    line: None,
21717                    title: "t".to_owned(),
21718                    detail: String::new(),
21719                }],
21720                vote: Some(vote),
21721                failed: None,
21722                duration_ms: 0,
21723                attempts: 0,
21724            }];
21725            let mut state = RunState::new(
21726                repo.clone(),
21727                "main".to_owned(),
21728                "deadbeef".to_owned(),
21729                "task".to_owned(),
21730                Config::default(),
21731            );
21732            state.reviews = vec![round];
21733            let mut runner = Runner {
21734                state,
21735                roles: ResolvedRoles {
21736                    implementers: Vec::new(),
21737                    judges: Vec::new(),
21738                    reviewers: Vec::new(),
21739                    fixer: None,
21740                    conductor: conductor(),
21741                    implementer_roster: Vec::new(),
21742                    judge_roster: Vec::new(),
21743                    reviewer_roster: Vec::new(),
21744                },
21745                sem: Arc::new(Semaphore::new(1)),
21746                pause: Pause::new(),
21747                interrupt: Pause::new(),
21748            };
21749            let shell = runner.state.config.shell();
21750            runner
21751                .stop_reviewing("round budget spent", &shell, &repo)
21752                .await
21753                .expect("stop_reviewing");
21754            assert_eq!(runner.state.status, RunStatus::Gating);
21755            assert_eq!(
21756                runner.state.contested_handoff.is_some(),
21757                expect,
21758                "{severity:?} + {vote:?}"
21759            );
21760        }
21761    }
21762
21763    /// The shape the incident this whole fix responds to actually had: the
21764    /// round budget spent, the last round's own e2e blocked on the shared
21765    /// build cache (held here by a live pid — this test process — exactly
21766    /// `cache`'s own unit tests' pattern for "another owner, still alive"
21767    /// without forking a process). `stop_reviewing` must retry it — not
21768    /// silently leave the round looking untouched (the catch-up-only half of
21769    /// the bug), and not read the contention as a red `e2e` and block the
21770    /// run on it (the other half). Called directly, the same way
21771    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
21772    /// above exercises `gate`, so this never needs a real cargo build to
21773    /// reach: the lease is never released, so `with_cache_lease` never gets
21774    /// past acquiring it into anything that would need a real workspace.
21775    #[tokio::test]
21776    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
21777        crate::run::pin_test_home();
21778        let home = crate::run::home();
21779
21780        let tmp = tempfile::tempdir().expect("tempdir");
21781        let repo = tmp.path().join("repo");
21782        std::fs::create_dir_all(&repo).unwrap();
21783        init_repo(&repo);
21784        let head = crate::git::rev_parse(&repo, "HEAD")
21785            .await
21786            .expect("rev-parse");
21787        // Unique to this test, so holding its lease cannot collide with
21788        // another test sharing the same process-wide `home`.
21789        let cache_dir = tmp.path().join("target");
21790
21791        let mut config = Config::default();
21792        config.verify.e2e = vec![format!(
21793            "CARGO_TARGET_DIR='{}' test -f README.md",
21794            cache_dir.display()
21795        )];
21796        config.graph.review_rounds = 1;
21797        // Bounded so a regression that does start waiting fails the test in
21798        // seconds, not hangs it.
21799        config.graph.timeout_verify = Some(2);
21800        config.graph.timeout_resource_wait = 2;
21801
21802        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21803        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21804            .expect("no io error acquiring directly")
21805        {
21806            crate::cache::AcquireOutcome::Acquired(g) => g,
21807            crate::cache::AcquireOutcome::Busy(b) => {
21808                panic!("expected the direct acquire to win the lease first: {b:?}")
21809            }
21810        };
21811
21812        let mut state = RunState::new(
21813            repo.clone(),
21814            "main".to_owned(),
21815            head.clone(),
21816            "task".to_owned(),
21817            config,
21818        );
21819        state.candidates = vec![Candidate {
21820            index: 0,
21821            label: 'A',
21822            agent: "alpha".to_owned(),
21823            branch: "does-not-exist".to_owned(),
21824            worktree: repo.clone(),
21825            summary: String::new(),
21826            stat: String::new(),
21827            files: 0,
21828            commits: 0,
21829            empty: false,
21830            failed: None,
21831            verified_noop: None,
21832            duration_ms: 0,
21833            folded: false,
21834        }];
21835        state.tally = Some(Tally {
21836            first_choice: BTreeMap::from([('A', 1)]),
21837            borda: BTreeMap::new(),
21838            winner: 'A',
21839            rankings: 1,
21840            unanimous_initial: true,
21841            deliberated: false,
21842            changed_votes: 0,
21843            unanimous_final: true,
21844            tie_break: None,
21845            judges: 0,
21846            present: 0,
21847            quorum: 0,
21848            met_quorum: true,
21849            uncontested: Some("only candidate A produced a change".to_owned()),
21850        });
21851        // The round budget's last round, deferred: `needs_catchup_run`'s
21852        // other trigger. `stop_reviewing`'s retry machinery must treat this
21853        // exactly like a resource-blocked attempt once it actually runs.
21854        state.reviews = vec![ReviewRound {
21855            round: 1,
21856            head: head.clone(),
21857            verified_head: None,
21858            verified_at: None,
21859            reviews: Vec::new(),
21860            e2e: Vec::new(),
21861            fix: None,
21862            blocking: 1,
21863            answered: 1,
21864            expected: 1,
21865            clean: false,
21866            verify_retried: false,
21867            e2e_deferred: true,
21868            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
21869            progressed: false,
21870            vote_split: false,
21871            reconsideration: Vec::new(),
21872            verdict: None,
21873        }];
21874
21875        let mut runner = Runner {
21876            state,
21877            roles: ResolvedRoles {
21878                implementers: Vec::new(),
21879                judges: Vec::new(),
21880                reviewers: Vec::new(),
21881                fixer: None,
21882                conductor: conductor(),
21883                implementer_roster: Vec::new(),
21884                judge_roster: Vec::new(),
21885                reviewer_roster: Vec::new(),
21886            },
21887            sem: Arc::new(Semaphore::new(1)),
21888            pause: Pause::new(),
21889            interrupt: Pause::new(),
21890        };
21891
21892        let shell = runner.state.config.shell();
21893        runner
21894            .stop_reviewing("round budget spent", &shell, &repo)
21895            .await
21896            .expect("stop_reviewing");
21897
21898        let last = runner.state.reviews.last().expect("round record");
21899        assert_eq!(
21900            last.e2e_status(),
21901            E2eStatus::ResourceBlocked,
21902            "the shared cache is still held; the attempt must read as blocked, not deferred or \
21903             failed: {last:?}"
21904        );
21905        assert_eq!(
21906            last.verified_head.as_deref(),
21907            Some(head.as_str()),
21908            "which commit this attempt targeted is known even though nothing finished checking \
21909             it"
21910        );
21911        let first_attempt_at = last
21912            .verified_at
21913            .expect("when this attempt ran is known too");
21914        assert_ne!(
21915            runner.state.status,
21916            RunStatus::Blocked,
21917            "contention is evidence about the machine, not the patch — it must not settle the \
21918             run as blocked: {:?}",
21919            runner.state.status
21920        );
21921        assert!(
21922            !runner
21923                .state
21924                .events
21925                .iter()
21926                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
21927            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
21928            runner.state.events
21929        );
21930
21931        // The cache is still held: a later reentry must retry the same
21932        // round's verification again — not leave it looking exactly as
21933        // untouched as the first blocked attempt, which is indistinguishable
21934        // from never having tried again at all.
21935        runner
21936            .stop_reviewing("round budget spent", &shell, &repo)
21937            .await
21938            .expect("stop_reviewing retry");
21939        assert_eq!(
21940            runner.state.reviews.len(),
21941            1,
21942            "no new round was started: {:?}",
21943            runner.state.reviews
21944        );
21945        let last = runner.state.reviews.last().expect("round record");
21946        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
21947        assert!(
21948            last.verified_at.expect("still known") > first_attempt_at,
21949            "a second reentry must be a fresh attempt, not a stale copy of the first"
21950        );
21951        assert_ne!(runner.state.status, RunStatus::Blocked);
21952
21953        held.release();
21954    }
21955
21956    #[cfg(unix)]
21957    #[tokio::test]
21958    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
21959        ask_test_home();
21960        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
21961            let tmp = tempfile::tempdir().unwrap();
21962            let repo = tmp.path().join("repo");
21963            std::fs::create_dir(&repo).unwrap();
21964            init_repo(&repo);
21965            let run_git = |args: &[&str]| {
21966                let out = std::process::Command::new("git")
21967                    .args(args)
21968                    .current_dir(&repo)
21969                    .output()
21970                    .unwrap();
21971                assert!(
21972                    out.status.success(),
21973                    "{args:?}: {}",
21974                    String::from_utf8_lossy(&out.stderr)
21975                );
21976            };
21977            let origin = tmp.path().join("origin.git");
21978            run_git(&["init", "--bare", origin.to_str().unwrap()]);
21979            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
21980            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
21981            run_git(&["add", "spec.rs"]);
21982            run_git(&["commit", "-m", "initial spec"]);
21983            run_git(&["push", "origin", "main"]);
21984            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
21985            run_git(&["checkout", "-b", "fix/review"]);
21986            std::fs::write(
21987                repo.join("check.rs"),
21988                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
21989            )
21990            .unwrap();
21991            run_git(&["add", "check.rs"]);
21992            run_git(&["commit", "-m", "use spec"]);
21993            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
21994            run_git(&["checkout", "main"]);
21995            std::fs::write(
21996                repo.join("spec.rs"),
21997                "struct AgentSpec { max_turn_secs: u64 }\n",
21998            )
21999            .unwrap();
22000            run_git(&["add", "spec.rs"]);
22001            run_git(&["commit", "-m", "extend spec"]);
22002            run_git(&["push", "origin", "main"]);
22003            run_git(&["checkout", "fix/review"]);
22004
22005            let mut runner = runner_at(RunStatus::Reviewing);
22006            runner.state.repo = repo.clone();
22007            runner.state.base_commit = base;
22008            runner.state.pr_head = Some("fix/review".into());
22009            runner.state.config.graph.review_rounds = max_rounds;
22010            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22011            runner.state.config.graph.sessions = false;
22012            runner.state.config.disk.min_free_bytes = 0;
22013            runner.state.config.verify.e2e =
22014                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22015            runner.state.candidates = vec![Candidate {
22016                index: 0,
22017                label: 'A',
22018                agent: "fixture".into(),
22019                branch: "fix/review".into(),
22020                worktree: repo.clone(),
22021                summary: String::new(),
22022                stat: String::new(),
22023                files: 1,
22024                commits: 1,
22025                empty: false,
22026                failed: None,
22027                verified_noop: None,
22028                duration_ms: 0,
22029                folded: false,
22030            }];
22031            runner.state.tally = Some(Tally {
22032                first_choice: BTreeMap::new(),
22033                borda: BTreeMap::new(),
22034                winner: 'A',
22035                rankings: 0,
22036                unanimous_initial: true,
22037                deliberated: false,
22038                changed_votes: 0,
22039                unanimous_final: true,
22040                tie_break: None,
22041                judges: 0,
22042                present: 0,
22043                quorum: 0,
22044                met_quorum: true,
22045                uncontested: Some("review-only".into()),
22046            });
22047            let mut last = review_round(false, 0, 1, 1, false, false);
22048            last.head = reviewed.clone();
22049            last.e2e_deferred = true;
22050            last.e2e[0].resource_blocked = true;
22051            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22052            if max_rounds == 1 {
22053                last.e2e.clear();
22054            }
22055            runner.state.reviews = vec![last];
22056            let calls = tmp.path().join("fix-calls");
22057            let mut fixer = spec("repair");
22058            fixer
22059                .env
22060                .insert("FIX_CALLS".into(), calls.display().to_string());
22061            fixer.command = vec!["sh".into(), "-c".into(), r#"
22062                echo fix >> "$FIX_CALLS"
22063                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22064                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22065                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22066                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22067            "#.into()];
22068            let mut reviewer = spec("reviewer");
22069            reviewer.command = vec![
22070                "sh".into(),
22071                "-c".into(),
22072                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22073                    .into(),
22074            ];
22075            runner.roles.fixer = Some(vec![fixer]);
22076            runner.roles.reviewers = vec![reviewer];
22077
22078            runner.sync_to_base().await.unwrap();
22079            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22080            assert_ne!(rebased, reviewed);
22081            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22082            if reentry {
22083                // Simulate a crash after catch-up evidence was saved but before
22084                // dispatching the fixer. No dedicated pending-repair field exists.
22085                let shell = runner.state.config.shell();
22086                runner
22087                    .stop_unresolved_review("deferred verification", &shell, &repo)
22088                    .await
22089                    .unwrap();
22090                assert!(runner.catchup_repairable());
22091                assert!(!calls.exists());
22092                runner.state = RunState::load(&runner.state.id).unwrap();
22093                assert!(runner.catchup_repairable());
22094            }
22095            runner.review_loop().await.unwrap();
22096            let first = &runner.state.reviews[0];
22097            assert_eq!(first.head, reviewed);
22098            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22099            assert!(
22100                first.verify_retried,
22101                "a reproduced build failure gets exactly one retry: {:?}",
22102                first.e2e
22103            );
22104            assert!(first.e2e[0].output_tail.contains("E0063"));
22105            assert!(!runner.catchup_repairable());
22106            if max_rounds == 2 {
22107                assert_eq!(
22108                    runner.state.status,
22109                    RunStatus::Gating,
22110                    "{}",
22111                    crate::report::run(&runner.state)
22112                );
22113                assert_eq!(runner.state.reviews.len(), 2);
22114                assert!(first.fix.as_ref().unwrap().committed);
22115                assert!(runner.state.reviews[1].clean);
22116                assert_eq!(
22117                    runner
22118                        .state
22119                        .reviews
22120                        .iter()
22121                        .filter(|r| r.fix.is_some())
22122                        .count(),
22123                    1
22124                );
22125                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22126                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22127            } else {
22128                assert_eq!(runner.state.status, RunStatus::Blocked);
22129                assert!(first.fix.is_none());
22130                assert!(!calls.exists());
22131                let recovery = crate::recovery::assess(
22132                    "prior",
22133                    Some(&runner.state),
22134                    &runner.landing_base(),
22135                    crate::recovery::Relation::Diverged,
22136                );
22137                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22138                let reasons = recovery.reasons.join("\n");
22139                assert!(
22140                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22141                    "{reasons}"
22142                );
22143                assert!(
22144                    reasons.contains("base sync to")
22145                        && reasons.contains("additional review is required"),
22146                    "{reasons}"
22147                );
22148            }
22149        }
22150    }
22151
22152    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22153    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22154    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22155    /// own top-of-function fast path (`review_conclusion`) correctly reads
22156    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22157    /// own `for` range is empty once the round budget is spent, so
22158    /// `review_loop` must retry the check itself rather than silently doing
22159    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22160    /// above exercises directly, but through `review_loop`'s own entry point
22161    /// this time, proving the wiring between the two rather than just the
22162    /// retry logic in isolation.
22163    #[tokio::test]
22164    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22165        crate::run::pin_test_home();
22166        let home = crate::run::home();
22167
22168        let tmp = tempfile::tempdir().expect("tempdir");
22169        let repo = tmp.path().join("repo");
22170        std::fs::create_dir_all(&repo).unwrap();
22171        init_repo(&repo);
22172        let head = crate::git::rev_parse(&repo, "HEAD")
22173            .await
22174            .expect("rev-parse");
22175        let cache_dir = tmp.path().join("target");
22176
22177        let mut config = Config::default();
22178        config.verify.e2e = vec![format!(
22179            "CARGO_TARGET_DIR='{}' test -f README.md",
22180            cache_dir.display()
22181        )];
22182        config.graph.review_rounds = 1;
22183        config.graph.timeout_verify = Some(2);
22184        config.graph.timeout_resource_wait = 2;
22185
22186        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22187        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22188            .expect("no io error acquiring directly")
22189        {
22190            crate::cache::AcquireOutcome::Acquired(g) => g,
22191            crate::cache::AcquireOutcome::Busy(b) => {
22192                panic!("expected the direct acquire to win the lease first: {b:?}")
22193            }
22194        };
22195
22196        let mut state = RunState::new(
22197            repo.clone(),
22198            "main".to_owned(),
22199            head.clone(),
22200            "task".to_owned(),
22201            config,
22202        );
22203        state.candidates = vec![Candidate {
22204            index: 0,
22205            label: 'A',
22206            agent: "alpha".to_owned(),
22207            branch: "does-not-exist".to_owned(),
22208            worktree: repo.clone(),
22209            summary: String::new(),
22210            stat: String::new(),
22211            files: 0,
22212            commits: 0,
22213            empty: false,
22214            failed: None,
22215            verified_noop: None,
22216            duration_ms: 0,
22217            folded: false,
22218        }];
22219        state.tally = Some(Tally {
22220            first_choice: BTreeMap::from([('A', 1)]),
22221            borda: BTreeMap::new(),
22222            winner: 'A',
22223            rankings: 1,
22224            unanimous_initial: true,
22225            deliberated: false,
22226            changed_votes: 0,
22227            unanimous_final: true,
22228            tie_break: None,
22229            judges: 0,
22230            present: 0,
22231            quorum: 0,
22232            met_quorum: true,
22233            uncontested: Some("only candidate A produced a change".to_owned()),
22234        });
22235        // The exact shape a prior process's `stop_reviewing` would have left
22236        // on disk: the round budget's last round, a real attempt already
22237        // made and already resource-blocked.
22238        state.reviews = vec![ReviewRound {
22239            round: 1,
22240            head: head.clone(),
22241            verified_head: Some(head.clone()),
22242            verified_at: Some(jiff::Timestamp::now()),
22243            reviews: Vec::new(),
22244            e2e: vec![CommandOutcome {
22245                command: format!(
22246                    "CARGO_TARGET_DIR='{}' test -f README.md",
22247                    cache_dir.display()
22248                ),
22249                code: None,
22250                output_tail: "waiting for the shared build cache".to_owned(),
22251                duration_ms: 0,
22252                resource_blocked: true,
22253            }],
22254            fix: None,
22255            blocking: 1,
22256            answered: 1,
22257            expected: 1,
22258            clean: false,
22259            verify_retried: false,
22260            e2e_deferred: false,
22261            e2e_defer_reason: None,
22262            progressed: false,
22263            vote_split: false,
22264            reconsideration: Vec::new(),
22265            verdict: None,
22266        }];
22267
22268        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22269        let mut runner = Runner {
22270            state,
22271            roles: ResolvedRoles {
22272                implementers: Vec::new(),
22273                judges: Vec::new(),
22274                reviewers: Vec::new(),
22275                fixer: None,
22276                conductor: conductor(),
22277                implementer_roster: Vec::new(),
22278                judge_roster: Vec::new(),
22279                reviewer_roster: Vec::new(),
22280            },
22281            sem: Arc::new(Semaphore::new(1)),
22282            pause: Pause::new(),
22283            interrupt: Pause::new(),
22284        };
22285
22286        // The lease is still held throughout, so this reentry's own retry is
22287        // also contended — proving `review_loop` actually tried again (not
22288        // that it happened to succeed) is what the timestamp comparison
22289        // below is for.
22290        runner.review_loop().await.expect("review_loop");
22291
22292        assert_eq!(
22293            runner.state.reviews.len(),
22294            1,
22295            "no new round was started on top of the unresolved one: {:?}",
22296            runner.state.reviews
22297        );
22298        let last = &runner.state.reviews[0];
22299        assert_eq!(
22300            last.e2e_status(),
22301            E2eStatus::ResourceBlocked,
22302            "still contended: {last:?}"
22303        );
22304        assert!(
22305            last.verified_at.expect("still known") > first_attempt_at,
22306            "review_loop must have actually retried the check, not left it exactly as found"
22307        );
22308        assert_ne!(
22309            runner.state.status,
22310            RunStatus::Blocked,
22311            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22312            runner.state.status
22313        );
22314
22315        held.release();
22316    }
22317
22318    #[tokio::test]
22319    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22320        crate::run::pin_test_home();
22321        for status in [RunStatus::Blocked, RunStatus::Gating] {
22322            let mut runner = runner_at(status);
22323            runner.state.config.graph.land = true;
22324            runner.state.gate_ran = true;
22325            runner.state.merge = Some(MergeOutcome {
22326                mode: MergeMode::Pr,
22327                ok: false,
22328                detail: "the fixer produced no commit".into(),
22329                empty: false,
22330            });
22331            let url = "https://example.invalid/o/r/pull/1";
22332            runner.state.pr = Some(crate::run::PrRecord {
22333                url: url.into(),
22334                number: 1,
22335                state: "open".into(),
22336                checks: "red".into(),
22337                round: 1,
22338                rounds: 1,
22339                red_at_merge: Vec::new(),
22340            });
22341            runner.state.save().unwrap();
22342            // The nonexistent repository makes observation fail before a forge
22343            // command can run. We still must reach land, rather than silently
22344            // return from the graph with its old gate and merge records.
22345            runner.execute_graph().await.unwrap();
22346            assert_eq!(runner.state.status, RunStatus::Blocked);
22347            assert!(runner.state.land_sync_pending);
22348            assert!(runner.state.events.iter().any(|event|
22349                event.node == "land" && event.message == format!("watching {url}")));
22350            assert_eq!(
22351                runner.state.merge.as_ref().unwrap().detail,
22352                "the fixer produced no commit"
22353            );
22354        }
22355    }
22356
22357    #[tokio::test]
22358    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22359        crate::run::pin_test_home();
22360        let tmp = tempfile::tempdir().expect("tempdir");
22361        let repo = tmp.path().join("repo");
22362        std::fs::create_dir_all(&repo).unwrap();
22363        init_repo(&repo);
22364
22365        let mut config = Config::default();
22366        config.merge.mode = MergeMode::Pr;
22367        config.graph.land = true;
22368        config.graph.land_approval = false;
22369
22370        let mut state = RunState::new(
22371            repo.clone(),
22372            "main".to_owned(),
22373            "deadbeef".to_owned(),
22374            "task".to_owned(),
22375            config,
22376        );
22377        state.candidates = vec![Candidate {
22378            index: 0,
22379            label: 'A',
22380            agent: "alpha".to_owned(),
22381            branch: "does-not-exist".to_owned(),
22382            worktree: repo.clone(),
22383            summary: String::new(),
22384            stat: String::new(),
22385            files: 0,
22386            commits: 0,
22387            empty: false,
22388            failed: None,
22389            verified_noop: None,
22390            duration_ms: 0,
22391            folded: false,
22392        }];
22393        state.tally = Some(Tally {
22394            first_choice: BTreeMap::from([('A', 1)]),
22395            borda: BTreeMap::new(),
22396            winner: 'A',
22397            rankings: 1,
22398            unanimous_initial: true,
22399            deliberated: false,
22400            changed_votes: 0,
22401            unanimous_final: true,
22402            tie_break: None,
22403            judges: 0,
22404            present: 0,
22405            quorum: 0,
22406            met_quorum: true,
22407            uncontested: Some("only candidate A produced a change".to_owned()),
22408        });
22409        state.reviews = vec![ReviewRound {
22410            round: 1,
22411            head: "deadbeef".to_owned(),
22412            verified_head: None,
22413            verified_at: None,
22414            reviews: Vec::new(),
22415            e2e: Vec::new(),
22416            fix: None,
22417            blocking: 0,
22418            answered: 0,
22419            expected: 0,
22420            clean: true,
22421            verify_retried: false,
22422            e2e_deferred: false,
22423            e2e_defer_reason: None,
22424            progressed: false,
22425            vote_split: false,
22426            reconsideration: Vec::new(),
22427            verdict: None,
22428        }];
22429        state.gate = vec![CommandOutcome {
22430            command: "test".to_owned(),
22431            code: Some(0),
22432            output_tail: String::new(),
22433            duration_ms: 0,
22434            resource_blocked: false,
22435        }];
22436        state.gate_ran = true;
22437        // A first pass through `merge` already pushed and opened this pull
22438        // request; `status` is `Landing` because a previous call into `land`
22439        // parked or was interrupted before it reached a terminal outcome.
22440        state.status = RunStatus::Landing;
22441        state.merge = Some(MergeOutcome {
22442            mode: MergeMode::Pr,
22443            ok: true,
22444            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22445            empty: false,
22446        });
22447
22448        // The Landing-resume shortcut calls `run_land` directly rather than
22449        // through `merge`, which is exactly the call site that used to skip
22450        // `settle_questions` - see the fixture below.
22451        ask_test_home();
22452        // A real resume loads a persisted run; driver ownership is checked
22453        // against that record before the Landing shortcut is entered.
22454        state.save().expect("save landing run");
22455        let store = ask::Questions::open();
22456        let q = ask_open_question(&store, &state.id);
22457
22458        let mut runner = Runner {
22459            state,
22460            roles: ResolvedRoles {
22461                implementers: Vec::new(),
22462                judges: Vec::new(),
22463                reviewers: Vec::new(),
22464                fixer: None,
22465                conductor: conductor(),
22466                implementer_roster: Vec::new(),
22467                judge_roster: Vec::new(),
22468                reviewer_roster: Vec::new(),
22469            },
22470            sem: Arc::new(Semaphore::new(1)),
22471            pause: Pause::new(),
22472            interrupt: Pause::new(),
22473        };
22474
22475        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22476        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22477        // exactly because `review_loop` would otherwise clobber the marker
22478        // first.
22479        runner.execute().await.expect("execute");
22480
22481        assert_eq!(
22482            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22483            Some("https://example.invalid/x/y/pull/1"),
22484            "reentry must not push again or open a second pull request over the \
22485             one `land` is already watching"
22486        );
22487        assert_ne!(
22488            runner.state.status,
22489            RunStatus::Landing,
22490            "land could not actually reach the fake pull request, so it must \
22491             have given up rather than left the run silently parked forever"
22492        );
22493        // `land` could not reach the fake pull request, so it gave up into
22494        // `Blocked` - still resumable, so the question must not have been
22495        // swept just because this branch now also calls `settle_questions`.
22496        assert_eq!(runner.state.status, RunStatus::Blocked);
22497        assert!(
22498            store.get(&q.id).unwrap().status.open(),
22499            "Blocked is still alive; settle_questions must have been a no-op here"
22500        );
22501    }
22502
22503    fn state_with_round(round: ReviewRound) -> RunState {
22504        let mut s = RunState::new(
22505            PathBuf::from("/repo"),
22506            "main".to_owned(),
22507            "abc1234".to_owned(),
22508            "add retries".to_owned(),
22509            Config::default(),
22510        );
22511        s.reviews = vec![round];
22512        s
22513    }
22514
22515    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22516        crate::verdict::Finding {
22517            id: id.to_owned(),
22518            severity,
22519            file: None,
22520            line: None,
22521            title: title.to_owned(),
22522            detail: String::new(),
22523        }
22524    }
22525
22526    #[test]
22527    fn pr_body_names_open_findings_and_declined_ones() {
22528        let round = ReviewRound {
22529            round: 2,
22530            head: "deadbee".to_owned(),
22531            verified_head: None,
22532            verified_at: None,
22533            reviews: vec![ReviewRecord {
22534                attempts: 0,
22535                reviewer: 1,
22536                agent: "alpha".to_owned(),
22537                summary: String::new(),
22538                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22539                vote: None,
22540                failed: None,
22541                duration_ms: 0,
22542            }],
22543            e2e: vec![CommandOutcome {
22544                command: "cargo test".to_owned(),
22545                code: Some(0),
22546                output_tail: String::new(),
22547                duration_ms: 0,
22548                resource_blocked: false,
22549            }],
22550            verify_retried: false,
22551            e2e_deferred: false,
22552            e2e_defer_reason: None,
22553            fix: Some(FixRecord {
22554                agent: "alpha".to_owned(),
22555                addressed: Vec::new(),
22556                rejected: vec![crate::verdict::Rejection {
22557                    id: "R1-1-1".to_owned(),
22558                    why: "not reachable from any caller".to_owned(),
22559                }],
22560                notes: String::new(),
22561                committed: true,
22562                failed: None,
22563                duration_ms: 0,
22564                continuation: None,
22565            }),
22566            blocking: 0,
22567            answered: 1,
22568            expected: 1,
22569            clean: false,
22570            progressed: true,
22571            vote_split: false,
22572            reconsideration: Vec::new(),
22573            verdict: None,
22574        };
22575        let state = state_with_round(round);
22576        let body = pr_message(&state, 'A').body;
22577
22578        assert!(body.contains("add retries"), "the task must still be there");
22579        assert!(body.contains("R2-1-1"), "{body}");
22580        assert!(!body.contains("unused import"), "{body}");
22581        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22582        assert!(
22583            !body.contains("not reachable from any caller"),
22584            "the reason it was declined: {body}"
22585        );
22586    }
22587
22588    #[test]
22589    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22590        let round = ReviewRound {
22591            round: 1,
22592            head: "deadbee".to_owned(),
22593            verified_head: None,
22594            verified_at: None,
22595            reviews: vec![ReviewRecord {
22596                attempts: 0,
22597                reviewer: 1,
22598                agent: "alpha".to_owned(),
22599                summary: String::new(),
22600                findings: Vec::new(),
22601                vote: None,
22602                failed: None,
22603                duration_ms: 0,
22604            }],
22605            e2e: Vec::new(),
22606            verify_retried: false,
22607            e2e_deferred: false,
22608            e2e_defer_reason: None,
22609            fix: None,
22610            blocking: 0,
22611            answered: 1,
22612            expected: 1,
22613            clean: true,
22614            progressed: false,
22615            vote_split: false,
22616            reconsideration: Vec::new(),
22617            verdict: None,
22618        };
22619        let state = state_with_round(round);
22620        let body = pr_message(&state, 'A').body;
22621        assert!(!body.contains("Open review findings"), "{body}");
22622        assert!(!body.contains("Declined"), "{body}");
22623    }
22624
22625    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22626        let mut state = RunState::new(
22627            PathBuf::from("/repo"),
22628            "main".to_owned(),
22629            "abc1234".to_owned(),
22630            instruction.to_owned(),
22631            Config::default(),
22632        );
22633        // These fixtures test execution flow, independent of host disk capacity.
22634        state.config.disk.min_free_bytes = 0;
22635        state.candidates.push(Candidate {
22636            index: 0,
22637            label: 'A',
22638            agent: "alpha".to_owned(),
22639            branch: "magi/x/A".to_owned(),
22640            worktree: PathBuf::from("/wt"),
22641            summary: summary.to_owned(),
22642            stat: String::new(),
22643            files: 1,
22644            commits: 1,
22645            empty: false,
22646            failed: None,
22647            verified_noop: None,
22648            folded: false,
22649            duration_ms: 0,
22650        });
22651        state
22652    }
22653
22654    fn review_state(subjects: &[&str]) -> RunState {
22655        let mut state = state_with_summary(
22656            "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",
22657            "",
22658        );
22659        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
22660        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
22661        state
22662    }
22663
22664    /// A branch rebased onto a main that moved past the recorded
22665    /// `base_commit` is titled from its own first commit, never main's.
22666    #[tokio::test]
22667    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
22668        ask_test_home();
22669        let tmp = tempfile::tempdir().unwrap();
22670        let repo = tmp.path().join("repo");
22671        std::fs::create_dir_all(&repo).unwrap();
22672        init_repo(&repo);
22673        let origin = tmp.path().join("origin.git");
22674        let g = |dir: &Path, args: &[&str]| {
22675            let out = std::process::Command::new("git")
22676                .args(args)
22677                .current_dir(dir)
22678                .quiet()
22679                .output()
22680                .expect("spawn git");
22681            assert!(
22682                out.status.success(),
22683                "git {args:?}: {}",
22684                String::from_utf8_lossy(&out.stderr)
22685            );
22686        };
22687        g(
22688            tmp.path(),
22689            &[
22690                "clone",
22691                "--bare",
22692                "-q",
22693                repo.to_str().unwrap(),
22694                origin.to_str().unwrap(),
22695            ],
22696        );
22697        g(
22698            &repo,
22699            &["remote", "add", "origin", origin.to_str().unwrap()],
22700        );
22701        let c1 = git::rev_parse(&repo, "main").await.unwrap();
22702
22703        // Main moves on; the branch is built on top of the new main.
22704        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
22705        g(&repo, &["add", "-A"]);
22706        g(
22707            &repo,
22708            &["commit", "-q", "-m", "chore(deps): update a crate"],
22709        );
22710        g(&repo, &["push", "-q", "origin", "main"]);
22711        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
22712        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22713        g(&repo, &["add", "-A"]);
22714        g(
22715            &repo,
22716            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
22717        );
22718        g(&repo, &["checkout", "-q", "main"]);
22719
22720        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
22721        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
22722        // Without a readable tracking ref the recorded base's merge base is used.
22723        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
22724        assert_eq!(fallback, c1);
22725
22726        let mut state = review_state(&[
22727            "chore(deps): update a crate",
22728            "fix(daemon): apply a chosen action",
22729        ]);
22730        state.repo = repo.clone();
22731        state.base_branch = "main".to_owned();
22732        state.base_commit = c1;
22733        refresh_reviewed_commits(&mut state, "feat/own").await;
22734        assert_eq!(
22735            state.reviewed_commits,
22736            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
22737        );
22738        assert_eq!(
22739            review_title(&state).as_deref(),
22740            Some("fix(daemon): apply a chosen action")
22741        );
22742        assert_eq!(
22743            leaked_subjects(&state, "feat/own").await,
22744            Some(vec!["chore(deps): update a crate".to_owned()])
22745        );
22746        // A stale tracking ref is still used when the fetch fails, but the
22747        // leak list is withheld.
22748        state.config.merge.remote = "nowhere".to_owned();
22749        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
22750    }
22751
22752    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
22753    /// with `origin/main` one commit behind it, and a summarizing agent that
22754    /// prints whatever `reply` holds.
22755    struct SummaryFixture {
22756        _tmp: tempfile::TempDir,
22757        repo: PathBuf,
22758        reply: PathBuf,
22759        runner: Runner,
22760    }
22761
22762    fn summary_fixture() -> SummaryFixture {
22763        ask_test_home();
22764        let tmp = tempfile::tempdir().unwrap();
22765        let repo = tmp.path().join("repo");
22766        std::fs::create_dir_all(&repo).unwrap();
22767        init_repo(&repo);
22768        let origin = tmp.path().join("origin.git");
22769        let g = |args: &[&str]| {
22770            let out = std::process::Command::new("git")
22771                .args(args)
22772                .current_dir(&repo)
22773                .quiet()
22774                .output()
22775                .expect("spawn git");
22776            assert!(
22777                out.status.success(),
22778                "git {args:?}: {}",
22779                String::from_utf8_lossy(&out.stderr)
22780            );
22781        };
22782        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
22783        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
22784        g(&["push", "-q", "origin", "main"]);
22785        g(&["checkout", "-q", "-b", "feat/own"]);
22786        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22787        g(&["add", "-A"]);
22788        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
22789        let reply = tmp.path().join("reply.txt");
22790        std::fs::write(
22791            &reply,
22792            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
22793        )
22794        .unwrap();
22795        let mut runner = runner_at(RunStatus::Gating);
22796        let mut state = review_state(&["feat(own): add the own file"]);
22797        state.repo = repo.clone();
22798        state.base_branch = "main".to_owned();
22799        state.candidates[0].branch = "feat/own".to_owned();
22800        state.candidates[0].worktree = repo.clone();
22801        let mut author = spec("alpha");
22802        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
22803        author
22804            .env
22805            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
22806        state.config.agents = vec![author];
22807        runner.state = state;
22808        SummaryFixture {
22809            _tmp: tmp,
22810            repo,
22811            reply,
22812            runner,
22813        }
22814    }
22815
22816    async fn posted(f: &mut SummaryFixture) -> PrMessage {
22817        let winner = f.runner.state.candidates[0].clone();
22818        f.runner
22819            .guarded_pr_message(&winner, None, true)
22820            .await
22821            .unwrap()
22822            .expect("an English description never parks")
22823    }
22824
22825    fn clean_round_with_minor_findings() -> ReviewRound {
22826        let mut round = passing_round(2, None);
22827        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
22828        round.reviews = vec![ReviewRecord {
22829            attempts: 0,
22830            reviewer: 1,
22831            agent: "alpha".into(),
22832            summary: "内部レビュー".into(),
22833            findings: vec![
22834                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
22835                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
22836            ],
22837            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
22838            failed: None,
22839            duration_ms: 0,
22840        }];
22841        round
22842    }
22843
22844    #[tokio::test]
22845    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
22846        for review_only in [false, true] {
22847            let mut f = summary_fixture();
22848            if !review_only {
22849                f.runner.state.candidates[0].agent = "alpha".into();
22850            }
22851            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
22852            assert!(f.runner.state.reviews[0].clean);
22853            assert!(f.runner.state.reviews[0].fix.is_none());
22854            assert!(f.runner.state.open_findings().is_empty());
22855            assert_eq!(
22856                crate::pr_outcome::required_finding_ids(&f.runner.state),
22857                ["R2-1-1", "R2-1-2"]
22858            );
22859            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22860            let evidence = crate::pr_outcome::summary_evidence(
22861                &f.runner.state,
22862                crate::pr_outcome::FinalHead::At(&head),
22863            );
22864            assert!(
22865                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
22866            );
22867            // The ordinary reply omits both IDs: no cached description is adopted.
22868            let omitted = posted(&mut f).await;
22869            assert!(omitted.body.contains("No description"));
22870            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
22871            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
22872            assert!(f.runner.state.change_summary.is_none());
22873            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();
22874            let described = posted(&mut f).await;
22875            assert!(described.body.contains("improve documentation for callers"));
22876            assert!(described.body.contains("remaining edge case"));
22877            assert!(described.body.contains("## Open review findings"));
22878            assert!(!described.body.contains("未修正"));
22879        }
22880    }
22881
22882    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
22883        let mut f = summary_fixture();
22884        if !review_only {
22885            f.runner.state.candidates[0].agent = "alpha".into();
22886        }
22887        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22888        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
22889        fixed
22890            .fix
22891            .as_mut()
22892            .unwrap()
22893            .rejected
22894            .push(crate::verdict::Rejection {
22895                id: "R1-1-1".into(),
22896                why: "呼び出されないコードのため辞退".into(),
22897            });
22898        let mut clean = clean_round_with_minor_findings();
22899        clean.verified_head = Some(head.clone());
22900        f.runner.state.reviews = vec![fixed, clean];
22901        ok_gate(&mut f.runner.state, Some(&head));
22902        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
22903        f.runner.state.config.agents.push(scripted("beta", reply));
22904        f.runner.state.config.roles.language_judge =
22905            Some(crate::config::AgentChoice::One("beta".into()));
22906        f
22907    }
22908
22909    #[tokio::test]
22910    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
22911        for review_only in [false, true] {
22912            let mut f = rewrite_fixture_with_findings(review_only,
22913                "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;
22914            let m = posted(&mut f).await;
22915            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22916            let expected =
22917                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
22918            assert!(m.body.contains(&expected));
22919            assert!(m.body.contains("## Review rounds"));
22920            assert!(
22921                m.body
22922                    .contains("Gate (`verify.gate`): passed on the final commit")
22923            );
22924            assert!(
22925                m.body
22926                    .contains("Tests (`verify.e2e`): passed on the final commit")
22927            );
22928            let c = f.runner.state.change_summary.as_ref().unwrap();
22929            assert!(
22930                m.body
22931                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
22932            );
22933            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22934            assert!(crate::pr_outcome::covers_required_findings(
22935                &f.runner.state,
22936                &m.body
22937            ));
22938            assert!(m.body.contains("documentation remains incomplete"));
22939            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
22940            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
22941            assert!(f.runner.state.github_text.is_none());
22942        }
22943    }
22944
22945    #[tokio::test]
22946    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
22947        for review_only in [false, true] {
22948            for reply in [
22949                "TITLE: fix: public description\nA short English description.",
22950                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
22951            ] {
22952                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
22953                let winner = f.runner.state.candidates[0].clone();
22954                let posted = f
22955                    .runner
22956                    .guarded_pr_message(&winner, None, true)
22957                    .await
22958                    .unwrap();
22959                assert!(posted.is_none());
22960                assert!(f.runner.state.parked);
22961                let withheld = f.runner.state.github_text.as_ref().unwrap();
22962                assert!(
22963                    withheld.rewrite.is_none(),
22964                    "an incomplete rewrite must not be selectable"
22965                );
22966                let q = ask::Questions::open()
22967                    .get(withheld.question.as_ref().unwrap())
22968                    .unwrap();
22969                assert!(
22970                    !q.choices
22971                        .contains(&crate::github_text::USE_REWRITE.to_owned())
22972                );
22973                assert!(
22974                    q.detail.contains("R1-1-1")
22975                        && q.detail.contains("R2-1-1")
22976                        && q.detail.contains("R2-1-2")
22977                );
22978            }
22979        }
22980    }
22981
22982    #[tokio::test]
22983    async fn japanese_reports_stay_local_in_both_public_run_modes() {
22984        for review_only in [false, true] {
22985            let mut f = summary_fixture();
22986            if !review_only {
22987                f.runner.state.candidates[0].agent = "alpha".into();
22988            }
22989            f.runner.state.instruction = "内部タスクの説明".into();
22990            f.runner.state.candidates[0].summary = "内部の候補報告".into();
22991            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22992            f.runner.state.reviews = vec![
22993                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
22994                round_with_notes(2, Some("二回目の内部修正報告です。")),
22995                passing_round(3, Some(&head)),
22996            ];
22997            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
22998            ok_gate(&mut f.runner.state, Some(&head));
22999            let captured = f.repo.join("public-prompt.txt");
23000            let author = &mut f.runner.state.config.agents[0];
23001            author.command = vec![
23002                "sh".into(),
23003                "-c".into(),
23004                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23005            ];
23006            author.env.insert(
23007                "PROMPT_FILE".into(),
23008                captured.to_string_lossy().into_owned(),
23009            );
23010            let m = posted(&mut f).await;
23011            assert!(m.body.contains("Adds `own.txt`"));
23012            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23013            assert!(m.body.contains("R1-1-1"));
23014            assert!(
23015                m.body
23016                    .contains("Gate (`verify.gate`): passed on the final commit")
23017            );
23018            assert!(
23019                m.body
23020                    .contains("Tests (`verify.e2e`): passed on the final commit")
23021            );
23022            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23023            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23024            let prompt = std::fs::read_to_string(captured).unwrap();
23025            assert!(prompt.contains(&format!(
23026                "git diff {} {head}",
23027                f.runner.state.change_summary.as_ref().unwrap().base
23028            )));
23029            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23030            assert_eq!(
23031                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23032                "二回目の内部修正報告です。"
23033            );
23034        }
23035    }
23036
23037    #[tokio::test]
23038    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23039        for review_only in [false, true] {
23040            let mut f = summary_fixture();
23041            if !review_only {
23042                f.runner.state.candidates[0].agent = "alpha".into();
23043            }
23044            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23045            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23046            std::fs::write(&f.reply, "no usable description").unwrap();
23047            let failed = posted(&mut f).await;
23048            assert!(
23049                failed
23050                    .body
23051                    .contains("No description of what this change does could be generated")
23052            );
23053            assert!(failed.body.is_ascii());
23054            assert!(f.runner.state.github_text.is_none());
23055            assert!(f.runner.state.change_summary.is_none());
23056            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23057            let evidence = crate::pr_outcome::summary_evidence(
23058                &f.runner.state,
23059                crate::pr_outcome::FinalHead::At(&head),
23060            );
23061            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23062            assert!(
23063                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23064                    .exists()
23065            );
23066            f.runner.state =
23067                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23068            std::fs::write(
23069                &f.reply,
23070                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23071            )
23072            .unwrap();
23073            let retried = posted(&mut f).await;
23074            assert!(retried.body.contains("Adds the committed own file."));
23075            assert_eq!(
23076                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23077                "日本語の修正報告"
23078            );
23079        }
23080    }
23081
23082    #[tokio::test]
23083    async fn same_head_verification_and_findings_invalidate_public_prose() {
23084        let mut f = summary_fixture();
23085        posted(&mut f).await;
23086        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23087        let original = f
23088            .runner
23089            .state
23090            .change_summary
23091            .as_ref()
23092            .unwrap()
23093            .evidence
23094            .clone();
23095        ok_gate(&mut f.runner.state, Some(&head));
23096        std::fs::write(
23097            &f.reply,
23098            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23099        )
23100        .unwrap();
23101        let verified = posted(&mut f).await;
23102        assert!(verified.body.contains("now verified"));
23103        assert_ne!(
23104            f.runner.state.change_summary.as_ref().unwrap().evidence,
23105            original
23106        );
23107        let mut round = round_with_notes(1, Some("内部報告"));
23108        round.reviews.push(ReviewRecord {
23109            attempts: 0,
23110            reviewer: 1,
23111            agent: "alpha".into(),
23112            summary: "内部レビュー".into(),
23113            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23114            vote: None,
23115            failed: None,
23116            duration_ms: 0,
23117        });
23118        round
23119            .fix
23120            .as_mut()
23121            .unwrap()
23122            .rejected
23123            .push(crate::verdict::Rejection {
23124                id: "R1-1-1".into(),
23125                why: "呼び出し元から到達できない".into(),
23126            });
23127        f.runner.state.reviews = vec![round];
23128        // A description omitting the required ID is unusable, even with a title.
23129        let omitted = posted(&mut f).await;
23130        assert!(omitted.body.contains("No description"));
23131        assert!(omitted.body.contains("R1-1-1"));
23132        assert!(!omitted.body.contains("到達"));
23133        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();
23134        let described = posted(&mut f).await;
23135        assert!(described.body.contains("unreachable from callers"));
23136        assert!(described.body.contains("R1-1-1"));
23137        assert!(!described.body.contains("到達"));
23138        let evidence = f
23139            .runner
23140            .state
23141            .change_summary
23142            .as_ref()
23143            .unwrap()
23144            .evidence
23145            .clone();
23146        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23147        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23148        assert!(posted(&mut f).await.body.contains("rationale updated"));
23149        assert_ne!(
23150            f.runner.state.change_summary.as_ref().unwrap().evidence,
23151            evidence
23152        );
23153        // Old serialized summaries have no evidence fingerprint and must regenerate.
23154        f.runner
23155            .state
23156            .change_summary
23157            .as_mut()
23158            .unwrap()
23159            .evidence
23160            .clear();
23161        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23162        assert!(posted(&mut f).await.body.contains("current specification"));
23163    }
23164
23165    #[tokio::test]
23166    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23167        let mut f = summary_fixture();
23168        let m = posted(&mut f).await;
23169        assert_eq!(m.title, "feat(own): add the own file");
23170        assert!(
23171            m.body
23172                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23173            "{}",
23174            m.body
23175        );
23176        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23177        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23178        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23179        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23180        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23181        let kept = f.runner.state.change_summary.as_ref().unwrap();
23182        assert_eq!(
23183            (kept.head.as_str(), kept.base.as_str()),
23184            (head.as_str(), base.as_str())
23185        );
23186        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23187    }
23188
23189    #[tokio::test]
23190    async fn review_only_summary_receives_the_configured_github_language() {
23191        let mut f = summary_fixture();
23192        f.runner.state.config.graph.github_language = "ja".into();
23193        let captured = f.repo.join("summary-prompt.txt");
23194        let author = &mut f.runner.state.config.agents[0];
23195        author.command = vec![
23196            "sh".into(),
23197            "-c".into(),
23198            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23199        ];
23200        author.env.insert(
23201            "PROMPT_FILE".into(),
23202            captured.to_string_lossy().into_owned(),
23203        );
23204        std::fs::write(
23205            &f.reply,
23206            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23207        )
23208        .unwrap();
23209        let m = posted(&mut f).await;
23210        let prompt = std::fs::read_to_string(captured).unwrap();
23211        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23212        assert!(!prompt.contains("in English"));
23213        assert_eq!(m.title, "feat(own): ファイルを追加");
23214        assert!(m.body.contains("own.txt を追加します。"));
23215    }
23216
23217    #[tokio::test]
23218    async fn review_fixes_come_after_the_whole_change_summary() {
23219        let mut f = summary_fixture();
23220        f.runner.state.reviews = vec![
23221            round_with_notes(1, Some("handled the PATH case")),
23222            round_with_notes(2, None),
23223        ];
23224        let m = posted(&mut f).await;
23225        let summary = m.body.find("## Summary").expect("summary");
23226        let fixes = m.body.find("## Review rounds").expect("review rounds");
23227        assert!(summary < fixes, "{}", m.body);
23228        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23229        assert!(m.body.contains("## Final verification"), "{}", m.body);
23230    }
23231
23232    #[tokio::test]
23233    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23234        let mut f = summary_fixture();
23235        let first = posted(&mut f).await;
23236        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23237        // The same head reuses the record: a different reply is not read.
23238        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23239        let again = posted(&mut f).await;
23240        assert_eq!((again.title, again.body), (first.title, first.body));
23241
23242        let g = |args: &[&str]| {
23243            let out = std::process::Command::new("git")
23244                .args(args)
23245                .current_dir(&f.repo)
23246                .quiet()
23247                .output()
23248                .expect("spawn git");
23249            assert!(out.status.success(), "git {args:?}");
23250        };
23251        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23252        g(&["add", "-A"]);
23253        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23254        let second = posted(&mut f).await;
23255        let kept = f.runner.state.change_summary.clone().unwrap();
23256        assert_ne!(kept.head, first_head);
23257        assert!(second.body.contains("Not read yet."), "{}", second.body);
23258        assert!(!second.body.contains("so the first summary is read"));
23259        assert_eq!(second.title, "feat(own): other");
23260    }
23261
23262    #[tokio::test]
23263    async fn an_unavailable_summary_is_stated_and_never_invented() {
23264        let mut f = summary_fixture();
23265        std::fs::write(&f.reply, "no title line here").unwrap();
23266        let m = posted(&mut f).await;
23267        assert!(
23268            m.body
23269                .contains("No description of what this change does could be generated"),
23270            "{}",
23271            m.body
23272        );
23273        assert!(m.body.contains("internal reports remain in local records"));
23274        assert!(f.runner.state.change_summary.is_none());
23275        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23276        // A preview asks nobody and claims nothing.
23277        let winner = f.runner.state.candidates[0].clone();
23278        let preview = f
23279            .runner
23280            .guarded_pr_message(&winner, None, false)
23281            .await
23282            .unwrap()
23283            .unwrap();
23284        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23285    }
23286
23287    #[test]
23288    fn pr_message_review_single_commit_uses_its_subject() {
23289        let state = review_state(&["feat(nats): per-role user"]);
23290        let m = pr_message(&state, 'A');
23291        assert_eq!(m.title, "feat(nats): per-role user");
23292        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23293        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23294    }
23295
23296    #[test]
23297    fn pr_message_review_multi_commit_takes_the_oldest() {
23298        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23299        let m = pr_message(&state, 'A');
23300        assert_eq!(m.title, "feat: the change");
23301        for s in ["feat: the change", "fix: typo", "fix: again"] {
23302            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23303        }
23304    }
23305
23306    #[test]
23307    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23308        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23309            let mut state = review_state(&[first, "fix: later fixup"]);
23310            state.candidates[0].branch = "機能/ログイン".to_owned();
23311            let m = pr_message(&state, 'A');
23312            assert!(
23313                m.title.starts_with("chore: land candidate A of run"),
23314                "{}",
23315                m.title
23316            );
23317        }
23318    }
23319
23320    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23321        BranchFacts {
23322            commits: commits
23323                .iter()
23324                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23325                .collect(),
23326            stat: stat.to_owned(),
23327        }
23328    }
23329
23330    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23331        let mut r = review_round(true, 0, 1, 1, true, true);
23332        r.round = round;
23333        r.fix = notes.map(|n| FixRecord {
23334            agent: "fixer".to_owned(),
23335            addressed: Vec::new(),
23336            rejected: Vec::new(),
23337            notes: n.to_owned(),
23338            committed: true,
23339            failed: None,
23340            duration_ms: 0,
23341            continuation: None,
23342        });
23343        r
23344    }
23345
23346    #[test]
23347    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23348        let state = review_state(&["ignored"]);
23349        let f = facts(
23350            &[
23351                (
23352                    "fix(login): resolve PATH on macOS",
23353                    "Login shells skip rc files.",
23354                ),
23355                ("fix: address review", ""),
23356            ],
23357            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23358        );
23359        let m = pr_message_with(&state, 'A', Some(&f));
23360        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23361        assert!(
23362            m.body
23363                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23364            "{}",
23365            m.body
23366        );
23367        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23368        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23369        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23370        for banned in [
23371            "Review the work already",
23372            "no task statement",
23373            "Original task",
23374        ] {
23375            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23376        }
23377        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23378    }
23379
23380    #[test]
23381    fn pr_message_review_truncates_a_huge_first_commit_body() {
23382        let state = review_state(&["ignored"]);
23383        let f = facts(
23384            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23385            "s",
23386        );
23387        let m = pr_message_with(&state, 'A', Some(&f));
23388        assert!(m.body.len() < 30_000, "{}", m.body.len());
23389        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23390        assert!(
23391            m.body.contains("- ... 1 more commit(s)"),
23392            "{}",
23393            m.body.len()
23394        );
23395        assert!(m.body.ends_with("magi:candidate-a\n"));
23396    }
23397
23398    #[test]
23399    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23400        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23401        assert_eq!(m.title, "feat: x");
23402        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23403        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23404        assert!(!m.body.contains("no task statement"), "{}", m.body);
23405    }
23406
23407    #[test]
23408    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23409        let mut state = review_state(&["日本語の件名"]);
23410        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23411        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23412        state.candidates[0].branch = "機能/ログイン".to_owned();
23413        assert!(
23414            pr_message(&state, 'A')
23415                .title
23416                .starts_with("chore: land candidate A")
23417        );
23418    }
23419
23420    #[test]
23421    fn pr_message_review_fixes_survive_a_clean_final_round() {
23422        let mut state = review_state(&["feat: x"]);
23423        state.reviews = vec![
23424            round_with_notes(1, Some("handled the PATH case")),
23425            round_with_notes(2, None),
23426        ];
23427        let body = pr_message(&state, 'A').body;
23428        assert!(
23429            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23430            "{body}"
23431        );
23432        assert!(body.contains("### Round 1"), "{body}");
23433
23434        state.reviews = vec![
23435            round_with_notes(1, Some("first fix")),
23436            round_with_notes(2, Some("")),
23437            round_with_notes(3, Some("second fix")),
23438            round_with_notes(4, None),
23439        ];
23440        let body = pr_message(&state, 'A').body;
23441        assert!(
23442            body.contains("### Round 1") && !body.contains("first fix"),
23443            "{body}"
23444        );
23445        assert!(
23446            body.contains("### Round 3") && !body.contains("second fix"),
23447            "{body}"
23448        );
23449        assert!(body.contains("### Round 2"), "{body}");
23450    }
23451
23452    const FINAL: &str = "abcdef1234567890";
23453
23454    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23455        let mut r = round_with_notes(round, None);
23456        r.verified_head = verified.map(str::to_owned);
23457        r
23458    }
23459
23460    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23461        state.gate = vec![CommandOutcome {
23462            command: "gate".to_owned(),
23463            code: Some(0),
23464            output_tail: String::new(),
23465            duration_ms: 0,
23466            resource_blocked: false,
23467        }];
23468        state.gate_ran = true;
23469        state.gate_head = head.map(str::to_owned);
23470    }
23471
23472    fn body_at(state: &RunState) -> String {
23473        pr_message_raw(
23474            state,
23475            'A',
23476            None,
23477            crate::pr_outcome::FinalHead::At(FINAL),
23478            ChangeNote::NotAsked,
23479        )
23480        .body
23481    }
23482
23483    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23484
23485    #[test]
23486    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23487        let mut state = review_state(&["feat: x"]);
23488        state.reviews = vec![
23489            round_with_notes(1, Some(SANDBOXED)),
23490            passing_round(2, Some(FINAL)),
23491        ];
23492        ok_gate(&mut state, Some(FINAL));
23493        let body = body_at(&state);
23494        assert!(!body.contains("Handled the PATH case."), "{body}");
23495        assert!(!body.contains("could not commit"), "{body}");
23496        assert!(!body.contains("could not run"), "{body}");
23497        assert!(
23498            body.contains("The fix is committed on the branch"),
23499            "{body}"
23500        );
23501        assert!(!body.contains("sandbox"), "{body}");
23502        assert!(
23503            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23504            "{body}"
23505        );
23506        assert!(
23507            body.contains("Gate (`verify.gate`): passed on the final commit"),
23508            "{body}"
23509        );
23510        // The raw report is untouched in the record.
23511        assert!(
23512            state.reviews[0]
23513                .fix
23514                .as_ref()
23515                .unwrap()
23516                .notes
23517                .contains("could not commit")
23518        );
23519    }
23520
23521    #[test]
23522    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23523        let mut state = review_state(&["feat: x"]);
23524        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23525        r1.fix.as_mut().unwrap().committed = false;
23526        let mut r2 = passing_round(2, Some(FINAL));
23527        r2.e2e[0].code = Some(1);
23528        state.reviews = vec![r1, r2];
23529        let body = body_at(&state);
23530        assert!(!body.contains("could not commit"), "{body}");
23531        assert!(!body.contains("could not run"), "{body}");
23532        assert!(body.contains("This round produced no commit"), "{body}");
23533        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23534        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23535        assert!(!body.contains("passed"), "{body}");
23536    }
23537
23538    #[test]
23539    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23540        let mut state = review_state(&["feat: x"]);
23541        state.reviews = vec![
23542            round_with_notes(1, Some(SANDBOXED)),
23543            passing_round(2, Some("0123456789abcdef")),
23544        ];
23545        ok_gate(&mut state, Some("0123456789abcdef"));
23546        let body = body_at(&state);
23547        assert!(!body.contains("HTTP tests could not run"), "{body}");
23548        // The commit claim is still settled by the structured record.
23549        assert!(!body.contains("could not commit"), "{body}");
23550        assert!(
23551            body.contains("passed on an earlier commit (`0123456`)"),
23552            "{body}"
23553        );
23554        assert!(!body.contains("passed on the final commit"), "{body}");
23555
23556        // A gate recorded before `gate_head` existed is "not recorded".
23557        ok_gate(&mut state, None);
23558        let body = body_at(&state);
23559        assert!(
23560            body.contains("passed on a commit that was not recorded"),
23561            "{body}"
23562        );
23563    }
23564
23565    #[test]
23566    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23567        let state = state_with_summary(
23568            "add retries to the client",
23569            "TITLE: feat: retries\n\nDid it.",
23570        );
23571        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23572        assert_eq!(m.title, "feat: retries");
23573        assert!(
23574            m.body.contains("<summary>Original task</summary>"),
23575            "{}",
23576            m.body
23577        );
23578        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23579        assert!(
23580            m.body
23581                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23582            "{}",
23583            m.body
23584        );
23585    }
23586
23587    #[test]
23588    fn pr_message_review_bounds_a_long_english_subject() {
23589        let long = format!("feat: {}", "word ".repeat(100));
23590        let m = pr_message(&review_state(&[&long]), 'A');
23591        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23592        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23593    }
23594
23595    #[test]
23596    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23597        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23598        let m = pr_message(&state, 'A');
23599        assert_eq!(m.title, "add retries");
23600        assert!(m.body.contains("<summary>Original task</summary>"));
23601        assert!(!m.body.contains("Commits under review"));
23602        assert_eq!(landing_subject_source(&state), state.instruction);
23603    }
23604
23605    #[test]
23606    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23607        let state = review_state(&["feat: the change", "fix: typo"]);
23608        let source = landing_subject_source(&state);
23609        assert_eq!(land::merge_subject("", &source), "feat: the change");
23610        assert_eq!(
23611            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23612            "feat: the change"
23613        );
23614        // An operator's rename still wins.
23615        assert_eq!(
23616            land::merge_subject("feat: renamed by hand", &source),
23617            "feat: renamed by hand"
23618        );
23619        let blank = review_state(&["日本語"]);
23620        assert!(
23621            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23622        );
23623    }
23624
23625    #[test]
23626    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23627        let state = review_state(&["feat: the change"]);
23628        let source = landing_subject_source(&state);
23629        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23630        assert_eq!(
23631            land::merge_subject(landing_title(&state, old), &source),
23632            "feat: the change"
23633        );
23634        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23635        let task = state_with_summary("add retries", "");
23636        assert_eq!(landing_title(&task, old), old);
23637    }
23638
23639    #[test]
23640    fn pr_message_describes_the_change_not_the_task() {
23641        let state = state_with_summary(
23642            "今回やってほしいこと: results projector を直す",
23643            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23644        );
23645        let m = pr_message(&state, 'A');
23646        assert_eq!(m.title, "fix(web): batch the runs list reads");
23647        assert!(
23648            m.body.starts_with("## Summary\n\n- reads run.json once"),
23649            "{}",
23650            m.body
23651        );
23652        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23653        let task_at = m.body.find("今回やってほしいこと").unwrap();
23654        let details_at = m.body.find("<details>").unwrap();
23655        assert!(
23656            details_at < task_at,
23657            "the task lives inside <details>: {}",
23658            m.body
23659        );
23660        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
23661        assert!(m.body.contains("magi:candidate-a"));
23662    }
23663
23664    #[test]
23665    fn pr_message_falls_back_to_the_task_without_a_title_line() {
23666        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
23667        let m = pr_message(&state, 'A');
23668        assert_eq!(m.title, "add retries");
23669        assert!(
23670            m.body.contains("## Summary\n\n- did some things"),
23671            "{}",
23672            m.body
23673        );
23674
23675        let none = RunState::new(
23676            PathBuf::from("/repo"),
23677            "main".to_owned(),
23678            "abc1234".to_owned(),
23679            "add retries".to_owned(),
23680            Config::default(),
23681        );
23682        let m = pr_message(&none, 'A');
23683        assert_eq!(m.title, "add retries");
23684        assert!(!m.body.contains("## Summary"), "{}", m.body);
23685    }
23686
23687    #[test]
23688    fn pr_message_refuses_the_candidate_commit_subject() {
23689        for bad in [
23690            "TITLE: magi: candidate A (uncommitted work)",
23691            "TITLE: chore: stuff (uncommitted work)",
23692            "TITLE:   ",
23693        ] {
23694            let state = state_with_summary("add retries", bad);
23695            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
23696        }
23697    }
23698
23699    #[test]
23700    fn pr_message_bounds_a_very_long_task_and_title() {
23701        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
23702        let state = state_with_summary(&long, "- nothing");
23703        let m = pr_message(&state, 'A');
23704        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23705        assert!(!m.title.contains('\n'));
23706
23707        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
23708        let m = pr_message(&state, 'A');
23709        assert!(m.title.starts_with("feat: "));
23710        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23711        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
23712    }
23713
23714    fn long_title_of(instruction: &str) -> String {
23715        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
23716    }
23717
23718    #[test]
23719    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
23720        let first = "Make the landing path keep a readable title for long tasks";
23721        let line = format!(
23722            "{first}. {}",
23723            "And then keep going with more words ".repeat(20)
23724        );
23725        let t = long_title_of(&line);
23726        assert_eq!(t, first);
23727        assert!(!t.starts_with("chore: land"));
23728    }
23729
23730    #[test]
23731    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
23732        let line = "word ".repeat(200);
23733        let t = long_title_of(&line);
23734        assert!(t.ends_with("word..."), "{t}");
23735        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
23736    }
23737
23738    #[test]
23739    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
23740        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
23741            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
23742        }
23743    }
23744
23745    #[test]
23746    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
23747        let mut state = state_with_summary("再試行を追加する", "- nothing");
23748        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
23749        state.config.graph.github_language = "ja".into();
23750        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
23751    }
23752
23753    #[test]
23754    fn pr_message_title_limit_is_exact() {
23755        let at = "a".repeat(PR_TITLE_MAX);
23756        assert_eq!(long_title_of(&at), at);
23757        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
23758        assert!(over.ends_with("..."), "{over}");
23759        assert_eq!(over.chars().count(), PR_TITLE_MAX);
23760    }
23761
23762    #[test]
23763    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
23764        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
23765        let t = long_title_of(&line);
23766        assert!(t.ends_with("..."), "{t}");
23767        assert!(t.is_ascii(), "{t}");
23768    }
23769
23770    #[test]
23771    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
23772        let line = format!(
23773            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
23774            "plus more filler words ".repeat(20)
23775        );
23776        let t = long_title_of(&line);
23777        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
23778    }
23779
23780    #[test]
23781    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
23782        let line = format!("\n\n# {}", "title words ".repeat(40));
23783        let state = state_with_summary(&line, "- nothing");
23784        let m = pr_message(&state, 'A');
23785        assert!(m.title.starts_with("title words"), "{}", m.title);
23786        assert_eq!(
23787            land::merge_subject(&m.title, &landing_subject_source(&state)),
23788            m.title
23789        );
23790        // An operator's rename wins untouched.
23791        assert_eq!(
23792            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
23793            "feat: renamed by hand"
23794        );
23795    }
23796
23797    #[tokio::test]
23798    async fn github_text_rewrite_is_bounded_and_falls_back() {
23799        crate::run::pin_test_home();
23800        for (reply, accepted) in [
23801            (
23802                "TITLE: fix: retries\nAdd retries for failed requests.",
23803                true,
23804            ),
23805            (
23806                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
23807                false,
23808            ),
23809            (
23810                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
23811                true,
23812            ),
23813            (
23814                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
23815                true,
23816            ),
23817            (
23818                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
23819                true,
23820            ),
23821            (
23822                "TITLE: fix: retries\n日本語の説明です。 token=secret",
23823                false,
23824            ),
23825            ("TITLE: fix: retries\n", false),
23826        ] {
23827            let dir = tempfile::tempdir().unwrap();
23828            let mut runner = runner_at(RunStatus::Gating);
23829            runner.state = state_with_summary(
23830                "add retries",
23831                "TITLE: fix: retries\n日本語の説明を書きます。",
23832            );
23833            runner.state.repo = dir.path().to_owned();
23834            runner.state.candidates[0].worktree = dir.path().to_owned();
23835            let mut author = spec("alpha");
23836            author.command = vec![
23837                "sh".into(),
23838                "-c".into(),
23839                "printf '%s' \"$REWRITE_REPLY\"".into(),
23840            ];
23841            author.env.insert("REWRITE_REPLY".into(), reply.into());
23842            runner.state.config.agents = vec![author];
23843            seed_public_summary(&mut runner);
23844            let winner = runner.state.candidates[0].clone();
23845            let first = runner
23846                .guarded_pr_message(&winner, None, true)
23847                .await
23848                .unwrap();
23849            let message = if accepted {
23850                first.expect("a passing rewrite never asks")
23851            } else {
23852                // Withheld: the run parks on a question and posts nothing yet.
23853                assert!(first.is_none());
23854                assert!(runner.state.parked);
23855                let store = ask::Questions::open();
23856                let asked: Vec<_> = store
23857                    .list()
23858                    .into_iter()
23859                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23860                    .collect();
23861                assert_eq!(asked.len(), 1);
23862                assert!(!asked[0].detail.contains("secret"));
23863                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
23864                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
23865                assert_eq!(
23866                    asked[0]
23867                        .choices
23868                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
23869                    rewrite.is_some()
23870                );
23871                // Silence: the question lapses and the neutral text is used,
23872                // without a second rewrite call or a second question.
23873                store
23874                    .update(&asked[0].id, |q| {
23875                        q.abandon("test");
23876                        Ok(())
23877                    })
23878                    .unwrap();
23879                let again = runner
23880                    .guarded_pr_message(&winner, None, true)
23881                    .await
23882                    .unwrap()
23883                    .expect("an abandoned question falls back");
23884                let n = store
23885                    .list()
23886                    .into_iter()
23887                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23888                    .count();
23889                assert_eq!(n, 1, "asked once per rejected text");
23890                again
23891            };
23892            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
23893            assert!(!message.body.contains("secret"));
23894            assert!(!message.body.contains("prefix"));
23895            assert!(!message.title.contains("secret"));
23896            assert_eq!(
23897                message.body.contains("Add retries for failed requests."),
23898                accepted
23899            );
23900            assert_eq!(
23901                runner.state.seats["github-text-rewrite"].turns, 1,
23902                "only one rewrite invocation"
23903            );
23904            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
23905            if accepted {
23906                assert!(runner.state.github_text.is_none());
23907                assert!(!runner.state.parked);
23908                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
23909                assert!(message.body.contains("## Final verification"));
23910                assert!(message.body.contains("Evidence: final diff"));
23911                assert!(
23912                    message
23913                        .body
23914                        .contains(&format!("magi:run/{}", runner.state.id))
23915                );
23916            }
23917            if !accepted {
23918                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
23919                assert!(
23920                    message
23921                        .body
23922                        .contains(&format!("magi:run/{}", runner.state.id))
23923                );
23924            }
23925        }
23926    }
23927
23928    fn scripted(id: &str, reply: &str) -> AgentSpec {
23929        let mut a = spec(id);
23930        a.command = vec![
23931            "sh".into(),
23932            "-c".into(),
23933            "printf '%s' \"$REWRITE_REPLY\"".into(),
23934        ];
23935        a.env.insert("REWRITE_REPLY".into(), reply.into());
23936        a
23937    }
23938
23939    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
23940    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
23941
23942    /// Gate tests inject generated public output, not internal reports.
23943    fn seed_public_summary(runner: &mut Runner) {
23944        let repo = &runner.state.repo;
23945        let g = |args: &[&str]| {
23946            let out = std::process::Command::new("git")
23947                .args(args)
23948                .current_dir(repo)
23949                .quiet()
23950                .output()
23951                .unwrap();
23952            assert!(out.status.success(), "git {args:?}");
23953            String::from_utf8_lossy(&out.stdout).trim().to_owned()
23954        };
23955        g(&["init", "-q", "-b", "main"]);
23956        g(&[
23957            "-c",
23958            "user.name=Test",
23959            "-c",
23960            "user.email=test@example.invalid",
23961            "commit",
23962            "-q",
23963            "--allow-empty",
23964            "-m",
23965            "feat: fixture",
23966        ]);
23967        let head = g(&["rev-parse", "HEAD"]);
23968        g(&["update-ref", "refs/remotes/origin/main", &head]);
23969        let evidence = crate::pr_outcome::summary_evidence(
23970            &runner.state,
23971            crate::pr_outcome::FinalHead::At(&head),
23972        );
23973        let generated = &runner.state.candidates[0].summary;
23974        runner.state.change_summary = Some(crate::run::ChangeSummary {
23975            base: head.clone(),
23976            head,
23977            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
23978            title: summary_title(generated).unwrap(),
23979            body: summary_without_title(generated),
23980        });
23981    }
23982
23983    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
23984        let mut runner = runner_at(RunStatus::Gating);
23985        runner.state = state_with_summary("add retries", JA_SUMMARY);
23986        if review_only {
23987            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23988        }
23989        runner.state.repo = dir.to_owned();
23990        runner.state.candidates[0].worktree = dir.to_owned();
23991        runner.state.config.agents = agents;
23992        seed_public_summary(&mut runner);
23993        runner
23994    }
23995
23996    fn gate_questions(runner: &Runner) -> usize {
23997        ask::Questions::open()
23998            .list()
23999            .into_iter()
24000            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24001            .count()
24002    }
24003
24004    #[tokio::test]
24005    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24006        crate::run::pin_test_home();
24007        let dir = tempfile::tempdir().unwrap();
24008        let mut runner = rewrite_runner(
24009            dir.path(),
24010            true,
24011            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24012        );
24013        runner.state.config.roles.language_judge =
24014            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24015        let winner = runner.state.candidates[0].clone();
24016        let msg = runner
24017            .guarded_pr_message(&winner, None, true)
24018            .await
24019            .unwrap()
24020            .expect("an English rewrite posts without asking");
24021        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24022        assert!(msg.body.contains("<details>kept</details>"));
24023        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24024        assert_eq!(gate_questions(&runner), 0);
24025        assert!(runner.state.github_text.is_none());
24026        assert!(!runner.state.seats.contains_key("impl-A"));
24027        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24028    }
24029
24030    #[tokio::test]
24031    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24032        crate::run::pin_test_home();
24033        let dir = tempfile::tempdir().unwrap();
24034        let mut runner = rewrite_runner(
24035            dir.path(),
24036            false,
24037            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24038        );
24039        runner.state.config.roles.language_judge =
24040            Some(crate::config::AgentChoice::One("beta".into()));
24041        runner.state.seats.insert(
24042            "impl-A".into(),
24043            SeatState::new("impl-A", "alpha", runner.state.seed),
24044        );
24045        let winner = runner.state.candidates[0].clone();
24046        let msg = runner
24047            .guarded_pr_message(&winner, None, true)
24048            .await
24049            .unwrap()
24050            .expect("rewritten");
24051        assert!(msg.body.contains("<details>kept</details>"));
24052        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24053        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24054        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24055    }
24056
24057    #[tokio::test]
24058    async fn rewrite_reuses_a_resumable_implementer_session() {
24059        crate::run::pin_test_home();
24060        let dir = tempfile::tempdir().unwrap();
24061        let mut runner = rewrite_runner(
24062            dir.path(),
24063            false,
24064            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24065        );
24066        runner.state.config.roles.language_judge =
24067            Some(crate::config::AgentChoice::One("beta".into()));
24068        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24069        seat.turns = 1;
24070        runner.state.seats.insert("impl-A".into(), seat);
24071        let winner = runner.state.candidates[0].clone();
24072        runner
24073            .guarded_pr_message(&winner, None, true)
24074            .await
24075            .unwrap()
24076            .expect("rewritten");
24077        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24078        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24079    }
24080
24081    #[tokio::test]
24082    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24083        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24084        // session, was out of quota, and nothing else was asked.
24085        crate::run::pin_test_home();
24086        let dir = tempfile::tempdir().unwrap();
24087        let mut exhausted = spec("alpha");
24088        exhausted.command = vec!["false".into()];
24089        let mut runner = rewrite_runner(
24090            dir.path(),
24091            false,
24092            vec![exhausted, scripted("beta", EN_REWRITE)],
24093        );
24094        // The implementer's own agent is in the role too: it is not asked twice.
24095        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24096            "alpha".into(),
24097            "beta".into(),
24098        ]));
24099        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24100        seat.turns = 1;
24101        runner.state.seats.insert("impl-A".into(), seat);
24102        let winner = runner.state.candidates[0].clone();
24103        let msg = runner
24104            .guarded_pr_message(&winner, None, true)
24105            .await
24106            .unwrap()
24107            .expect("the role rewrites after the implementer fails");
24108        assert!(msg.body.contains("`src/net.rs`"));
24109        assert_eq!(
24110            runner.state.seats["impl-A"].turns, 2,
24111            "the implementer was tried once"
24112        );
24113        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24114        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24115    }
24116
24117    #[tokio::test]
24118    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24119        crate::run::pin_test_home();
24120        let dir = tempfile::tempdir().unwrap();
24121        let mut broken = spec("bad");
24122        broken.command = vec!["false".into()];
24123        let mut runner = rewrite_runner(
24124            dir.path(),
24125            true,
24126            vec![
24127                broken,
24128                scripted("noformat", "Add retries."),
24129                scripted("good", EN_REWRITE),
24130            ],
24131        );
24132        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24133            "bad".into(),
24134            "noformat".into(),
24135            "good".into(),
24136        ]));
24137        let winner = runner.state.candidates[0].clone();
24138        let msg = runner
24139            .guarded_pr_message(&winner, None, true)
24140            .await
24141            .unwrap()
24142            .expect("the third agent rewrites");
24143        assert!(msg.body.contains("`src/net.rs`"));
24144        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24145        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24146    }
24147
24148    #[tokio::test]
24149    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24150        crate::run::pin_test_home();
24151        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24152        for (agents, role, saved) in [
24153            (
24154                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24155                Some("beta"),
24156                true,
24157            ),
24158            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24159            (Vec::new(), None, false),
24160        ] {
24161            let dir = tempfile::tempdir().unwrap();
24162            let mut runner = rewrite_runner(dir.path(), true, agents);
24163            runner.state.config.roles.language_judge =
24164                role.map(|r| crate::config::AgentChoice::One(r.into()));
24165            let winner = runner.state.candidates[0].clone();
24166            let first = runner
24167                .guarded_pr_message(&winner, None, true)
24168                .await
24169                .unwrap();
24170            assert!(first.is_none(), "withheld text parks the run");
24171            assert!(runner.state.parked);
24172            assert_eq!(gate_questions(&runner), 1);
24173            let g = runner.state.github_text.as_ref().unwrap();
24174            assert_eq!(g.rewrite.is_some(), saved);
24175            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24176        }
24177    }
24178
24179    #[tokio::test]
24180    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24181        crate::run::pin_test_home();
24182        let dir = tempfile::tempdir().unwrap();
24183        let mut runner = runner_at(RunStatus::Gating);
24184        runner.state =
24185            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24186        runner.state.repo = dir.path().to_owned();
24187        runner.state.candidates[0].worktree = dir.path().to_owned();
24188        let mut author = spec("alpha");
24189        author.command = vec![
24190            "sh".into(),
24191            "-c".into(),
24192            "printf '%s' \"$REWRITE_REPLY\"".into(),
24193        ];
24194        author.env.insert(
24195            "REWRITE_REPLY".into(),
24196            format!(
24197                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24198                "English sentence. ".repeat(600)
24199            ),
24200        );
24201        runner.state.config.agents = vec![author];
24202        seed_public_summary(&mut runner);
24203        let winner = runner.state.candidates[0].clone();
24204        assert!(
24205            runner
24206                .guarded_pr_message(&winner, None, true)
24207                .await
24208                .unwrap()
24209                .is_none()
24210        );
24211        let record = runner.state.github_text.clone().unwrap();
24212        let rewrite = record.rewrite.clone().unwrap();
24213        assert_eq!(rewrite.failed, ["body-language"]);
24214        assert!(
24215            rewrite
24216                .body
24217                .ends_with(&format!("magi:run/{}", runner.state.id))
24218        );
24219        let store = ask::Questions::open();
24220        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24221        assert!(
24222            q.choices
24223                .contains(&crate::github_text::USE_REWRITE.to_owned())
24224        );
24225        for label in [
24226            "ORIGINAL",
24227            "FALLBACK",
24228            "REWRITE",
24229            "Rules still failed: body-language",
24230            "truncated",
24231        ] {
24232            assert!(q.detail.contains(label), "{label}");
24233        }
24234        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24235            &runner.state,
24236            &crate::github_text::artifact_name(&record.fingerprint),
24237        ))
24238        .unwrap();
24239        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24240        // Restart from serialized state, then retry after a bad owner title.
24241        runner.state =
24242            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24243        store
24244            .update(&q.id, |q| {
24245                q.say("まだ日本語")?;
24246                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24247            })
24248            .unwrap();
24249        assert!(
24250            runner
24251                .guarded_pr_message(&winner, None, true)
24252                .await
24253                .unwrap()
24254                .is_none()
24255        );
24256        let retry = runner.state.github_text.as_ref().unwrap();
24257        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24258        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24259        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24260        assert!(
24261            q.posting_comparison
24262                .as_ref()
24263                .unwrap()
24264                .matches_detail(&q.detail)
24265        );
24266        store
24267            .update(&q.id, |q| {
24268                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24269            })
24270            .unwrap();
24271        let message = runner
24272            .guarded_pr_message(&winner, None, true)
24273            .await
24274            .unwrap()
24275            .unwrap();
24276        assert_eq!(message.title, rewrite.title);
24277        assert_eq!(message.body, rewrite.body);
24278        assert_eq!(
24279            runner.state.github_text.as_ref().unwrap().choice,
24280            Some(GithubTextChoice::Rewrite)
24281        );
24282        let again = runner
24283            .guarded_pr_message(&winner, None, true)
24284            .await
24285            .unwrap()
24286            .unwrap();
24287        assert_eq!(again.title, message.title);
24288        assert_eq!(again.body, message.body);
24289        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24290        assert!(
24291            !runner
24292                .state
24293                .events
24294                .iter()
24295                .any(|e| e.message.contains(&rewrite.title)
24296                    || e.message.contains("English sentence."))
24297        );
24298    }
24299
24300    #[tokio::test]
24301    async fn historical_posting_reply_never_expires_into_fallback() {
24302        crate::run::pin_test_home();
24303        let dir = tempfile::tempdir().unwrap();
24304        let mut runner = runner_at(RunStatus::Gating);
24305        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24306        runner.state.repo = dir.path().to_owned();
24307        runner.state.candidates[0].worktree = dir.path().to_owned();
24308        seed_public_summary(&mut runner);
24309        let winner = runner.state.candidates[0].clone();
24310        assert!(
24311            runner
24312                .guarded_pr_message(&winner, None, true)
24313                .await
24314                .unwrap()
24315                .is_none()
24316        );
24317        let id = runner
24318            .state
24319            .github_text
24320            .as_ref()
24321            .unwrap()
24322            .question
24323            .clone()
24324            .unwrap();
24325        let store = ask::Questions::open();
24326        let mut q = store.get(&id).unwrap();
24327        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24328        q.answer(ask::Answer::Choice(
24329            crate::github_text::POST_ORIGINAL.into(),
24330        ))
24331        .unwrap();
24332        q.answer_delivered = true;
24333        store.put(&mut q).unwrap();
24334        let source = std::fs::read(store.path_of(&id)).unwrap();
24335        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24336        std::fs::create_dir_all(&migration).unwrap();
24337        std::fs::write(
24338            migration.join("state.json"),
24339            serde_json::to_vec(&serde_json::json!({
24340                "schema": 1, "sources": [id], "pending": [id]
24341            }))
24342            .unwrap(),
24343        )
24344        .unwrap();
24345        for _ in 0..2 {
24346            assert!(
24347                runner
24348                    .guarded_pr_message(&winner, None, true)
24349                    .await
24350                    .unwrap()
24351                    .is_none()
24352            );
24353            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24354            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24355        }
24356        let home = crate::run::home();
24357        crate::task_chat::sweep(
24358            &crate::queue::Queue::at(home.join("queue")),
24359            &crate::talk::Talks::at(home.join("talks")),
24360            &store,
24361            &home,
24362        );
24363        let outbox = crate::task_inquiry::Outbox::at(&home);
24364        outbox
24365            .update_decision(&id, |d| {
24366                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24367                d.source_answer_at = q.answered_at;
24368                Ok(true)
24369            })
24370            .unwrap();
24371        outbox
24372            .settle(
24373                &id,
24374                "owner-chat",
24375                "Owner confirms no publication remains necessary",
24376                None,
24377            )
24378            .unwrap();
24379        assert!(
24380            runner
24381                .guarded_pr_message(&winner, None, true)
24382                .await
24383                .unwrap()
24384                .is_none()
24385        );
24386        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24387        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24388    }
24389
24390    #[tokio::test]
24391    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24392        crate::run::pin_test_home();
24393        let dir = tempfile::tempdir().unwrap();
24394        let mut runner = runner_at(RunStatus::Gating);
24395        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24396        runner.state.repo = dir.path().to_owned();
24397        runner.state.candidates[0].worktree = dir.path().to_owned();
24398        seed_public_summary(&mut runner);
24399        let winner = runner.state.candidates[0].clone();
24400        assert!(
24401            runner
24402                .guarded_pr_message(&winner, None, true)
24403                .await
24404                .unwrap()
24405                .is_none()
24406        );
24407        let record = runner.state.github_text.as_ref().unwrap();
24408        assert!(record.rewrite.is_none());
24409        // Records written before the additive field deserialize with no rewrite.
24410        let mut old = serde_json::to_value(record).unwrap();
24411        old.as_object_mut().unwrap().remove("rewrite");
24412        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24413        assert!(old.rewrite.is_none());
24414        let id = record.question.clone().unwrap();
24415        ask::Questions::open()
24416            .update(&id, |q| {
24417                q.choices.push(crate::github_text::USE_REWRITE.into());
24418                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24419            })
24420            .unwrap();
24421        let message = runner
24422            .guarded_pr_message(&winner, None, true)
24423            .await
24424            .unwrap()
24425            .unwrap();
24426        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24427        assert_eq!(
24428            runner.state.github_text.as_ref().unwrap().choice,
24429            Some(GithubTextChoice::Fallback)
24430        );
24431    }
24432
24433    #[tokio::test]
24434    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24435        crate::run::pin_test_home();
24436        let dir = tempfile::tempdir().unwrap();
24437        let mut runner = runner_at(RunStatus::Gating);
24438        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24439        runner.state.repo = dir.path().to_owned();
24440        runner.state.candidates[0].worktree = dir.path().to_owned();
24441        seed_public_summary(&mut runner);
24442        let winner = runner.state.candidates[0].clone();
24443        assert!(
24444            runner
24445                .guarded_pr_message(&winner, None, true)
24446                .await
24447                .unwrap()
24448                .is_none()
24449        );
24450        let store = ask::Questions::open();
24451        let find = |run: &str| {
24452            store
24453                .list()
24454                .into_iter()
24455                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24456                .unwrap()
24457        };
24458        let run = runner.state.id.clone();
24459        let q = find(&run);
24460        let fp = runner
24461            .state
24462            .github_text
24463            .as_ref()
24464            .unwrap()
24465            .fingerprint
24466            .clone();
24467        let name = crate::github_text::artifact_name(&fp);
24468        let path = crate::run::artifact_path(&runner.state, &name);
24469        assert!(q.detail.contains(&path.display().to_string()));
24470        assert!(q.detail.contains("title-language: title"));
24471        let saved = std::fs::read_to_string(&path).expect("artifact written");
24472        assert!(saved.contains("日本語のタイトル"));
24473        assert!(q.cwd.is_none());
24474        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24475        // A bad replacement is refused and asked about once more.
24476        let say = |id: &str, text: &str, choice: &str| {
24477            store
24478                .update(id, |q| {
24479                    q.thread.push(ask::Turn {
24480                        who: ask::Who::Operator,
24481                        body: text.to_owned(),
24482                        at: jiff::Timestamp::now(),
24483                        note: None,
24484                    });
24485                    q.answer(ask::Answer::Choice(choice.to_owned()))
24486                })
24487                .unwrap();
24488        };
24489        say(&q.id, "まだ日本語", "use my text");
24490        assert!(
24491            runner
24492                .guarded_pr_message(&winner, None, true)
24493                .await
24494                .unwrap()
24495                .is_none()
24496        );
24497        let second = find(&run);
24498        assert_ne!(second.id, q.id);
24499        assert!(second.detail.contains("did not pass"));
24500        // The retry still compares the original text; the rejected
24501        // replacement is named by category only.
24502        assert!(second.detail.contains("日本語のタイトル"));
24503        assert!(!second.detail.contains("まだ日本語"));
24504        assert!(second.detail.contains(&path.display().to_string()));
24505        say(&second.id, "fix: retry failed requests", "use my text");
24506        let message = runner
24507            .guarded_pr_message(&winner, None, true)
24508            .await
24509            .unwrap()
24510            .expect("a vetted replacement is posted");
24511        assert_eq!(message.title, "fix: retry failed requests");
24512        assert_eq!(
24513            runner
24514                .state
24515                .github_text
24516                .as_ref()
24517                .unwrap()
24518                .chosen_title
24519                .as_deref(),
24520            Some("fix: retry failed requests")
24521        );
24522        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24523        // Resumed again: the saved decision is applied, nothing is re-asked.
24524        let again = runner
24525            .guarded_pr_message(&winner, None, true)
24526            .await
24527            .unwrap()
24528            .unwrap();
24529        assert_eq!(again.title, message.title);
24530        assert_eq!(
24531            store
24532                .list()
24533                .into_iter()
24534                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24535                .count(),
24536            2
24537        );
24538    }
24539
24540    #[test]
24541    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24542        // What magi itself writes stays English under any configured language,
24543        // so a future localisation of these headings fails here. (The agents'
24544        // own text is also checked by the posting gate.)
24545        let mut state = state_with_summary(
24546            "add retries",
24547            "TITLE: fix(web): batch reads\n- reads run.json once",
24548        );
24549        state.config.graph.language = "ja".to_owned();
24550        let m = pr_message(&state, 'A');
24551        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24552        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24553
24554        // The task is the operator's own text: it goes in untouched, and the
24555        // fallback title (no summary) may be in its language too.
24556        let task = "今回やってほしいこと: results projector を直す";
24557        let mut state = state_with_summary(task, "- no title line");
24558        state.config.graph.language = "ja".to_owned();
24559        let m = pr_message(&state, 'A');
24560        assert_eq!(
24561            m.title,
24562            format!("chore: land candidate A of run {}", state.id)
24563        );
24564        assert!(
24565            m.body.contains(&format!(
24566                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24567            )),
24568            "{}",
24569            m.body
24570        );
24571    }
24572
24573    #[test]
24574    fn pr_message_scrubs_home_paths_and_addresses() {
24575        let state = state_with_summary(
24576            "fix it in /Users/someone/src/x",
24577            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24578        );
24579        let m = pr_message(&state, 'A');
24580        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24581            assert!(!m.body.contains(leak), "{}", m.body);
24582        }
24583        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24584    }
24585
24586    #[test]
24587    fn pr_message_survives_a_task_that_closes_details() {
24588        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24589        let m = pr_message(&state, 'A');
24590        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24591    }
24592
24593    #[test]
24594    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24595        let cmd = manual_merge_command(
24596            MergeStyle::Squash,
24597            Path::new("/repo"),
24598            "b",
24599            "fix: \"quoted\" $(x) `y`\n\nbody",
24600        );
24601        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24602    }
24603
24604    #[test]
24605    fn manual_merge_command_matches_the_configured_style() {
24606        let repo = Path::new("/repo");
24607        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24608
24609        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24610        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24611
24612        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24613        assert_eq!(
24614            squash,
24615            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24616             \"Merge magi run 0832 (candidate A)\""
24617        );
24618
24619        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24620        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24621    }
24622
24623    #[test]
24624    fn a_nudge_gets_a_quarter_of_the_budget() {
24625        // The judge and implement budgets magi ships with.
24626        assert_eq!(retry_budget(secs(1200), true), secs(300));
24627        assert_eq!(retry_budget(secs(3600), true), secs(900));
24628    }
24629
24630    #[test]
24631    fn a_resent_prompt_keeps_the_whole_budget() {
24632        // The seat kept no context, so the retry is the original job again and
24633        // shortening it would only guarantee a second failure.
24634        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24635        assert_eq!(retry_budget(secs(60), false), secs(60));
24636    }
24637
24638    #[test]
24639    fn the_floor_never_exceeds_the_original_budget() {
24640        // A short configured timeout must not be *raised* by the floor: the
24641        // operator asked for a bound, and a retry may not outlast the attempt
24642        // it is retrying.
24643        assert_eq!(retry_budget(secs(60), true), secs(60));
24644        assert_eq!(retry_budget(secs(480), true), secs(120));
24645        assert_eq!(retry_budget(secs(0), true), secs(0));
24646    }
24647
24648    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24649        agent::CommandEvidence {
24650            id: "item1".to_owned(),
24651            description: "cargo test".to_owned(),
24652            exit_code,
24653            result_summary: String::new(),
24654            source: "codex".to_owned(),
24655        }
24656    }
24657
24658    #[test]
24659    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
24660        // No evidence is not the same fact as unconfirmed evidence: a
24661        // backend with no adapter, or a reply that ran no commands at all,
24662        // must not be misread as carrying a dangling job.
24663        assert!(!has_unconfirmed_command(&[]));
24664    }
24665
24666    #[test]
24667    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
24668        // Deliberately not a check on the exit code's *value*: a fixer
24669        // legitimately runs something that fails mid-iteration before it
24670        // succeeds, and that must never by itself reopen a valid report.
24671        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
24672        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
24673        assert!(!has_unconfirmed_command(&[
24674            evidence(Some(0)),
24675            evidence(Some(101))
24676        ]));
24677    }
24678
24679    #[test]
24680    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
24681        assert!(has_unconfirmed_command(&[
24682            evidence(Some(0)),
24683            evidence(None)
24684        ]));
24685    }
24686
24687    #[test]
24688    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
24689        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24690        assert_eq!(
24691            verified_noop_claim(true, &[], text).as_deref(),
24692            Some("already fixed by b32cfc4, on main.")
24693        );
24694    }
24695
24696    #[test]
24697    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
24698        // A timeout or a bad exit code reads as the ordinary loss it is,
24699        // whatever the reply's own prose claims.
24700        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24701        assert!(verified_noop_claim(false, &[], text).is_none());
24702    }
24703
24704    #[test]
24705    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
24706        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24707        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
24708        // A confirmed command alongside the marker is fine.
24709        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
24710    }
24711
24712    #[test]
24713    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
24714        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
24715    }
24716
24717    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
24718    /// pair, in order, labelled A, B, C, ...
24719    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
24720        runner.state.candidates = shape
24721            .iter()
24722            .enumerate()
24723            .map(|(i, &(empty, verified))| Candidate {
24724                index: i,
24725                label: (b'A' + i as u8) as char,
24726                agent: "sonnet".to_owned(),
24727                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
24728                worktree: PathBuf::from(format!("/wt/{i}")),
24729                summary: String::new(),
24730                stat: String::new(),
24731                files: 0,
24732                commits: 0,
24733                empty,
24734                failed: None,
24735                verified_noop: verified.map(str::to_owned),
24736                duration_ms: 0,
24737                folded: false,
24738            })
24739            .collect();
24740    }
24741
24742    #[test]
24743    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
24744        ask_test_home();
24745        let mut runner = runner_at(RunStatus::Implementing);
24746        set_candidates(
24747            &mut runner,
24748            &[
24749                (true, Some("already on main at b32cfc4")),
24750                (true, Some("same fix, see the existing test")),
24751            ],
24752        );
24753
24754        runner
24755            .after_implement()
24756            .expect("a verified no-op is not an error");
24757
24758        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
24759    }
24760
24761    #[test]
24762    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
24763        ask_test_home();
24764        let mut runner = runner_at(RunStatus::Implementing);
24765        // Candidate A declares a verified no-op; candidate B simply wrote
24766        // nothing and said nothing about why. One candidate's claim is not
24767        // the whole run's agreement.
24768        set_candidates(
24769            &mut runner,
24770            &[(true, Some("already on main at b32cfc4")), (true, None)],
24771        );
24772
24773        let err = runner
24774            .after_implement()
24775            .expect_err("an unverified empty candidate must still fail the run");
24776
24777        assert!(
24778            err.to_string().contains("no candidate produced a change"),
24779            "{err}"
24780        );
24781        assert_eq!(runner.state.status, RunStatus::Failed);
24782    }
24783
24784    #[test]
24785    fn after_implement_still_fails_an_ordinary_all_empty_run() {
24786        ask_test_home();
24787        let mut runner = runner_at(RunStatus::Implementing);
24788        set_candidates(&mut runner, &[(true, None), (true, None)]);
24789
24790        let err = runner
24791            .after_implement()
24792            .expect_err("no candidate declared anything; this is an ordinary failure");
24793
24794        assert!(
24795            err.to_string().contains("no candidate produced a change"),
24796            "{err}"
24797        );
24798        assert_eq!(runner.state.status, RunStatus::Failed);
24799    }
24800}
24801
24802/// A graft rollback whose restore could not be confirmed (see
24803/// [`Runner::graft`]).
24804#[derive(Debug)]
24805struct GraftRestoreFailed(String);
24806
24807impl std::fmt::Display for GraftRestoreFailed {
24808    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24809        write!(
24810            f,
24811            "could not restore the winner to its pre-graft commit: {}",
24812            self.0
24813        )
24814    }
24815}
24816
24817impl std::error::Error for GraftRestoreFailed {}
24818
24819/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
24820/// not the agent: they never draw on an agent's own timeout, and running out of
24821/// them never reads as an agent failure.
24822#[cfg(test)]
24823mod resource_wait_tests {
24824    use super::*;
24825    use std::collections::BTreeMap;
24826
24827    fn sh(id: &str, script: &str) -> AgentSpec {
24828        AgentSpec {
24829            id: id.to_owned(),
24830            kind: crate::config::AgentKind::Command,
24831            model: None,
24832            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
24833            extra_args: Vec::new(),
24834            env: BTreeMap::new(),
24835            prompt_delivery: None,
24836            max_turn_secs: None,
24837        }
24838    }
24839
24840    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
24841        SeatJob {
24842            seat: SeatState::new("impl-A", &spec.id, 1),
24843            spec,
24844            cwd: dir.to_path_buf(),
24845            prompt: "do it".to_owned(),
24846            timeout,
24847            allow_write: true,
24848            sessions: false,
24849            artifacts: dir.join("art"),
24850            stem: "impl-A".to_owned(),
24851            handover: None,
24852        }
24853    }
24854
24855    fn state(resource_wait_secs: u64) -> RunState {
24856        let mut config = Config::default();
24857        config.graph.timeout_resource_wait = resource_wait_secs;
24858        RunState::new(
24859            PathBuf::from("/repo"),
24860            "main".to_owned(),
24861            "abc1234".to_owned(),
24862            "task".to_owned(),
24863            config,
24864        )
24865    }
24866
24867    fn hold(cache: &Path) -> crate::cache::Guard {
24868        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
24869        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
24870            crate::cache::AcquireOutcome::Acquired(g) => g,
24871            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
24872        }
24873    }
24874
24875    async fn run(
24876        jobs: Vec<SeatJob>,
24877        sem: Arc<Semaphore>,
24878        cache: Option<&Path>,
24879        st: &mut RunState,
24880    ) -> Vec<(usize, SeatState, AgentOutcome)> {
24881        let prompts = Prompts::default();
24882        let ctx = WaveCtx {
24883            run: "r",
24884            node: "implement",
24885            prompts: &prompts,
24886            cache,
24887            round: None,
24888            carry_seats: false,
24889            pauses: None,
24890        };
24891        wave(jobs, sem, &ctx, st, 0).await
24892    }
24893
24894    #[tokio::test]
24895    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
24896        crate::run::pin_test_home();
24897        let home = crate::run::home();
24898        let tmp = tempfile::tempdir().unwrap();
24899        let repo = tmp.path().join("repo");
24900        let checkout = tmp.path().join("checkout");
24901        std::fs::create_dir(&repo).unwrap();
24902        git::git(&repo, &["init"]).await.unwrap();
24903        git::git(
24904            &repo,
24905            &[
24906                "-c",
24907                "user.name=Fixture",
24908                "-c",
24909                "user.email=fixture@example.invalid",
24910                "commit",
24911                "--allow-empty",
24912                "-m",
24913                "initial",
24914            ],
24915        )
24916        .await
24917        .unwrap();
24918        git::worktree_add_detached(&repo, &checkout, "HEAD")
24919            .await
24920            .unwrap();
24921        let target = crate::build_target::resolve(&home, &checkout).unwrap();
24922        let target_lease = hold(&target);
24923        let shared = tmp.path().join("unrelated");
24924        let _shared_lease = hold(&shared);
24925        let mut st = state(0);
24926        st.repo = repo.clone();
24927        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
24928        st.config.verify.e2e = vec![format!(
24929            "CARGO_TARGET_DIR='{}' cargo test",
24930            git::path_arg(&shared)
24931        )];
24932        let config = tmp.path().join("config.toml");
24933        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
24934        let prompts = Prompts::default();
24935        let run_id = st.id.clone();
24936        let ctx = WaveCtx {
24937            run: &run_id,
24938            node: "implement",
24939            prompts: &prompts,
24940            cache: None,
24941            round: None,
24942            carry_seats: false,
24943            pauses: None,
24944        };
24945        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
24946        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
24947        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
24948        assert_eq!(results[0].1.turns, 0);
24949        let saved = RunState::load_under(&run_id, &home).unwrap();
24950        let block = saved.resource_block.unwrap();
24951        assert!(matches!(
24952            block.cause,
24953            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
24954                if actual == &target
24955        ));
24956        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
24957        let mut task = crate::queue::Task::new(
24958            "build".into(),
24959            "build".into(),
24960            repo,
24961            crate::queue::Source::Human,
24962        );
24963        task.runs.push(run_id);
24964        task.hold_machine(Some(format!(
24965            "{}{}",
24966            crate::cache::RESOURCE_HOLD,
24967            block.description()
24968        )));
24969        queue.put(&mut task).unwrap();
24970        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
24971        let triage =
24972            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
24973        let pending = triage();
24974        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
24975        assert_eq!(
24976            queue.get(&task.id).unwrap().status,
24977            crate::queue::TaskStatus::Held
24978        );
24979        drop(target_lease);
24980        assert_eq!(triage().resumed, vec![task.id.clone()]);
24981        assert_eq!(
24982            queue.get(&task.id).unwrap().status,
24983            crate::queue::TaskStatus::Queued
24984        );
24985        assert!(crate::cache::in_use(&home, &shared));
24986    }
24987
24988    #[tokio::test]
24989    async fn verification_cache_wait_preserves_the_command_budget() {
24990        crate::run::pin_test_home();
24991        let tmp = tempfile::tempdir().unwrap();
24992        let cache = tmp.path().join("target");
24993        let guard = hold(&cache);
24994        let release = tokio::spawn(async move {
24995            tokio::time::sleep(Duration::from_millis(100)).await;
24996            guard.release();
24997        });
24998        let mut st = state(10);
24999        let budget = Duration::from_millis(50);
25000        let wait = repository_wait(&st, None);
25001        let (outcomes, _) = with_cache_lease(
25002            &mut st,
25003            Some(&cache),
25004            "gate",
25005            "gate",
25006            tmp.path(),
25007            "abc1234",
25008            budget,
25009            "test gate",
25010            &wait,
25011            |_, available| async move {
25012                assert_eq!(
25013                    available, budget,
25014                    "contention must not shorten verification"
25015                );
25016                (Vec::new(), false, Vec::new())
25017            },
25018        )
25019        .await
25020        .unwrap();
25021        release.await.unwrap();
25022        assert!(outcomes.is_empty(), "{outcomes:?}");
25023        assert!(
25024            st.events
25025                .iter()
25026                .any(|event| event.message.contains("waiting for"))
25027        );
25028        assert!(st.resource_wait.is_none());
25029        // The verification body no longer owns the lease after returning.
25030        hold(&cache).release();
25031    }
25032
25033    #[tokio::test]
25034    async fn verification_cache_wait_expires_without_starting_commands() {
25035        crate::run::pin_test_home();
25036        let tmp = tempfile::tempdir().unwrap();
25037        let cache = tmp.path().join("target");
25038        let _held = hold(&cache);
25039        let mut st = state(0);
25040        let wait = repository_wait(&st, None);
25041        let (outcomes, _) = with_cache_lease(
25042            &mut st,
25043            Some(&cache),
25044            "gate",
25045            "gate",
25046            tmp.path(),
25047            "abc1234",
25048            Duration::from_secs(60),
25049            "test gate",
25050            &wait,
25051            |_, _| async { panic!("commands must not start without the cache lease") },
25052        )
25053        .await
25054        .unwrap();
25055        assert_eq!(outcomes.len(), 1);
25056        assert!(outcomes[0].resource_blocked);
25057        assert!(st.resource_wait.is_none());
25058        assert!(matches!(
25059            st.resource_block.unwrap().cause,
25060            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25061        ));
25062    }
25063
25064    #[tokio::test]
25065    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25066        crate::run::pin_test_home();
25067        let tmp = tempfile::tempdir().unwrap();
25068        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25069        let cache = tmp.path().join("cache");
25070        let mut state = state(21600);
25071        let wait = repository_wait(&state, None);
25072        let (outcomes, _) = with_cache_lease(
25073            &mut state,
25074            Some(&cache),
25075            "gate",
25076            "gate",
25077            tmp.path(),
25078            "head",
25079            Duration::from_secs(60),
25080            "gate",
25081            &wait,
25082            |_, _| async { panic!("freshness failure must not start verification") },
25083        )
25084        .await
25085        .unwrap();
25086        assert_eq!(outcomes.len(), 1);
25087        assert!(outcomes[0].resource_blocked);
25088        let block = state.resource_block.unwrap();
25089        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25090        assert!(!block.description().contains("timed out"));
25091    }
25092
25093    #[tokio::test]
25094    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25095        crate::run::pin_test_home();
25096        let tmp = tempfile::tempdir().unwrap();
25097        let cache = tmp.path().join("cache");
25098        let _held = hold(&cache);
25099        let mut state = state(21600);
25100        let pause = Pause::new();
25101        let interrupt = Pause::new();
25102        let cause = ParkCause::Operator;
25103        pause.park_for(cause.clone());
25104        let prompts = Prompts::default();
25105        let ctx = WaveCtx {
25106            run: "test",
25107            node: "fix",
25108            prompts: &prompts,
25109            cache: Some(&cache),
25110            round: None,
25111            carry_seats: false,
25112            pauses: Some((&pause, &interrupt)),
25113        };
25114        let result = wave(
25115            vec![job(
25116                sh("writer", "exit 99"),
25117                tmp.path(),
25118                Duration::from_secs(1),
25119            )],
25120            Arc::new(Semaphore::new(1)),
25121            &ctx,
25122            &mut state,
25123            0,
25124        )
25125        .await;
25126        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
25127        assert_eq!(result[0].1.turns, 0);
25128        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25129        assert_eq!(
25130            state.resource_block.unwrap().cause,
25131            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
25132        );
25133        assert!(state.active.is_empty());
25134    }
25135
25136    #[tokio::test]
25137    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
25138        crate::run::pin_test_home();
25139        let tmp = tempfile::tempdir().unwrap();
25140        let cache = tmp.path().join("target-a");
25141        let guard = hold(&cache);
25142        // Held for longer than the agent's whole 1s budget.
25143        tokio::spawn(async move {
25144            tokio::time::sleep(Duration::from_millis(1500)).await;
25145            guard.release();
25146        });
25147        let mut st = state(60);
25148        let results = run(
25149            vec![job(
25150                sh("alpha", "echo ok"),
25151                tmp.path(),
25152                Duration::from_secs(1),
25153            )],
25154            Arc::new(Semaphore::new(1)),
25155            Some(&cache),
25156            &mut st,
25157        )
25158        .await;
25159        assert!(
25160            matches!(results[0].2, AgentOutcome::Ok(_)),
25161            "the wait must not be charged to the agent"
25162        );
25163        assert!(st.resource_block.is_none());
25164        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25165        assert!(st.resource_wait.is_none() && st.active.is_empty());
25166    }
25167
25168    #[tokio::test]
25169    #[cfg(unix)]
25170    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
25171        use std::os::fd::AsRawFd as _;
25172        crate::run::pin_test_home();
25173        let tmp = tempfile::tempdir().unwrap();
25174        crate::git::git(tmp.path(), &["init"]).await.unwrap();
25175        let common = tmp.path().join(".git");
25176        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
25177        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
25178        assert_eq!(
25179            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
25180            0
25181        );
25182        let mut st = state(1);
25183        st.config.coordination = crate::config::test_coordination();
25184        let mut reader = job(
25185            sh("reader", "echo must-not-run"),
25186            tmp.path(),
25187            Duration::from_secs(30),
25188        );
25189        reader.allow_write = false;
25190        let results = run(
25191            vec![reader.clone()],
25192            Arc::new(Semaphore::new(1)),
25193            None,
25194            &mut st,
25195        )
25196        .await;
25197        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25198        assert_eq!(results[0].1.turns, 0);
25199        assert!(FailClass::of(&results[0].2).is_none());
25200        assert_eq!(
25201            st.resource_block.as_ref().unwrap().kind,
25202            "repository coordination"
25203        );
25204        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25205        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25206        drop(external);
25207        let editor = crate::repo_lock::SeatLease::for_checkout(
25208            tmp.path(),
25209            true,
25210            crate::config::test_coordination().as_ref(),
25211        )
25212        .await
25213        .unwrap();
25214        let pause = Pause::new();
25215        let interrupt = Pause::new();
25216        let prompts = Prompts::default();
25217        let ctx = WaveCtx {
25218            run: "r",
25219            node: "review",
25220            prompts: &prompts,
25221            cache: None,
25222            round: None,
25223            carry_seats: false,
25224            pauses: Some((&pause, &interrupt)),
25225        };
25226        let (results, ()) = tokio::join!(
25227            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25228            async {
25229                tokio::time::sleep(Duration::from_millis(50)).await;
25230                pause.park();
25231            }
25232        );
25233        assert!(
25234            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25235        );
25236        assert_eq!(results[0].1.turns, 0);
25237        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25238        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25239        drop(editor);
25240    }
25241
25242    #[tokio::test]
25243    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25244        crate::run::pin_test_home();
25245        let tmp = tempfile::tempdir().unwrap();
25246        let cache = tmp.path().join("target-b");
25247        let _held = hold(&cache);
25248        let mut st = state(1);
25249        let results = run(
25250            vec![job(
25251                sh("alpha", "echo ok"),
25252                tmp.path(),
25253                Duration::from_secs(1),
25254            )],
25255            Arc::new(Semaphore::new(1)),
25256            Some(&cache),
25257            &mut st,
25258        )
25259        .await;
25260        let (_, seat, out) = &results[0];
25261        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25262        assert!(wave_blocked(&results));
25263        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25264        assert_eq!(seat.turns, 0, "nothing was asked");
25265        assert!(
25266            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25267            "no agent was spawned"
25268        );
25269        assert!(FailClass::of(out).is_none(), "not a failure class");
25270        let block = st.resource_block.as_ref().expect("recorded for the resume");
25271        assert_eq!(block.kind, "shared build cache");
25272        assert!(matches!(
25273            block.cause,
25274            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25275        ));
25276        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25277        assert!(st.active.is_empty());
25278    }
25279
25280    #[tokio::test]
25281    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25282        crate::run::pin_test_home();
25283        let tmp = tempfile::tempdir().unwrap();
25284        let mut st = state(1);
25285        let results = run(
25286            vec![job(
25287                sh("alpha", "echo ok"),
25288                tmp.path(),
25289                Duration::from_secs(1),
25290            )],
25291            Arc::new(Semaphore::new(0)),
25292            None,
25293            &mut st,
25294        )
25295        .await;
25296        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25297        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25298        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25299    }
25300
25301    #[tokio::test]
25302    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25303        crate::run::pin_test_home();
25304        let tmp = tempfile::tempdir().unwrap();
25305        let mut st = state(60);
25306        let results = run(
25307            vec![job(
25308                sh("alpha", "sleep 30"),
25309                tmp.path(),
25310                Duration::from_secs(1),
25311            )],
25312            Arc::new(Semaphore::new(1)),
25313            None,
25314            &mut st,
25315        )
25316        .await;
25317        let out = &results[0].2;
25318        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25319        let class = FailClass::of(out).expect("a failure");
25320        assert_eq!(class, FailClass::Timeout);
25321        assert!(should_hand_over(None, &class), "existing handover policy");
25322        assert!(st.resource_block.is_none());
25323    }
25324}