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};
61
62/// Fixed commit message for graph-owned mechanical `verify.pre_gate` commits.
63pub const PRE_GATE_COMMIT_MESSAGE: &str = "magi: pre_gate (mechanical fixes)";
64
65/// Event node recorded by [`Runner::run_pre_gate`].
66pub(crate) const PRE_GATE_EVENT_NODE: &str = "pre_gate";
67
68/// Durable event text logged when [`Runner::run_pre_gate`] commits mechanical changes.
69pub(crate) fn pre_gate_commit_event(head: &str) -> String {
70    format!("committed mechanical fixes ({head})")
71}
72use crate::worktree_setup;
73
74/// Bytes of a failing command's output kept in an event, so the reason a run
75/// stopped is readable from the report without opening `run.json`.
76const EVENT_OUTPUT_TAIL: usize = 2_000;
77
78/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
79/// command's pid before releasing the build cache's lease.
80const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
81
82/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
83/// command's pid to actually exit before giving up and releasing anyway.
84///
85/// A timeout means the process was asked to die (`kill_on_drop`,
86/// `start_kill`), not that it already has — on Windows in particular that can
87/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
88/// the instant the command returns would let the very next acquirer (this
89/// run's own next round, another run's verification, the janitor's prune)
90/// start touching the same directory while it might still be writing to it,
91/// so this polls the actual pid — real confirmation, not a fixed guess —
92/// until it is gone or this ceiling is reached. It is still not full
93/// process-tree reaping: a grandchild the timed-out process spawned and that
94/// outlives it independently is invisible to a pid check, and continuing to
95/// observe and collect *that* stays a different piece of work with its own
96/// owner. Set generously because the common case returns early the moment
97/// the pid is confirmed gone, not because every timeout pays this in full.
98const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
99
100/// Consecutive review rounds with no tree progress (see
101/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
102/// instead of spending the rest of the round budget.
103///
104/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
105/// legitimately finds nothing left to change (its previous round's fix already
106/// covered it, and this round's reviewers re-raised only nits) looks the same
107/// as one that is spinning, for exactly one round. Two in a row is where the
108/// two stop being distinguishable, and a review round on this workload has
109/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
110/// third attempt at a tree that has not moved twice running is pure cost.
111/// This does not touch `review_rounds` itself, which stays the operator's
112/// call.
113pub(crate) const STAGNANT_LIMIT: usize = 2;
114
115/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
116/// a base that moved before giving up and leaving the run `Blocked` for a
117/// person.
118///
119/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
120/// that keeps moving faster than a run can catch it is not something more
121/// rebasing fixes, it is a person's call. Not the same *number as*
122/// `land_rounds` - this budget is spent before a pull request exists, land's
123/// after - but bounded for the identical reason, so it uses the same
124/// default. Counted across both call sites in [`Runner::finish_after_tally`]
125/// (once before review, once before the gate), because either one finding
126/// the base still moving is the same signal.
127pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
128
129/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
130/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
131/// reply held no [`FixReport`].
132///
133/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
134/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
135/// "I'll pause here until the `cargo make check` background run reports
136/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
137/// No `FixReport` was ever collected from that seat, and the run moved on to
138/// the next review round regardless.
139///
140/// Bounded independently of `review_rounds` and `graph.retries`: this
141/// recovers one seat's missing report mid-round, not a new round of review or
142/// an ordinary parse retry, and must not itself become the unbounded wait the
143/// rest of this module exists to avoid.
144const MAX_FIX_CONTINUATIONS: usize = 2;
145
146/// One queued agent invocation.
147///
148/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
149/// CLI hung up on its own stream is asked again from the same job rather than
150/// rebuilt from scratch. See [`Runner::resume_undelivered`].
151#[derive(Clone)]
152struct SeatJob {
153    spec: AgentSpec,
154    seat: SeatState,
155    cwd: PathBuf,
156    prompt: String,
157    timeout: Duration,
158    allow_write: bool,
159    sessions: bool,
160    artifacts: PathBuf,
161    stem: String,
162    /// The prompt for a seat that has been handed to another roster agent
163    /// (a fresh session): everything the original seat would have
164    /// remembered. `None` when `prompt` already carries it, as the first
165    /// ranking and the implement prompt do. Never a resume-style prompt.
166    handover: Option<String>,
167}
168
169/// How the graph reads one agent invocation.
170///
171/// Quota is split out from an ordinary failure on purpose: a rate-limited call
172/// is known to fail again if retried now, so the retry loop must not spend an
173/// attempt on it. `Dropped` is split out for the opposite reason: unlike
174/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
175/// error JSON, never the agent's answer — a caller that matched only
176/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
177/// left to read that JSON as if it were usable output. `resume_undelivered`
178/// is the only caller that acts on it; everywhere else it is reported like an
179/// ordinary failure.
180enum AgentOutcome {
181    /// A usable output.
182    Ok(AgentOutput),
183    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
184    Quota(AgentOutput),
185    /// The CLI hung up on its own stream after billed work. See
186    /// [`agent::AgentOutput::work_undelivered`].
187    Dropped(AgentOutput),
188    /// Any other failure: a timeout, a bad exit code, an empty reply.
189    Failed(String),
190    /// A resource prevented admission or interrupted execution. Not an agent
191    /// failure: never advance a fallback chain or spend an attempt on it.
192    /// Post-spawn interruptions carry a typed error into wave, which records
193    /// implementation preservation before returning this outcome. This outcome
194    /// alone is not proof that no source changes were made.
195    /// [`RunState::resource_block`] says why.
196    ResourceBlocked(String),
197}
198
199/// A request to park the run at its next node boundary.
200///
201/// Cloning is how the request travels: the loop keeps one handle and hands a
202/// clone to each [`Runner`], and every clone points at the same flag. There
203/// is no channel because there is nothing to send - the only message is
204/// "park", it is idempotent, and a flag cannot be missed by a receiver that
205/// was not listening yet.
206///
207/// The boundary is what makes this cheap. Every node writes the run's state
208/// before the next one starts, and every node skips what is already recorded:
209/// `prep` returns early once candidates exist, `implement` asks only the seats
210/// with nothing on disk, `judge` returns early once judgements exist. So a
211/// parked run resumes into exactly the node it stopped before, and no agent
212/// work is thrown away. Killing the process mid-node, by contrast, loses
213/// whatever the seats in flight had not yet written - which for an implement
214/// wave is an hour of paid work.
215///
216/// A [`Runner`] watches two independent handles of this type - see
217/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
218/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
219/// clone covering the whole daemon's lifetime and is never asked to un-park,
220/// which is correct exactly because nothing is dispatched after it fires.
221/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
222/// that parks for an interrupted task must go on to run other tasks
223/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
224/// reusing the daemon-wide one.
225#[derive(Debug, Clone, Default)]
226pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
227
228impl Pause {
229    /// A pause nobody has asked for yet.
230    #[must_use]
231    pub fn new() -> Self {
232        Self::default()
233    }
234
235    /// Ask the run to park at its next node boundary. Idempotent.
236    pub fn park(&self) {
237        self.0.store(true, Ordering::SeqCst);
238    }
239
240    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
241    /// fold into the run's own `park` event - so an operator reading the run
242    /// later knows this was a deliberate interrupt rather than a shutdown or
243    /// a binary swap. The first reason recorded wins; a park already in
244    /// flight is not relabelled by a second, unrelated request.
245    pub fn park_because(&self, reason: impl Into<String>) {
246        self.park_for(ParkCause::Interrupt {
247            reason: reason.into(),
248        });
249    }
250
251    /// [`Pause::park`], recording the structured cause. The first cause
252    /// recorded wins, like [`Pause::park_because`].
253    pub fn park_for(&self, cause: ParkCause) {
254        let mut reason_guard = self
255            .1
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if reason_guard.is_none() {
259            *reason_guard = Some(cause);
260        }
261        drop(reason_guard);
262        self.park();
263    }
264
265    /// Has a park been asked for?
266    #[must_use]
267    pub fn parked(&self) -> bool {
268        self.0.load(Ordering::SeqCst)
269    }
270
271    /// Why the park was asked for, when the caller used [`Pause::park_because`].
272    #[must_use]
273    pub fn reason(&self) -> Option<String> {
274        self.cause().map(|c| c.label())
275    }
276
277    /// The structured cause, when one was recorded.
278    #[must_use]
279    pub fn cause(&self) -> Option<ParkCause> {
280        self.1
281            .lock()
282            .unwrap_or_else(std::sync::PoisonError::into_inner)
283            .clone()
284    }
285}
286
287/// Drives one run.
288pub struct Runner {
289    /// Run state; public so the CLI can report on it.
290    pub state: RunState,
291    roles: ResolvedRoles,
292    sem: Arc<Semaphore>,
293    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
294    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
295    /// this is never the same handle as `interrupt`.
296    pause: Pause,
297    /// Set when `magi serve`'s interrupt scheduler wants this specific run
298    /// parked at its next node boundary, to let a task marked
299    /// [`crate::queue::Task::interrupt`] run alone before this one carries
300    /// on. Unlike `pause`, a fresh, unshared handle per run - see
301    /// [`Runner::watch_interrupt`].
302    interrupt: Pause,
303}
304
305/// Where the branch's own commits start: its merge base with the base branch
306/// as the remote has it now, else with the recorded `base_commit`. A branch
307/// rebased onto a base that moved past `base_commit` would otherwise count
308/// the base's commits as its own under `base_commit..branch`.
309async fn review_base(
310    repo: &Path,
311    remote: &str,
312    base_branch: &str,
313    base_commit: &str,
314    branch: &str,
315) -> String {
316    review_base_checked(repo, remote, base_branch, base_commit, branch)
317        .await
318        .0
319}
320
321/// [`review_base`] plus whether the base was read from a freshly fetched
322/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
323/// never older than `base_commit`'s view of the base), but the answer is then
324/// not trusted to rewrite a pull request's title.
325async fn review_base_checked(
326    repo: &Path,
327    remote: &str,
328    base_branch: &str,
329    base_commit: &str,
330    branch: &str,
331) -> (String, bool) {
332    let tracking = format!("{remote}/{base_branch}");
333    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
334    if git::rev_exists(repo, &tracking).await
335        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
336        && !mb.is_empty()
337    {
338        return (mb, fresh);
339    }
340    let mb = git::merge_base(repo, base_commit, branch)
341        .await
342        .ok()
343        .filter(|mb| !mb.is_empty())
344        .unwrap_or_else(|| base_commit.to_owned());
345    (mb, false)
346}
347
348/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
349/// when git cannot say or finds nothing: a stale list is better than a wrong
350/// or empty one.
351pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
352    if !is_review_run(state) {
353        return;
354    }
355    let base = review_base(
356        &state.repo,
357        &state.config.merge.remote,
358        &state.base_branch,
359        &state.base_commit,
360        branch,
361    )
362    .await;
363    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
364        && !subjects.is_empty()
365        && state.reviewed_commits.as_ref() != Some(&subjects)
366    {
367        state.reviewed_commits = Some(subjects);
368        state.save().ok();
369    }
370}
371
372/// Subjects of the base's commits between the recorded start and the branch's
373/// merge base: what a stale `base_commit..branch` would have mistaken for the
374/// branch's own work.
375async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
376    let (base, trusted) = review_base_checked(
377        &state.repo,
378        &state.config.merge.remote,
379        &state.base_branch,
380        &state.base_commit,
381        branch,
382    )
383    .await;
384    if !trusted {
385        return None;
386    }
387    git::subjects(&state.repo, &state.base_commit, &base)
388        .await
389        .ok()
390}
391
392/// May an adopted pull request's title be replaced with `computed`? Only when
393/// it is empty, magi's own shape, or a base commit's subject that leaked in;
394/// a title a person wrote stays. Never when `computed` is itself a leak.
395pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
396    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
397    if is_leak(computed) {
398        return false;
399    }
400    let cur = current.trim();
401    cur.is_empty()
402        || cur.starts_with(REVIEW_PROMPT_OPENING)
403        || cur.starts_with("chore: land candidate")
404        || cur.starts_with("magi: candidate")
405        || is_leak(cur)
406}
407
408/// The commit a run branches from: the base branch as the remote has it.
409///
410/// Two failures this replaces. A run used to branch off `HEAD` and so refused
411/// to start on a dirty tree, which made `magi serve` decline every task for as
412/// long as the operator had work in progress - most of the time. Branching off
413/// the *local* base branch fixed that and introduced a worse one: `land` merges
414/// the winner on GitHub, nothing updates the local ref, and the next run
415/// branches off a base missing everything the previous runs landed. Two tasks
416/// in a row from a phone would have had the second silently re-implementing
417/// against stale code and opening a pull request that reverted the first.
418///
419/// Only refs move here - no checkout, no local branch, no merge - so it is safe
420/// with uncommitted work in the tree. A machine with no network still starts:
421/// the fetch may fail and the local tip is used with a warning, because
422/// refusing to run offline is a worse failure than running against a base the
423/// operator can see for themselves.
424///
425/// One function, called by both entry points. Two answers to "where does a run
426/// branch from" is the kind of drift nobody notices until a diff is wrong.
427/// Bring the local `branch` in line with `<remote>/<branch>` before a review
428/// checks it out.
429///
430/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
431/// anything other than plain `git push` from this checkout (a jj colocated
432/// workspace, another clone) moves only the remote-tracking ref - so the local
433/// one can be a stale placeholder. It moves only when local is behind the remote or is an
434/// empty placeholder that diverged from it; unpushed local work is kept, and a real
435/// divergence is refused rather than guessed at.
436async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
437    let tracking = format!("{remote}/{branch}");
438    let fetched = git::fetch(repo, remote, branch).await;
439    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
440    let local_exists = git::branch_exists(repo, branch).await?;
441    if !fresh {
442        if !local_exists {
443            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
444        }
445        tracing::warn!(
446            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
447        );
448        return Ok(());
449    }
450    let remote_sha = git::rev_parse(repo, &tracking).await?;
451    if !local_exists {
452        git::git(repo, &["branch", branch, &tracking]).await?;
453        return Ok(());
454    }
455    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
456    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
457        return Ok(());
458    }
459    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
460        // Diverged. `reconcile` settles it only when it can prove nothing is
461        // lost: a local tip that is the remote's change rebased is pushed over
462        // it (lease pinned to the tip read here), a tip whose every extra
463        // commit is empty is a placeholder the remote's work replaced, and
464        // anything else is two different changes - a question for a person.
465        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
466            .await?
467        {
468            crate::reconcile::Reconciliation::Pushed => {
469                tracing::warn!(
470                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
471                    short(&local_sha),
472                    short(&remote_sha)
473                );
474                return Ok(());
475            }
476            crate::reconcile::Reconciliation::Placeholder => {}
477            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
478        }
479    }
480    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
481    if !out.ok() {
482        bail!(
483            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
484            short(&local_sha),
485            short(&remote_sha),
486            out.stderr
487        );
488    }
489    tracing::warn!(
490        "local `{branch}` was stale: fast-forwarded {} -> {}",
491        short(&local_sha),
492        short(&remote_sha)
493    );
494    Ok(())
495}
496
497async fn resolve_base(
498    repo: &Path,
499    base_branch: &str,
500    remote: &str,
501    coordination: Option<&crate::config::Coordination>,
502) -> Result<crate::run::FetchedBase> {
503    let _lease = crate::repo_lock::SeatLease::operation_with(
504        repo,
505        coordination,
506        &crate::repo_lock::WaitPolicy::current(),
507    )
508    .await?;
509    let tracking = format!("{remote}/{base_branch}");
510    let fetched = git::fetch(repo, remote, base_branch).await;
511    if let Ok(out) = &fetched
512        && out.ok()
513        && git::rev_exists(repo, &tracking).await
514    {
515        return Ok(crate::run::FetchedBase {
516            remote: remote.to_owned(),
517            branch: base_branch.to_owned(),
518            commit: git::rev_parse(repo, &tracking).await?,
519            fetched_at: jiff::Timestamp::now(),
520        });
521    }
522    let why = match &fetched {
523        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
524        Ok(_) => format!("{remote} has no {base_branch}"),
525        Err(e) => e.to_string(),
526    };
527    // No fallback to the local branch: it may be behind, and branching off an
528    // old commit is the stale-checkout bug this check exists to prevent.
529    bail!(
530        "cannot read {tracking} ({why}); refusing to branch off the local \
531         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
532         base / remote in magi.toml. This is launcher preparation: check the \
533         launcher's network, Git access and repository coordination before \
534         retrying"
535    )
536}
537
538/// Outcome of the shared fixer chain, before caller-owned stop policy.
539enum FixStep {
540    Resource,
541    Recorded { report_lost: bool },
542}
543
544/// Exclusive claim shared by targeted repairs and repository reassignment.
545/// Held before asynchronous fix preflight and released on every return or panic.
546///
547/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
548/// manual `magi fix` invocations against the same run are otherwise
549/// invisible to each other and would race to remove and recreate the same
550/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
551/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
552/// which is only ever reclaimed later, out of band, by
553/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
554/// `magi fix` invocation is not necessarily running under either of those, so
555/// nothing would ever sweep a lock a killed or crashed process left behind.
556/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
557/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
558/// lease use: an unreadable or unparsable pid, or a liveness query the
559/// platform cannot answer, reads as alive and the lock is left in place.
560pub(crate) struct FixClaim {
561    path: PathBuf,
562}
563
564impl FixClaim {
565    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
566        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
567        let path = dir.join("fix.lock");
568        let retry = crate::lock_file::Retry::new(None);
569        match Self::create(&path, retry) {
570            Ok(claim) => Ok(claim),
571            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
572                if Self::reclaim_if_dead(&path) {
573                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
574                } else {
575                    bail!(
576                        "another repair or `magi fix` is already running for this run ({} exists)",
577                        path.display()
578                    )
579                }
580            }
581            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
582        }
583    }
584
585    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
586        let mut f = retry.create(path)?;
587        use std::io::Write as _;
588        // Read back by `reclaim_if_dead` on a later, stuck invocation.
589        writeln!(f, "{}", std::process::id())?;
590        Ok(Self {
591            path: path.to_owned(),
592        })
593    }
594
595    /// True if the lock named a process confirmed dead, in which case it was
596    /// also removed. Never true on an unreadable file, an unparsable pid, or
597    /// a liveness query the platform cannot answer — see this type's own doc.
598    fn reclaim_if_dead(path: &Path) -> bool {
599        let dead = std::fs::read_to_string(path)
600            .ok()
601            .and_then(|body| body.trim().parse::<u32>().ok())
602            .is_some_and(|pid| !crate::proc::pid_alive(pid));
603        dead && std::fs::remove_file(path).is_ok()
604    }
605}
606
607impl Drop for FixClaim {
608    fn drop(&mut self) {
609        let _ = std::fs::remove_file(&self.path);
610    }
611}
612
613#[doc(hidden)]
614pub struct ExecutionLeaseGuard {
615    _lease: crate::driver::ExecutionLease,
616}
617
618#[doc(hidden)]
619pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
620    Ok(ExecutionLeaseGuard {
621        _lease: crate::driver::maintenance(home, run_id)?,
622    })
623}
624
625/// Holds the mutable runner as well as its durable lease: cancellation must
626/// clear both copies of ownership, including state a caller may save later.
627struct DriverExecution<'a> {
628    runner: &'a mut Runner,
629    driver: crate::driver::DriverGuard,
630}
631
632impl Drop for DriverExecution<'_> {
633    fn drop(&mut self) {
634        self.driver.release_local(&mut self.runner.state);
635    }
636}
637
638fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
639    if let Some(startup) = &mut state.startup {
640        startup.stage = stage.to_owned();
641    }
642    state.save()
643}
644
645/// Keep a reservation visible as blocked until startup finishes. A killed process
646/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
647struct StartupGuard {
648    id: String,
649    armed: bool,
650}
651
652impl StartupGuard {
653    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
654        state.startup = Some(crate::run::Startup {
655            kind: kind.to_owned(),
656            branch: branch.map(str::to_owned),
657            stage: "reserved".to_owned(),
658            complete: false,
659            failure: None,
660        });
661        state.status = RunStatus::Blocked;
662        state.reserve()?;
663        Ok(Self {
664            id: state.id.clone(),
665            armed: true,
666        })
667    }
668
669    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
670        startup_stage(state, stage)
671    }
672
673    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
674        let result = result.and_then(|()| {
675            state.startup.as_mut().expect("reserved startup").complete = true;
676            state.save()
677        });
678        self.armed = false;
679        match result {
680            Ok(()) => Ok(()),
681            Err(error) => {
682                let startup = state.startup.as_mut().expect("reserved startup");
683                startup.complete = false;
684                startup.failure = Some(format!("{error:#}"));
685                let context = crate::run::StartupFailure {
686                    run: state.id.clone(),
687                    stage: startup.stage.clone(),
688                };
689                // Repository assets may remain. Never infer that a failed startup
690                // is safe to resume or that an earlier owner has been restored.
691                state.status = RunStatus::Failed;
692                state.driver_exited = true;
693                state.event(
694                    "startup-failed",
695                    format!("{context}: {error:#}; retained assets require inspection"),
696                );
697                if let Err(save) = state.save() {
698                    tracing::warn!(
699                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
700                        state.id
701                    );
702                }
703                Err(error.context(context))
704            }
705        }
706    }
707}
708
709impl Drop for StartupGuard {
710    fn drop(&mut self) {
711        if self.armed
712            && let Ok(mut state) = RunState::load(&self.id)
713        {
714            state.status = RunStatus::Blocked;
715            state.driver_exited = true;
716            if let Some(startup) = &mut state.startup {
717                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
718            }
719            state.event(
720                "startup-interrupted",
721                "startup did not finish; inspect retained assets before recovery",
722            );
723            if let Err(error) = state.save() {
724                tracing::error!(
725                    "could not record interrupted startup {}: {error:#}",
726                    self.id
727                );
728            }
729        }
730    }
731}
732
733impl Runner {
734    /// A queue-side failure after construction must not strand an unexecuted run.
735    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
736        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
737            return error;
738        }
739        if let Some(startup) = &mut self.state.startup {
740            startup.stage = stage.to_owned();
741        } else {
742            // A resumed run already has execution history: do not rewrite it.
743            return error;
744        }
745        StartupGuard {
746            id: self.state.id.clone(),
747            armed: true,
748        }
749        .finish(&mut self.state, Err(error))
750        .expect_err("startup failed")
751    }
752
753    /// Start a fresh run against `repo`.
754    pub async fn start(
755        repo: &Path,
756        instruction: String,
757        config: Config,
758        origin: Origin,
759    ) -> Result<Self> {
760        Self::start_naming(repo, instruction, "", config, origin).await
761    }
762
763    /// [`Runner::start`] for a queued task. Titles and instructions never
764    /// select implementation sources. The title argument is retained for callers.
765    pub async fn start_naming(
766        repo: &Path,
767        instruction: String,
768        _also_scan: &str,
769        config: Config,
770        origin: Origin,
771    ) -> Result<Self> {
772        let repo = git::toplevel(repo).await?;
773        let missing = agent::missing_programs(&config.agents);
774        if !missing.is_empty() {
775            bail!(
776                "these agent programs are not on PATH: {}. Fix the roster in \
777                 magi.toml or install them.",
778                missing.join(", ")
779            );
780        }
781        let base_branch =
782            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
783                .await?;
784        let fetched_base = resolve_base(
785            &repo,
786            &base_branch,
787            &config.merge.remote,
788            config.coordination.as_ref(),
789        )
790        .await?;
791        let base_commit = fetched_base.commit.clone();
792        let roles = config.resolve_roles()?;
793        let max_parallel = config.graph.max_parallel.max(1);
794        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
795        // Capture task identity and repository assignment before the first
796        // save, so publication scope survives crashes and later task moves.
797        state.fetched_base = Some(fetched_base);
798        state.set_origin(origin)?;
799        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
800        state.status = RunStatus::Prep;
801        state.event("start", format!("run {} created", state.id));
802        startup.finish(&mut state, Ok(()))?;
803        Ok(Self {
804            state,
805            roles,
806            sem: Arc::new(Semaphore::new(max_parallel)),
807            pause: Pause::new(),
808            interrupt: Pause::new(),
809        })
810    }
811
812    /// Open a review-only run against work that already exists on `branch`.
813    ///
814    /// The expensive half of the graph is the implement wave — measured at
815    /// 111 and 134 internal tool-loop turns on this repository, against a
816    /// handful for a judge or a reviewer. The cheap half is worth running on
817    /// hand-written work too, and there was no way to reach it.
818    ///
819    /// No new state and no schema change are needed: a run with **one** viable
820    /// candidate and a tally already decided degrades `execute` to exactly
821    /// review → gate → merge, because `judge` skips a single-candidate field,
822    /// `deliberate` has fewer than two first choices to reconcile, `vote`
823    /// returns early, `tally` is already present and `fold_losers` has no
824    /// losers. Resuming such a run therefore does the right thing as well.
825    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
826        Self::review_taking_over(repo, branch, config, None, origin).await
827    }
828
829    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
830    /// at the same task still has `branch` checked out, its worktree is
831    /// released first if that is safe (see [`crate::handover`]), and the
832    /// review refuses with the reason if it is not. `None` is a hand-run
833    /// review: it has no earlier attempts, so only a worktree of a dead run
834    /// magi recorded itself can be released.
835    pub async fn review_taking_over(
836        repo: &Path,
837        branch: &str,
838        config: Config,
839        takeover: Option<crate::handover::Takeover>,
840        origin: Origin,
841    ) -> Result<Self> {
842        let repo = git::toplevel(repo).await?;
843        let missing = agent::missing_programs(&config.agents);
844        if !missing.is_empty() {
845            bail!(
846                "these agent programs are not on PATH: {}. Fix the roster in \
847                 magi.toml or install them.",
848                missing.join(", ")
849            );
850        }
851        let base_branch =
852            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
853                .await?;
854        if base_branch == branch {
855            bail!("`{branch}` is the base branch; there is nothing to review against");
856        }
857        let fetched_base = resolve_base(
858            &repo,
859            &base_branch,
860            &config.merge.remote,
861            config.coordination.as_ref(),
862        )
863        .await?;
864        let base_commit = fetched_base.commit.clone();
865
866        let roles = config.resolve_roles()?;
867        let max_parallel = config.graph.max_parallel.max(1);
868        let mut state = RunState::new(
869            repo.clone(),
870            base_branch,
871            base_commit.clone(),
872            format!("Review the work already on branch `{branch}`."),
873            config,
874        );
875        state.fetched_base = Some(fetched_base);
876        state.set_origin(origin)?;
877        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
878        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
879        let opened = async {
880            startup.stage(&mut state, "handover")?;
881
882            // Released before anything else touches the branch: a stale local
883            // branch is moved with `git branch -f`, which git refuses while an
884            // earlier attempt's worktree still has it checked out. Everything
885            // after this point that can fail puts the old run back.
886            // A hand-run review has no task, hence no earlier attempts, but a
887            // worktree of a dead run magi made may still be released.
888            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
889                earlier: Vec::new(),
890                home: crate::run::home(),
891                choice: None,
892                task_instruction: None,
893            });
894            let wait = repository_wait(&state, None);
895            let coordination_config = state.config.coordination.clone();
896            let coordination =
897                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
898                    .await?;
899            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
900            if let Some(released) = &released {
901                state.event(
902                    "release",
903                    format!(
904                        "took `{branch}` over from run {}: its worktree was released: {}",
905                        crate::run::short_of(&released.old_id),
906                        released.audit
907                    ),
908                );
909            }
910            let opened = async {
911                startup.stage(&mut state, "review-preflight")?;
912                // The owner's answer to an earlier divergence question is applied
913                // here: after the release (git will not move a checked-out branch)
914                // and before the sync that would otherwise ask again.
915                state.foreign_checkout = crate::handover::preflight_review(
916                    &repo,
917                    branch,
918                    &takeover.home,
919                    &state.config.merge.remote,
920                )
921                .await?;
922                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
923                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
924                }
925                if let Some(choice) = takeover.choice.as_ref()
926                    && let Err(e) =
927                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
928                            .await
929                {
930                    return Err(e.context("applying the owner's answer about the diverged branch"));
931                }
932                // An earlier attempt of this task that published the task head, and
933                // whose work is the branch under review, hands that head over: the
934                // review run updates the same pull request. Without one (a legacy
935                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
936                // own head and its own open pull request is adopted as before.
937                for id in takeover.earlier.iter().rev() {
938                    if let Ok(old) = RunState::load_under(id, &takeover.home)
939                        && let Some(head) = old.pr_head.clone()
940                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
941                    {
942                        state.pr_head = Some(head);
943                        break;
944                    }
945                }
946                drop(coordination);
947                startup.stage(&mut state, "open-review")?;
948                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
949            }
950            .await;
951            if opened.is_err()
952                && let Some(released) = &released
953            {
954                // Restoration is ownership checked and best effort. Keep the original
955                // startup cause even if reacquiring coordination is no longer possible.
956                match crate::repo_lock::SeatLease::operation_with(
957                    &repo,
958                    coordination_config.as_ref(),
959                    &wait,
960                )
961                .await
962                {
963                    Ok(_coordination) => {
964                        released.restore(&repo, branch).await;
965                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
966                            .map(|old| {
967                                format!(
968                                    "predecessor released_to={:?}; candidate path exists={}",
969                                    old.released_to,
970                                    old.candidates.iter().any(|c| {
971                                        c.branch == branch && c.worktree.exists()
972                                    }),
973                                )
974                            })
975                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
976                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
977                    }
978                    Err(error) => {
979                        tracing::warn!(
980                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
981                            state.id
982                        );
983                        state.event(
984                            "startup-restore",
985                            format!("restoration not attempted: {error:#}"),
986                        );
987                    }
988                }
989            }
990            opened
991        }
992        .await;
993        startup.finish(&mut state, opened)?;
994        Ok(Self {
995            state,
996            roles,
997            sem: Arc::new(Semaphore::new(max_parallel)),
998            pause: Pause::new(),
999            interrupt: Pause::new(),
1000        })
1001    }
1002
1003    /// Recover exactly the operator-selected public implementation, without touching old sources.
1004    pub async fn recover_pr(
1005        repo: &Path,
1006        task: &str,
1007        selection: crate::pr_recovery::Selection,
1008        mut config: Config,
1009    ) -> Result<Self> {
1010        selection.configure(&mut config)?;
1011        let assignment = crate::run::task_assignment_for(task)?;
1012        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1013        let base_branch =
1014            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1015                .await?;
1016        let fetched_base = resolve_base(
1017            repo,
1018            &base_branch,
1019            &config.merge.remote,
1020            config.coordination.as_ref(),
1021        )
1022        .await?;
1023        let base_commit = fetched_base.commit.clone();
1024        selection
1025            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1026            .await?;
1027        Box::pin(selection.verify_source(repo)).await?;
1028        if let Some(proof) = &selection.source_proof {
1029            anyhow::ensure!(
1030                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1031                "source rebase base is outside the fetched landing base"
1032            );
1033        }
1034        let roles = config.resolve_roles()?;
1035        let max_parallel = config.graph.max_parallel.max(1);
1036        let mut state = RunState::new(
1037            repo.to_path_buf(),
1038            base_branch,
1039            base_commit.clone(),
1040            selection.instruction.clone(),
1041            config,
1042        );
1043        state.fetched_base = Some(fetched_base);
1044        state.set_origin(crate::run::Origin::queue(task))?;
1045        state.pr_head = Some(selection.branch.clone());
1046        state.pr_recovery = Some(selection.clone());
1047        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1048    }
1049
1050    async fn open_selected(
1051        repo: &Path,
1052        mut state: RunState,
1053        roles: ResolvedRoles,
1054        max_parallel: usize,
1055        base_commit: String,
1056        selection: crate::pr_recovery::Selection,
1057    ) -> Result<Self> {
1058        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1059        let opened = async {
1060            startup.stage(&mut state, "predecessors")?;
1061            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1062            startup.stage(&mut state, "open-selected")?;
1063            let branch = state.branch_for('A');
1064            let wait = repository_wait(&state, None);
1065            let prepared = async {
1066                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1067                git::git(repo, &["branch", &branch, selection.source()]).await?;
1068                drop(coordination);
1069                anyhow::Ok(())
1070            }
1071            .await;
1072            prepared?;
1073            state.event(
1074                "recovery",
1075                format!(
1076                    "selected implementation {} for {} (public lease {})",
1077                    selection.source(),
1078                    selection.url,
1079                    selection.head
1080                ),
1081            );
1082            let takeover = crate::handover::Takeover {
1083                earlier: Vec::new(),
1084                home: crate::run::home(),
1085                choice: None,
1086                task_instruction: Some(selection.instruction.clone()),
1087            };
1088            state.save()?;
1089            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1090        }
1091        .await;
1092        startup.finish(&mut state, opened)?;
1093        Ok(Self {
1094            state,
1095            roles,
1096            sem: Arc::new(Semaphore::new(max_parallel)),
1097            pause: Pause::new(),
1098            interrupt: Pause::new(),
1099        })
1100    }
1101
1102    /// What the newest earlier attempt that reviewed `branch` leaves for this
1103    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1104    /// no earlier attempts. Reads the earlier record only: ownership of its
1105    /// worktree and branch is [`crate::handover`]'s business.
1106    async fn inherit(
1107        repo: &Path,
1108        branch: &str,
1109        base_commit: &str,
1110        takeover: &crate::handover::Takeover,
1111    ) -> Option<crate::recovery::RecoveryRecord> {
1112        use crate::recovery::{Relation, assess};
1113        let newest = takeover.earlier.last()?;
1114        let mut chosen = None;
1115        for id in takeover.earlier.iter().rev() {
1116            if let Ok(old) = RunState::load_under(id, &takeover.home)
1117                && !old.reviews.is_empty()
1118                && (old.winner().is_some_and(|w| w.branch == branch)
1119                    || old.pr_head.as_deref() == Some(branch))
1120            {
1121                chosen = Some(old);
1122                break;
1123            }
1124        }
1125        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1126            .await
1127            .unwrap_or_default();
1128        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1129            Some(last) if last.head == tip => Relation::Same,
1130            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1131            _ => Relation::Diverged,
1132        };
1133        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1134        Some(assess(from, chosen.as_ref(), base_commit, relation))
1135    }
1136
1137    /// The half of [`Runner::review_taking_over`] that can fail after an
1138    /// earlier attempt's worktree was released.
1139    async fn open_review(
1140        repo: &Path,
1141        branch: &str,
1142        state: &mut RunState,
1143        base_commit: String,
1144        takeover: &crate::handover::Takeover,
1145    ) -> Result<()> {
1146        startup_stage(state, "review-sync")?;
1147        let wait = repository_wait(state, None);
1148        let _coordination = coordinate_operation(state, repo, &wait).await?;
1149        if state.foreign_checkout.is_some() {
1150            // Never reconcile or force-move a ref checked out by the operator.
1151            if state.pr_head.is_none() {
1152                state.pr_head = Some(branch.to_owned());
1153            }
1154        } else if state.pr_recovery.is_none() {
1155            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1156        }
1157        // The commit subjects are the closest thing to a task statement that
1158        // existing work carries, and the reviewers are told as much.
1159        let start = review_base(
1160            repo,
1161            &state.config.merge.remote,
1162            &state.base_branch,
1163            &base_commit,
1164            branch,
1165        )
1166        .await;
1167        let log = git::log_oneline(repo, &start, branch)
1168            .await
1169            .unwrap_or_default();
1170        let log_text = if log.trim().is_empty() {
1171            "(no commit messages)"
1172        } else {
1173            log.trim()
1174        };
1175        let mut instruction = format!(
1176            "Review the work already on branch `{branch}`. There is no task \
1177             statement: what the change claims to do is whatever its commits \
1178             say.\n\n{log_text}"
1179        );
1180        // A retry of a task whose earlier attempt left reviews behind carries
1181        // that attempt's evidence, and the task's own statement with it: the
1182        // completion criteria are the task's, not whatever the commits claim.
1183        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1184            if let Some(task) = takeover
1185                .task_instruction
1186                .as_deref()
1187                .filter(|t| !t.trim().is_empty())
1188                && rec.reviewed_head.is_some()
1189            {
1190                instruction = format!(
1191                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1192                    task.trim()
1193                );
1194                rec.criteria_inherited = true;
1195            }
1196            state.event("recovery", rec.summary());
1197            state.recovery = Some(rec);
1198        }
1199        if let Some(selected) = &state.pr_recovery {
1200            instruction = selected.instruction.clone();
1201        }
1202        state.task_instruction = takeover.task_instruction.clone();
1203        state.instruction = instruction;
1204        state.reviewed_commits = Some(
1205            git::subjects(repo, &start, branch)
1206                .await
1207                .unwrap_or_default(),
1208        );
1209
1210        // A takeover must not forget a hold that a previous review observed,
1211        // even if repairs have since removed it from the branch.
1212        for id in &takeover.earlier {
1213            if let Ok(old) = RunState::load_under(id, &takeover.home)
1214                && old.repo == state.repo
1215                && (old.pr_head.as_deref() == Some(branch)
1216                    || old.winner().is_some_and(|w| w.branch == branch))
1217            {
1218                for hold in old.branch_owner_holds {
1219                    if !state.branch_owner_holds.contains(&hold) {
1220                        state.event(
1221                            "approval-policy",
1222                            format!(
1223                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1224                                hold.control.key(),
1225                                hold.file,
1226                                hold.head
1227                            ),
1228                        );
1229                        state.branch_owner_holds.push(hold);
1230                    }
1231                }
1232            }
1233        }
1234        // Select the actual review tip before observing owner policy. A foreign
1235        // checkout can lag its remote descendant, and repairs must not erase
1236        // holds introduced only on that selected commit.
1237        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1238            let tracking = format!("{}/{branch}", state.config.merge.remote);
1239            // A surviving tracking ref is not evidence that the remote still
1240            // offers this tip. Adopt it only after a successful fetch here.
1241            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1242            let mut head = checkout.synced_head.clone();
1243            if matches!(fetched, Ok(out) if out.ok()) {
1244                let remote = git::rev_parse(repo, &tracking).await?;
1245                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1246                    head = remote;
1247                }
1248            }
1249            head
1250        } else {
1251            git::rev_parse(repo, branch).await?
1252        };
1253        state.observe_branch_owner_holds(&reviewed_head).await;
1254
1255        // An attached worktree, so the fixer's commits land on the branch under
1256        // review rather than on a detached head nobody will look at again.
1257        let worktree = state.worktree_root().join("under-review");
1258        if let Some(parent) = worktree.parent() {
1259            tokio::fs::create_dir_all(parent).await.ok();
1260        }
1261        let path = worktree.to_string_lossy().to_string();
1262        let review_branch = if state.foreign_checkout.is_some() {
1263            let shadow = format!("magi/{}/review", state.short());
1264            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1265            shadow
1266        } else {
1267            branch.to_owned()
1268        };
1269        startup_stage(state, "review-checkout")?;
1270        git::git(repo, &["worktree", "add", &path, &review_branch])
1271            .await
1272            .with_context(|| {
1273                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1274            })?;
1275
1276        startup_stage(state, "worktree-setup")?;
1277        let setup = match ensure_setup_config(state, repo).await {
1278            Ok(()) => {
1279                worktree_setup::prepare_with(
1280                    &state.config,
1281                    repo,
1282                    &worktree,
1283                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1284                )
1285                .await
1286            }
1287            Err(e) => Err(e),
1288        };
1289        if let Err(e) = setup {
1290            git::worktree_remove_clean(repo, &worktree).await.ok();
1291            return Err(e);
1292        }
1293        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1294            .await
1295            .unwrap_or(0);
1296        if commits == 0 {
1297            git::worktree_remove_clean(repo, &worktree).await.ok();
1298            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1299        }
1300        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1301            .await
1302            .map(|f| f.len())
1303            .unwrap_or(0);
1304        if files == 0
1305            && let (Ok(head_tree), Ok(base_tree)) = (
1306                git::tree_of(&worktree, "HEAD").await,
1307                git::tree_of(&worktree, &base_commit).await,
1308            )
1309            && head_tree == base_tree
1310        {
1311            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1312            git::worktree_remove_clean(repo, &worktree).await.ok();
1313            bail!(
1314                "`{branch}` at {} has a tree identical to base {}; this usually means \
1315                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1316                 against `{}/{branch}`) rather than an empty change",
1317                short(&head),
1318                short(&base_commit),
1319                state.config.merge.remote
1320            );
1321        }
1322        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1323            .await
1324            .unwrap_or_default();
1325
1326        state.candidates.push(Candidate {
1327            index: 0,
1328            label: 'A',
1329            // Not an agent id on purpose: nothing in the roster wrote this, and
1330            // the stats tables must not credit anyone with a win for it.
1331            agent: EXISTING_BRANCH.to_owned(),
1332            branch: review_branch,
1333            worktree,
1334            summary: String::new(),
1335            stat,
1336            files,
1337            commits,
1338            empty: false,
1339            failed: None,
1340            verified_noop: None,
1341            duration_ms: 0,
1342            folded: false,
1343        });
1344        state.tally = Some(Tally {
1345            first_choice: BTreeMap::from([('A', 0)]),
1346            borda: BTreeMap::new(),
1347            winner: 'A',
1348            rankings: 0,
1349            unanimous_initial: false,
1350            deliberated: false,
1351            changed_votes: 0,
1352            unanimous_final: false,
1353            tie_break: None,
1354            // No panel sat, so no quorum applies. Zero judges is the correct
1355            // number for work that never competed, and must not be reported as
1356            // a collapsed panel.
1357            judges: 0,
1358            present: 0,
1359            quorum: 0,
1360            met_quorum: true,
1361            uncontested: Some("review-only run: nothing competed".to_owned()),
1362        });
1363        state.status = RunStatus::Reviewing;
1364        state.prep_complete = Some(true);
1365        state.event(
1366            "start",
1367            format!(
1368                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1369                state.id
1370            ),
1371        );
1372        Ok(())
1373    }
1374
1375    /// Authorize one bounded synchronization interval, under the caller's queue task
1376    /// claim and the same owner/execution locks used by run maintenance.
1377    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1378        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1379    }
1380
1381    /// Authorize a known preparation failure against the inspected evidence.
1382    pub async fn authorize_base_preparation_recovery(
1383        home: &Path,
1384        id: &str,
1385        task: &str,
1386        digest: &str,
1387    ) -> Result<()> {
1388        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1389    }
1390
1391    /// Queue release uses its durable approval generation exactly once.
1392    pub(crate) async fn authorize_base_recovery_from_resumption(
1393        home: &Path,
1394        id: &str,
1395        task: &str,
1396    ) -> Result<()> {
1397        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1398    }
1399
1400    pub(crate) async fn authorize_base_recovery_control(
1401        home: &Path,
1402        task: &str,
1403        control: &mut crate::base_recovery_control::Transaction,
1404    ) -> Result<()> {
1405        let id = control.request.run.clone();
1406        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1407    }
1408
1409    async fn authorize_base_recovery_request(
1410        home: &Path,
1411        id: &str,
1412        task: &str,
1413        resumption: bool,
1414        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1415        terminal_digest: Option<&str>,
1416    ) -> Result<()> {
1417        let _owner = crate::pr_head::owner_lock(home, id)?;
1418        let mut state = RunState::load_under(id, home)?;
1419        crate::pr_head::ensure_owner(&state)?;
1420        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1421        anyhow::ensure!(
1422            queued.execution_runs().last().is_some_and(|run| run == id)
1423                && queued.assignment_accepts(&state)
1424                && queued.status != crate::queue::TaskStatus::Done
1425                && !queued.fresh_start
1426                && queued.review_branch.is_none(),
1427            "run task ownership changed"
1428        );
1429        anyhow::ensure!(
1430            state
1431                .origin
1432                .as_ref()
1433                .and_then(|o| o.task.as_deref())
1434                .is_none_or(|owner| owner == task),
1435            "run belongs to another task"
1436        );
1437        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1438        anyhow::ensure!(
1439            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1440            "run is live or its ownership is unknown"
1441        );
1442        // Judge the previous driver's lease before acquiring our maintenance
1443        // lease. The owner lock excludes new driver claims across both steps.
1444        let _execution = crate::driver::maintenance(home, id)?;
1445        anyhow::ensure!(
1446            state.status.resumable()
1447                && state.released_to.is_none()
1448                && state.retired_to.is_none()
1449                && state.pr_taken_over_by.is_none(),
1450            "run ownership is final"
1451        );
1452        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1453        anyhow::ensure!(
1454            !state.pr_publication_pending
1455                && !crate::handover::landing_checkpoint(&state)
1456                && state.merge_decision.is_none(),
1457            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1458        );
1459        let winner = state.winner().context("run has no retained winner")?;
1460        anyhow::ensure!(
1461            git::is_clean(&winner.worktree).await?,
1462            "retained worktree has uncommitted changes"
1463        );
1464        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1465        anyhow::ensure!(
1466            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1467            "retained worktree does not match the winner branch"
1468        );
1469        if let Some(control) = control.as_ref() {
1470            anyhow::ensure!(
1471                head.starts_with(&control.request.head),
1472                "retained HEAD changed since the owner request"
1473            );
1474            anyhow::ensure!(
1475                state
1476                    .base_sync_recovery
1477                    .stop
1478                    .as_ref()
1479                    .is_none_or(|stop| stop.head == head),
1480                "retained HEAD differs from the recorded stop head; inspect it first"
1481            );
1482        }
1483        anyhow::ensure!(
1484            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1485            "{}",
1486            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1487        );
1488        state.ensure_base_episode();
1489        state.record_base_sync_stop(&head);
1490        let preparation = state.unknown_preparation_stop(&head);
1491        anyhow::ensure!(
1492            state
1493                .base_sync_recovery
1494                .stop
1495                .as_ref()
1496                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1497                || (preparation && !resumption),
1498            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1499        );
1500        let fetched =
1501            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1502        anyhow::ensure!(
1503            fetched.ok(),
1504            "cannot authorize base recovery without a fetched base"
1505        );
1506        let approved_tip = git::rev_parse(
1507            &state.repo,
1508            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1509        )
1510        .await?;
1511        let preparation_digest = state.preparation_digest(&head);
1512        anyhow::ensure!(
1513            preparation
1514                || (terminal_digest.is_none()
1515                    && control
1516                        .as_ref()
1517                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1518            "preparation evidence digest does not name an eligible preparation stop"
1519        );
1520        if preparation {
1521            anyhow::ensure!(
1522                crate::daemon::compatible_run_instruction(&state, &queued),
1523                "task instruction does not match the retained run"
1524            );
1525            if let Some(control) = control.as_ref() {
1526                anyhow::ensure!(
1527                    control.request.head == head
1528                        && control.request.evidence_digest.is_some()
1529                        && control.request.evidence_digest == preparation_digest
1530                        && control.request.decision.is_none(),
1531                    "preparation stop requires the full HEAD and current inspected evidence digest"
1532                );
1533            } else {
1534                anyhow::ensure!(
1535                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1536                    "preparation stop requires the current inspected evidence digest"
1537                );
1538            }
1539            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1540            anyhow::ensure!(
1541                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1542                "current base does not descend from the stopped base"
1543            );
1544            git::probe_rebase_preparation(
1545                &state,
1546                &head,
1547                &home.join("runs").join(id),
1548                &repository_wait(&state, None),
1549            )
1550            .await?;
1551        }
1552        if let Some(control) = control.as_deref_mut() {
1553            let queue = crate::queue::Queue::at(home.join("queue"));
1554            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1555            if let Some(prior) = state
1556                .base_sync_recovery
1557                .authorizations
1558                .iter()
1559                .find(|a| a.request.as_deref() == Some(&control.key()))
1560            {
1561                anyhow::ensure!(
1562                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1563                    "recovery request was consumed or invalidated; it cannot queue again"
1564                );
1565                return control.enqueue(&queue);
1566            }
1567        }
1568        if resumption {
1569            anyhow::ensure!(
1570                crate::daemon::compatible_run_instruction(&state, &queued),
1571                "resumption instruction does not match the retained run"
1572            );
1573            let approval = queued
1574                .resumption
1575                .as_ref()
1576                .context("no operator resumption")?;
1577            anyhow::ensure!(
1578                approval.instruction == queued.instruction,
1579                "resumption approval does not match the current task instruction"
1580            );
1581            state.authorize_base_sync_resumption(task, approval)?;
1582        } else {
1583            state.authorize_base_sync(task)?;
1584        }
1585        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1586        state
1587            .base_sync_recovery
1588            .authorizations
1589            .last_mut()
1590            .unwrap()
1591            .scope = Some(crate::base_sync_recovery::Scope {
1592            tip: approved_tip,
1593            instruction: queued.instruction.clone(),
1594            episode,
1595            preparation_digest,
1596        });
1597        if let Some(control) = control.as_deref_mut() {
1598            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1599            authorization.request = Some(control.key());
1600            authorization.generation = control.generation();
1601            authorization.decision = control.decision();
1602            authorization.question = control
1603                .request
1604                .decision
1605                .as_ref()
1606                .map(|_| control.request.request.clone());
1607        }
1608        state.event(
1609            "base-recovery",
1610            if preparation {
1611                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1612            } else {
1613                "owner authorized a bounded base synchronization interval; fresh verification required"
1614            },
1615        );
1616        state.save_under(home)?;
1617        if let Some(control) = control {
1618            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1619        }
1620        Ok(())
1621    }
1622
1623    /// Reopen an existing run.
1624    pub fn resume(id: &str) -> Result<Self> {
1625        let state = RunState::load(id)?;
1626        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1627        if state.startup.as_ref().is_some_and(|s| !s.complete)
1628            || (state.status == RunStatus::Prep
1629                && state.instruction.trim().is_empty()
1630                && state.candidates.is_empty()
1631                && state.prep_complete == Some(false))
1632        {
1633            bail!(
1634                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1635            );
1636        }
1637        crate::pr_head::ensure_owner(&state)?;
1638        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1639            bail!(
1640                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1641            );
1642        }
1643        if let Some(to) = &state.released_to {
1644            bail!(
1645                "run {} cannot be resumed: its worktree was released to run {}",
1646                state.short(),
1647                crate::run::short_of(to)
1648            );
1649        }
1650        let roles = state.config.resolve_roles()?;
1651        if let Some(id) = &state.config.graph.selected_implementer
1652            && state.candidates.iter().any(|c| c.agent != *id)
1653        {
1654            bail!(
1655                "replacement implementer pin does not match the saved candidates; task must stay held"
1656            );
1657        }
1658        let max_parallel = state.config.graph.max_parallel.max(1);
1659        Ok(Self {
1660            state,
1661            roles,
1662            sem: Arc::new(Semaphore::new(max_parallel)),
1663            pause: Pause::new(),
1664            interrupt: Pause::new(),
1665        })
1666    }
1667
1668    /// Walk the graph to a terminal state, skipping nodes already recorded.
1669    ///
1670    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1671    /// the phone - ends here, so this is the one place a run that ended
1672    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1673    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1674    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1675        // Allocate before polling: boxing inside an async wrapper would still
1676        // retain its construction frame while the nested graph is polled.
1677        Box::pin(self.execute_inner(None))
1678    }
1679
1680    pub(crate) async fn execute_sync_only(
1681        &mut self,
1682        request: crate::base_sync_only::Request,
1683    ) -> Result<()> {
1684        Box::pin(self.execute_inner(Some(request))).await
1685    }
1686
1687    async fn execute_inner(
1688        &mut self,
1689        sync_only: Option<crate::base_sync_only::Request>,
1690    ) -> Result<()> {
1691        anyhow::ensure!(
1692            self.state.startup.as_ref().is_none_or(|s| s.complete),
1693            "startup incomplete; inspect retained evidence before explicit recovery"
1694        );
1695        if let Some(selection) = &self.state.pr_recovery
1696            && (selection.source_proof.is_some() || selection.source_run.is_some())
1697        {
1698            Box::pin(selection.verify_source(&self.state.repo)).await?;
1699        }
1700        // Queue claims cover daemon work; this also serializes manual drivers
1701        // consuming a repair answer, including the new review and decision.
1702        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1703            || self.state.land_approval.is_some()
1704            || self.state.merge_decision.is_some()
1705            || !self.state.merge_repairs.is_empty()
1706            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1707        {
1708            let claim = FixClaim::acquire(&self.state.dir())?;
1709            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1710            let disk = RunState::load(&self.state.id)?;
1711            let checkpoint = |s: &RunState| {
1712                (
1713                    s.merge_repairs.len(),
1714                    s.merge_repairs
1715                        .last()
1716                        .map(|r| (r.question.clone(), r.phase)),
1717                    s.land_approval
1718                        .as_ref()
1719                        .map(|a| (a.question.clone(), a.head.clone())),
1720                )
1721            };
1722            if checkpoint(&disk) != checkpoint(&self.state) {
1723                bail!(
1724                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1725                );
1726            }
1727            Some(claim)
1728        } else {
1729            None
1730        };
1731        let base_only = sync_only.is_some();
1732        let mut execution = self.claim_driver(sync_only).await?;
1733        let runner = &mut *execution.runner;
1734        let wait = runner.repository_wait();
1735        // Keep the graph's large future off the callers' stack, including
1736        // standalone task attempts running on a default-sized test thread.
1737        let result = if base_only {
1738            wait.scope(Box::pin(async {
1739                let repo = runner.state.repo.clone();
1740                let result = async {
1741                    let _coordination = runner.coordinate(&repo).await?;
1742                    anyhow::ensure!(
1743                        !runner.pause.parked() && !runner.interrupt.parked(),
1744                        "paused before base synchronization"
1745                    );
1746                    crate::base_sync_only::sync(&mut runner.state).await
1747                }
1748                .await;
1749                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1750                pass.result = match result {
1751                    Ok(outcome) => outcome,
1752                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1753                };
1754                let summary = pass.summary();
1755                runner.state.event("base-sync-only", summary);
1756                runner.state.save()
1757            }))
1758            .await
1759        } else {
1760            wait.scope(Box::pin(runner.execute_graph())).await
1761        };
1762        let result = match result {
1763            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1764                record_repository_block(&mut runner.state, &e);
1765                runner.park_here()?;
1766                Ok(())
1767            }
1768            other => other,
1769        };
1770        execution.driver.finish(&mut runner.state).await?;
1771        let ended = if result.is_err() {
1772            Some({
1773                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1774                if let Err(error) = &result {
1775                    notice.message = format!(
1776                        "Run {} stopped with an error: {}",
1777                        runner.state.id,
1778                        error.to_string().lines().next().unwrap_or("unknown error")
1779                    );
1780                }
1781                notice
1782            })
1783        } else {
1784            crate::notices::run_ended(&runner.state)
1785        };
1786        if let Some(notice) = ended {
1787            crate::notices::raise(notice);
1788        }
1789        result
1790    }
1791
1792    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1793        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1794    }
1795
1796    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1797        let wait = self.repository_wait();
1798        coordinate_operation(&mut self.state, cwd, &wait).await
1799    }
1800
1801    /// Validate ownership and persist the driver claim in one critical section.
1802    async fn claim_driver(
1803        &mut self,
1804        sync_only: Option<crate::base_sync_only::Request>,
1805    ) -> Result<DriverExecution<'_>> {
1806        let owner = match crate::pr_head::owner_lock_wait(
1807            &crate::run::home(),
1808            &self.state.id,
1809            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1810        )
1811        .await
1812        {
1813            Ok(owner) => owner,
1814            Err(error) => {
1815                let detail = format!("worktree maintenance or ownership update: {error:#}");
1816                // Admission did not own run.json: retain this resource outcome
1817                // in memory for queue settlement without overwriting a concurrent
1818                // retirement or publication transaction.
1819                self.state.resource_block = Some(crate::run::ResourceBlock {
1820                    cause: crate::run::ResourceBlockCause::Other,
1821                    node: "start".into(),
1822                    kind: "worktree maintenance".into(),
1823                    detail: detail.clone(),
1824                    at: Timestamp::now(),
1825                });
1826                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1827            }
1828        };
1829        let disk = RunState::load(&self.state.id)?;
1830        crate::pr_head::ensure_owner(&disk)?;
1831        let now = Timestamp::now();
1832        let home = crate::run::home();
1833        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1834        let assessment = disk.assess_liveness_under(&home, claim, now);
1835        // Only proven-live ownership refuses here. Unknown records (legacy runs
1836        // with no claim marker or process identity) fall through to the
1837        // exclusive execution lease taken just below, which is what actually
1838        // keeps a second driver out.
1839        anyhow::ensure!(
1840            assessment.verdict != crate::run::Liveness::Live,
1841            "{}",
1842            assessment.live_driver_refusal()
1843        );
1844        if let Some(to) = &disk.released_to {
1845            bail!(
1846                "run {} cannot continue: its worktree was released to run {}",
1847                self.state.short(),
1848                crate::run::short_of(to)
1849            );
1850        }
1851        anyhow::ensure!(
1852            serde_json::to_value(&disk.base_sync_recovery)?
1853                == serde_json::to_value(&self.state.base_sync_recovery)?,
1854            "base recovery changed since this run was loaded; reload the saved run"
1855        );
1856        anyhow::ensure!(
1857            disk.sync_only_passes == self.state.sync_only_passes,
1858            "base-only synchronization changed since this run was loaded; reload the saved run"
1859        );
1860        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1861        let mut execution = DriverExecution {
1862            runner: self,
1863            driver,
1864        };
1865        // Declare after the execution guard: on any claim error this short
1866        // lock must drop before that guard reloads and releases ownership.
1867        let _owner = owner;
1868        if let Some(request) = sync_only {
1869            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1870            anyhow::ensure!(
1871                request.run == disk.id,
1872                "sync-base-only request targets a different run"
1873            );
1874            let state = &mut execution.runner.state;
1875            let task_entry = state.next_pass_task_entry;
1876            *state = disk;
1877            state.next_pass_task_entry = task_entry;
1878            if state.pending_sync_only().is_some() {
1879                let pass_index = state.passes.len();
1880                let pass = state.sync_only_passes.last_mut().unwrap();
1881                anyhow::ensure!(
1882                    pass.request == request,
1883                    "interrupted base-only synchronization belongs to a different request"
1884                );
1885                pass.pass_index = pass_index;
1886            } else {
1887                let pass = crate::base_sync_only::Pass::new(request, state);
1888                state.sync_only_passes.push(pass);
1889            }
1890            if state.status == RunStatus::Failed {
1891                state.status = RunStatus::Blocked;
1892            }
1893        } else {
1894            anyhow::ensure!(
1895                disk.pending_sync_only().is_none(),
1896                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1897            );
1898            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1899                .await?;
1900        }
1901        let state = &mut execution.runner.state;
1902        // Moving again, so it is no longer parked. Set before the walk rather
1903        // than in `resume`, so every way of re-entering the graph clears it
1904        // and a card cannot claim a run is waiting to be resumed while the
1905        // agents are already working.
1906        state.parked = false;
1907        state.resource_wait = None;
1908        state.resource_block = None;
1909        // Any seat this state still lists as answering belongs to whatever
1910        // process last drove this run — this one included, if it crashed
1911        // mid-wave. Cleared and flushed immediately, before anything else
1912        // runs, so a resume can never show a seat as live when nothing is
1913        // asking it anything yet; the node that actually dispatches the next
1914        // wave repopulates it.
1915        state.clear_active();
1916        // Recorded in the same spot, and flushed together with the clear
1917        // above: this is the pid a reader checks (`RunState::liveness`) when
1918        // no daemon claim exists to answer "is a process still driving this
1919        // run" — a plain `magi run` / `magi review` typed into a terminal
1920        // claims nothing there. Always overwritten, never only-if-absent, so
1921        // a resumed run's stale pid from a previous, possibly-dead process
1922        // can never survive into this one's own report. Unlike
1923        // `clear_active`, this changes on every single `execute()` call, so
1924        // the save below is now unconditional rather than only-if-cleared.
1925        //
1926        // `driver_started_at` is recorded in the same breath, from this same
1927        // pid, so `liveness` can tell a live pid that is genuinely still us
1928        // apart from one the OS has since handed to an unrelated process —
1929        // see that field's own doc for why the pid alone is not enough.
1930        let pid = std::process::id();
1931        state.driver_pid = Some(pid);
1932        state.driver_started_at = crate::proc::process_started_at(pid);
1933        state.driver_exited = false;
1934        state.driver_claimed = Some(true);
1935        state.begin_pass();
1936        execution.driver.bind(state);
1937        state.save()?;
1938        execution.driver.record(state)?;
1939        Ok(execution)
1940    }
1941
1942    /// No conflict checkpoint proves dispatch was never reached. End that
1943    /// consumed generation so an owner can explicitly authorize a fresh one.
1944    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1945        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1946        if let Err(error) = &result
1947            && !error.is::<crate::repo_lock::ResourceBlocked>()
1948            && self
1949                .state
1950                .repair_grants
1951                .last()
1952                .is_some_and(|g| g.conflict.is_none())
1953        {
1954            self.state.repair_grants.last_mut().unwrap().phase =
1955                crate::repair_budget::Phase::Complete;
1956            self.state.status = RunStatus::Blocked;
1957            self.state.save()?;
1958            bail!(
1959                "{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",
1960                self.state.passes.last().map_or(0, |p| p.index)
1961            );
1962        }
1963        result
1964    }
1965
1966    /// A grant owns only these repair attempts. Confirmation reviews cannot
1967    /// create another fixer allowance, and every operation is restart-checkpointed.
1968    async fn execute_granted_repair(&mut self) -> Result<()> {
1969        use crate::repair_budget::{Kind, Phase};
1970        let index = self.state.repair_grants.len() - 1;
1971        let winner = self
1972            .state
1973            .winner()
1974            .cloned()
1975            .context("repair winner missing")?;
1976        loop {
1977            let grant = self.state.repair_grants[index].clone();
1978            match grant.phase {
1979                Phase::Pending => {
1980                    if grant.spent >= grant.receipt.request.rounds {
1981                        self.state.repair_grants[index].phase = Phase::Complete;
1982                        self.state.status = RunStatus::Blocked;
1983                        self.state.save()?;
1984                        return Ok(());
1985                    }
1986                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
1987                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
1988                            .await?;
1989                    }
1990                    // Reserve before dispatch. A crash can consume an attempt,
1991                    // but can never duplicate it or reset saved fixer history.
1992                    self.state.repair_grants[index].spent += 1;
1993                    self.state.repair_grants[index].phase = Phase::Fixing;
1994                    self.state.save()?;
1995                    match grant.receipt.request.kind {
1996                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1997                        Kind::Gate => {
1998                            let failed = self.state.gate.clone();
1999                            let _ = self.gate_fix_round(&winner, &failed).await?;
2000                        }
2001                        Kind::Review => {
2002                            let mut record = self
2003                                .state
2004                                .reviews
2005                                .last()
2006                                .cloned()
2007                                .context("review failure missing")?;
2008                            let round = record.round;
2009                            let step = self.run_fix_round(&winner, &mut record).await?;
2010                            self.state.reviews[round - 1] = record;
2011                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2012                                self.state.repair_grants[index].phase = Phase::Complete;
2013                                self.state.status = RunStatus::Blocked;
2014                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2015                                self.state.save()?;
2016                                return Ok(());
2017                            }
2018                            if matches!(step, FixStep::Resource) {
2019                                self.stop_for_resource()?;
2020                                return Ok(());
2021                            }
2022                            self.state.save()?;
2023                        }
2024                    }
2025                    if self.resource_halt()? {
2026                        return Ok(());
2027                    }
2028                }
2029                Phase::Fixing => {
2030                    if grant.receipt.request.kind == Kind::BaseConflict {
2031                        self.repair_base_conflict(false).await?;
2032                    }
2033                    // Interrupted fixers may have left source changes or an
2034                    // unpushed commit. Preserve them before fresh assessment.
2035                    let _coordination = self.coordinate(&winner.worktree).await?;
2036                    let rescued = git::rescue_commit(
2037                        &winner.worktree,
2038                        "magi: preserve interrupted granted repair",
2039                    )
2040                    .await?;
2041                    self.state.note_withheld("repair-grant", &rescued.withheld);
2042                    // Fresh checks must supersede even a same-head failure.
2043                    // Archive rather than erase failure evidence or counters.
2044                    self.state
2045                        .verification_history
2046                        .push(crate::run::VerificationEvidence {
2047                            superseded_by: None,
2048                            archived_at: Some(Timestamp::now()),
2049                            fixes_spent: Some(self.state.gate_fixes.len()),
2050                            gate_head: self.state.gate_head.take(),
2051                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2052                            gate: std::mem::take(&mut self.state.gate),
2053                            e2e: self.state.head_e2e.take(),
2054                        });
2055                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2056                        self.state
2057                            .verification_history
2058                            .push(crate::run::VerificationEvidence {
2059                                superseded_by: None,
2060                                archived_at: Some(Timestamp::now()),
2061                                fixes_spent: Some(self.state.gate_fixes.len()),
2062                                gate_head: None,
2063                                gate_ran: false,
2064                                gate: Vec::new(),
2065                                e2e: Some(e2e),
2066                            });
2067                    }
2068                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2069                    self.state.repair_grants[index].head =
2070                        git::rev_parse(&winner.worktree, "HEAD").await?;
2071                    self.state.repair_grants[index].phase = Phase::Reviewing;
2072                    if grant.receipt.request.kind == Kind::BaseConflict {
2073                        self.state.base_sync_recovery.stop = None;
2074                        if let Some(sync) = &mut self.state.base_sync {
2075                            sync.tip = grant
2076                                .receipt
2077                                .request
2078                                .tip
2079                                .clone()
2080                                .context("repair base tip missing")?;
2081                            sync.conflict = None;
2082                            sync.behind = 0;
2083                        }
2084                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2085                    }
2086                    self.state.save()?;
2087                }
2088                Phase::Reviewing => {
2089                    self.review_loop_pass().await?;
2090                    if self.resource_halt()? {
2091                        return Ok(());
2092                    }
2093                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2094                    let reviewed = (self.state.reviews.len() > grant.review_start)
2095                        .then(|| self.state.reviews.last())
2096                        .flatten();
2097                    let review_passed = reviewed.is_some_and(|r| {
2098                        r.clean
2099                            && r.expected > 0
2100                            && r.answered == r.expected
2101                            && matches!(
2102                                r.e2e_status(),
2103                                E2eStatus::Passed | E2eStatus::NotConfigured
2104                            )
2105                            && ((r.e2e_status() == E2eStatus::NotConfigured
2106                                && self.state.config.verify.e2e.is_empty())
2107                                || r.verified_head.as_deref() == Some(head.as_str()))
2108                    });
2109                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2110                    if !clean {
2111                        let next = if review_passed
2112                            && let Some(r) = reviewed
2113                            && r.head != head
2114                        {
2115                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2116                                &self.state,
2117                                r,
2118                                &head,
2119                            )
2120                            .await
2121                            .map(|_| Some(Phase::Reviewing))
2122                        } else if grant.receipt.request.kind == Kind::Review
2123                            && grant.spent < grant.receipt.request.rounds
2124                        {
2125                            crate::repair_budget::prove_review_target(&self.state, &head)
2126                                .await
2127                                .map(|_| Some(Phase::Pending))
2128                        } else {
2129                            Ok(None)
2130                        };
2131                        let next = match next {
2132                            Ok(next) => next,
2133                            Err(error) => {
2134                                if self.state.repair_grants[index]
2135                                    .checkpoint_provenance_retry(&head, &error)
2136                                {
2137                                    self.state.status = RunStatus::Blocked;
2138                                    self.state.event("repair-grant", format!(
2139                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2140                                    ));
2141                                    self.state.save()?;
2142                                    return Ok(());
2143                                }
2144                                None
2145                            }
2146                        };
2147                        if next == Some(Phase::Reviewing) {
2148                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2149                            self.state.repair_grants[index].head = head;
2150                            self.state.repair_grants[index].phase = Phase::Reviewing;
2151                            self.state.status = RunStatus::Blocked;
2152                            self.state.event(
2153                                "repair-grant",
2154                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2155                            );
2156                            self.state.save()?;
2157                            return Ok(());
2158                        }
2159                        // A confirmation review carries no additional fix budget.
2160                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2161                            self.state.repair_grants[index].head = head;
2162                            Phase::Pending
2163                        } else {
2164                            Phase::Complete
2165                        };
2166                        self.state.status = RunStatus::Blocked;
2167                        self.state.event(
2168                            "repair-grant",
2169                            "fresh review did not clear the repaired head; no publication",
2170                        );
2171                        self.state.save()?;
2172                        if self.state.repair_grants[index].phase == Phase::Pending {
2173                            continue;
2174                        }
2175                        return Ok(());
2176                    }
2177                    self.state.repair_grants[index].phase = Phase::Gating;
2178                    self.state.save()?;
2179                }
2180                Phase::Gating => {
2181                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2182                    self.state.reconcile_verification_head(&head);
2183                    let wait = self.repository_wait();
2184                    if self
2185                        .state
2186                        .reviews
2187                        .last()
2188                        .is_none_or(|r| r.head != head || !r.clean)
2189                    {
2190                        self.state.status = RunStatus::Blocked;
2191                        self.state.repair_grants[index].phase = Phase::Complete;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "head changed since fresh review; repair held",
2195                        );
2196                        self.state.save()?;
2197                        return Ok(());
2198                    }
2199                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2200                        return Ok(());
2201                    }
2202                    let outcomes = self.run_gate(&winner).await?;
2203                    if verify_inconclusive(&outcomes) {
2204                        return Ok(());
2205                    }
2206                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    if after != head {
2208                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2209                        self.state.repair_grants[index].head = after;
2210                        self.state.repair_grants[index].phase = Phase::Reviewing;
2211                        self.state.status = RunStatus::Blocked;
2212                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2213                        self.state.save()?;
2214                        return Ok(());
2215                    }
2216                    let passed = outcomes.iter().all(CommandOutcome::ok);
2217                    // Follow-up grants owe the same guarded checkout delivery
2218                    // as the conflict repair that introduced the new head.
2219                    if passed
2220                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2221                    {
2222                        return Ok(());
2223                    }
2224                    self.state.repair_grants[index].succeeded = passed;
2225                    self.state.gate = outcomes;
2226                    self.state.gate_ran = true;
2227                    self.state.status = if passed {
2228                        RunStatus::Gating
2229                    } else {
2230                        RunStatus::Blocked
2231                    };
2232                    self.state.repair_grants[index].phase = if !passed
2233                        && grant.receipt.request.kind == Kind::Gate
2234                        && grant.spent < grant.receipt.request.rounds
2235                    {
2236                        Phase::Pending
2237                    } else {
2238                        Phase::Complete
2239                    };
2240                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2241                        // Persist publication debt with the successful checkpoint.
2242                        self.state.pr_publication_pending = true;
2243                    } else if passed {
2244                        self.state.status = RunStatus::Ready;
2245                    }
2246                    self.state.save()?;
2247                    if !passed {
2248                        continue;
2249                    }
2250                    // Existing PR ownership and push lease stay in place. The
2251                    // normal publisher owes the new reviewed/gated SHA, and
2252                    // land's fresh owner approval remains mandatory.
2253                    if self.state.config.merge.mode != MergeMode::Pr {
2254                        self.state.status = RunStatus::Ready;
2255                        self.state.event(
2256                            "repair-grant",
2257                            "repair verified locally; grant carries no merge authorization",
2258                        );
2259                        self.state.save()?;
2260                        return Ok(());
2261                    }
2262                    return self.merge().await;
2263                }
2264                Phase::Complete => return Ok(()),
2265            }
2266        }
2267    }
2268
2269    async fn execute_graph(&mut self) -> Result<()> {
2270        // Even a terminal run may reenter through an explicit recovery action.
2271        // Restore before prep shortcuts, saved conversations or graph nodes use
2272        // a disposable path; GC may already have removed its original objects.
2273        let archive_home = crate::run::home().canonicalize()?;
2274        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2275            let repo = self.state.repo.clone();
2276            let _coordination = self.coordinate(&repo).await?;
2277            ensure_setup_config(&mut self.state, &repo).await?;
2278            crate::retention::restore_execution_seats(
2279                &archive_home,
2280                &self.state,
2281                _coordination.as_ref(),
2282            )
2283            .await?;
2284        }
2285        self.state.configure_recovery_resume()?;
2286        if self
2287            .state
2288            .repair_grants
2289            .last()
2290            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2291        {
2292            return self.execute_granted_repair().await;
2293        }
2294        if self
2295            .state
2296            .repair_grants
2297            .last()
2298            .is_some_and(|g| !g.succeeded)
2299        {
2300            self.state.status = RunStatus::Blocked;
2301            self.state.save()?;
2302            return Ok(());
2303        }
2304        // Preservation may invalidate an old empty classification. Resolve it
2305        // before any resume shortcut can reuse a verdict or publish a branch.
2306        self.persist_candidates().await?;
2307        // A saved base stop outranks stage markers, including legacy Voting.
2308        // Recovery never reenters implementation, deliberation or voting.
2309        if self.state.base_sync_blocked() {
2310            self.sync_to_base().await?;
2311            if !self.state.base_sync_blocked()
2312                && self.state.status != RunStatus::AlreadyInBase
2313                && !self.resource_halt()?
2314            {
2315                self.finish_after_tally().await?;
2316            }
2317            return Ok(());
2318        }
2319        if self
2320            .state
2321            .merge_decision
2322            .as_ref()
2323            .is_some_and(|decision| !decision.closed)
2324            && self.state.status != RunStatus::Landing
2325        {
2326            if crate::merge_decision::resumable_hold(&self.state) {
2327                self.state.merge = Some(MergeOutcome {
2328                    mode: MergeMode::Pr,
2329                    ok: false,
2330                    detail: self
2331                        .state
2332                        .merge_decision
2333                        .as_ref()
2334                        .unwrap()
2335                        .target
2336                        .pr
2337                        .clone(),
2338                    empty: false,
2339                });
2340                self.run_land().await?;
2341                self.settle_questions();
2342                return Ok(());
2343            }
2344            bail!(
2345                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2346            );
2347        }
2348        if self.state.config.graph.selected_implementer.is_some()
2349            && self.state.status == RunStatus::Blocked
2350            && self.state.tally.is_none()
2351            && self.state.candidate_preservation.is_empty()
2352            && self.state.interrupted_implementations.is_empty()
2353        {
2354            bail!(
2355                "selected implementation is held; explicitly release the owning task to retry it"
2356            );
2357        }
2358
2359        if self.state.merge_repairs.last().is_some_and(|r| {
2360            matches!(
2361                r.phase,
2362                crate::run::MergeRepairPhase::Requested
2363                    | crate::run::MergeRepairPhase::Fixing
2364                    | crate::run::MergeRepairPhase::Reviewing
2365            )
2366        }) {
2367            if self.repair_merge_review().await? {
2368                self.run_land().await?;
2369            }
2370            self.settle_questions();
2371            return Ok(());
2372        }
2373        // Publication already passed review and gate. Resume only that node:
2374        // syncing to a newer base here could change the verified commit.
2375        if self.state.pr_publication_pending {
2376            self.merge().await?;
2377            if self.resource_halt()? {
2378                return Ok(());
2379            }
2380            self.state.save()?;
2381            self.settle_questions();
2382            return Ok(());
2383        }
2384        // A run that already lost its quorum never resumes into the verdict
2385        // machinery: `deliberate` and `vote` would otherwise clobber the
2386        // stalled marker back to Voting and the run would keep going past a
2387        // verdict that is no longer trustworthy. Everything already recorded is
2388        // kept, so the run stays resumable (or foldable) for a human to pick up.
2389        //
2390        // On --resume the run gets one chance to repair itself: the seats a
2391        // rate limit took out are re-asked. If their quota has since reset and
2392        // the quorum is restored, the run picks up and finishes; otherwise it
2393        // stays stale and still-resumable for a later retry. If it does not
2394        // recover, the returned status stays `Stalled` and nothing was
2395        // clobbered (the recovery only mutates entries for the lost seats).
2396        if self.state.status == RunStatus::Stalled {
2397            if self.recover_stall().await? {
2398                self.finish_after_tally().await?;
2399            } else {
2400                // Still below quorum: persist the marker and stay resumable.
2401                self.state.save()?;
2402            }
2403            return Ok(());
2404        }
2405        // A run parked inside `land` - watching CI, mid fix-round, or
2406        // waiting on the owner's merge approval - resumes directly into it,
2407        // never back through `prep`. Everything before `merge` already
2408        // concluded; that is the only way `status` reaches `Landing` in the
2409        // first place. Re-walking `review_loop` first would also be actively
2410        // wrong: its own status recomputation (see its doc) treats any
2411        // clean round as reason to set `status` to `Gating`, which would
2412        // clobber this marker before `merge` ever ran, and this run would
2413        // never find its way back into `land` at all.
2414        if self.state.status == RunStatus::Landing
2415            || crate::handover::landing_checkpoint(&self.state)
2416        {
2417            self.state.land_sync_pending = true;
2418            self.state.save()?;
2419            self.run_land().await?;
2420            // `run_land` may have settled the run right here - CI came back
2421            // green and the PR merged, say - without ever passing back
2422            // through `merge`'s own trailing call. Whatever it left `status`
2423            // as is what this has to read.
2424            self.settle_questions();
2425            return Ok(());
2426        }
2427        // A run parked at `merge` on the owner's word about a withheld PR text
2428        // resumes straight into `merge`. Re-walking the tail would sync to the
2429        // base again (possibly rebasing, possibly spending the fixer) after the
2430        // gate had passed, and then push a tree nobody reviewed or gated.
2431        if self.state.github_text.is_some()
2432            && self.state.merge.is_none()
2433            && self.state.status == RunStatus::Gating
2434        {
2435            self.merge().await?;
2436            if self.resource_halt()? {
2437                return Ok(());
2438            }
2439            self.state.save()?;
2440            return Ok(());
2441        }
2442        // A resource stop left the reserved synchronization unfinished. Reconcile
2443        // its exact HEAD and base before starting any earlier graph stage.
2444        if self.state.pending_base_operation().is_some() {
2445            return self.finish_after_tally().await;
2446        }
2447        if let Err(e) = self.prep().await {
2448            if e.is::<crate::repo_lock::ResourceBlocked>() {
2449                return Err(e);
2450            }
2451            self.state.status = RunStatus::Blocked;
2452            self.state
2453                .prep_failure
2454                .get_or_insert_with(|| format!("{e:#}"));
2455            self.state
2456                .event("prep", format!("preparation stopped: {e:#}"));
2457            self.state.save()?;
2458            return Err(e);
2459        }
2460        if self.park_here()? {
2461            return Ok(());
2462        }
2463        self.advise().await?;
2464        if self.park_here()? {
2465            return Ok(());
2466        }
2467        self.implement().await?;
2468        if self.park_here()? {
2469            return Ok(());
2470        }
2471        // `after_implement` already saved the state and settled any open
2472        // questions when it set this; nothing later in the graph has
2473        // anything to judge.
2474        if self.state.status == RunStatus::VerifiedNoop {
2475            return Ok(());
2476        }
2477        self.judge().await?;
2478        if self.park_here()? {
2479            return Ok(());
2480        }
2481        self.deliberate().await?;
2482        if self.park_here()? {
2483            return Ok(());
2484        }
2485        self.vote().await?;
2486        if self.park_here()? {
2487            return Ok(());
2488        }
2489        self.tally()?;
2490        // A verdict that lost its quorum is not trustworthy: do not review,
2491        // gate, or merge on it. Everything already done is kept, so the run
2492        // stays resumable (or foldable); the human can replace the agent that
2493        // ran out of quota and pick it up.
2494        if self.state.status == RunStatus::Stalled {
2495            // Persist the stalled marker now — the normal end-of-execute save
2496            // below is below this early return, and without it a resumed run
2497            // would reload a pre-tally status and keep going.
2498            self.state.save()?;
2499            return Ok(());
2500        }
2501        self.finish_after_tally().await?;
2502        Ok(())
2503    }
2504
2505    /// A wave could not start its agents because a shared resource stayed busy
2506    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2507    /// resumable. Unstarted seats have no result; completed peers retain
2508    /// their saved candidate state.
2509    fn stop_for_resource(&mut self) -> Result<()> {
2510        // Resource acquisition observes cancellation inside a node. Complete
2511        // the same durable park as every other node boundary before returning.
2512        if self.pause.parked() || self.interrupt.parked() {
2513            self.park_here()?;
2514            return Ok(());
2515        }
2516        if self.state.resource_block.is_some() {
2517            self.state.status = RunStatus::Blocked;
2518        }
2519        self.state.save()
2520    }
2521
2522    /// Stop walking the graph if a node ended on a resource block.
2523    fn resource_halt(&mut self) -> Result<bool> {
2524        if self.state.resource_block.is_none() {
2525            return Ok(false);
2526        }
2527        self.stop_for_resource()?;
2528        Ok(true)
2529    }
2530
2531    /// Park here if asked to, recording it in the run's own timeline.
2532    ///
2533    /// Returns whether the caller should stop walking the graph. The state is
2534    /// saved either way by the node that just finished; this adds the event so
2535    /// the operator's card says why a run that is neither finished nor moving
2536    /// is sitting where it is.
2537    fn park_here(&mut self) -> Result<bool> {
2538        let parking = self.pause.parked() || self.interrupt.parked();
2539        if !parking && self.state.resource_block.is_some() {
2540            self.stop_for_resource()?;
2541            return Ok(true);
2542        }
2543        // Either handle asking is enough - see `Pause`'s own doc for why
2544        // they are never the same one. `interrupt` is checked second so a
2545        // reason it carries is preferred in the message below over a plain
2546        // shutdown park racing it at the same boundary.
2547        if !self.pause.parked() && !self.interrupt.parked() {
2548            return Ok(false);
2549        }
2550        if self.state.parked {
2551            return Ok(true);
2552        }
2553        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2554        if let Some(block) = &mut self.state.resource_block
2555            && matches!(
2556                block.cause,
2557                crate::run::ResourceBlockCause::Cancelled { .. }
2558            )
2559        {
2560            block.cause = crate::run::ResourceBlockCause::Cancelled {
2561                park: cause.clone(),
2562            };
2563        }
2564        let why = match cause.as_ref().map(ParkCause::label) {
2565            Some(reason) => format!(
2566                "parked after `{}` ({reason}) — resume to carry on from here",
2567                self.state.status.as_str()
2568            ),
2569            None => format!(
2570                "parked after `{}` — resume to carry on from here",
2571                self.state.status.as_str()
2572            ),
2573        };
2574        self.state.event("park", why);
2575        self.state
2576            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2577        self.state.parked = true;
2578        self.state.save()?;
2579        Ok(true)
2580    }
2581
2582    /// Only a new explicit operator approval may retry failed preparation.
2583    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2584        if self.state.prep_failure.is_none() {
2585            return Ok(());
2586        }
2587        let failed_at = self
2588            .state
2589            .events
2590            .iter()
2591            .rev()
2592            .find(|event| event.node == "prep")
2593            .map_or(self.state.updated_at, |event| event.at);
2594        anyhow::ensure!(
2595            approval_at > failed_at,
2596            "preparation retry requires a new explicit release after the failure"
2597        );
2598        self.state.prep_failure = None;
2599        self.state.prep_complete = Some(false);
2600        self.state
2601            .event("prep-retry", "operator approved retry of preparation");
2602        Ok(())
2603    }
2604
2605    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2606    pub fn on_pause(&mut self, pause: Pause) {
2607        self.pause = pause;
2608    }
2609
2610    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2611    /// scheduler asking this one run - and no other - to park so a task
2612    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2613    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2614    /// handle.
2615    pub fn watch_interrupt(&mut self, pause: Pause) {
2616        self.interrupt = pause;
2617    }
2618
2619    /// Abandon this run's own open questions, once `status` has actually
2620    /// settled rather than merely paused.
2621    ///
2622    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2623    /// either back up with the candidates, the review round and the seat
2624    /// sessions already on disk, so a question an implementer asked mid-round
2625    /// may still get a real answer read by a real resume. Only the statuses
2626    /// `resumable` excludes are actually final: the run merged, it reached
2627    /// `Ready` with nothing left to do, it failed outright with no
2628    /// established point to continue from, or every candidate agreed, with
2629    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2630    /// every one of those the seat that asked is gone for good, exactly like
2631    /// the run being deleted under `magi run rm` - so the same cleanup
2632    /// applies, worded for what actually happened instead of "the run was
2633    /// deleted".
2634    ///
2635    /// Best-effort and silent on success: called from every place `status`
2636    /// can land on one of those three, including ones a resumed run revisits,
2637    /// so it must cost nothing when there was nothing open to begin with.
2638    fn settle_questions(&mut self) {
2639        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2640            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2641        }
2642    }
2643
2644    /// The tail of the graph after a trustworthy tally: fold losers, review,
2645    /// gate, merge, and persist.
2646    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2647        Box::pin(self.finish_after_tally_inner())
2648    }
2649
2650    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2651        // Before the losers are folded: their branches are what the graft
2652        // reads from.
2653        self.graft().await?;
2654        if self.resource_halt()? {
2655            return Ok(());
2656        }
2657        self.fold_losers().await?;
2658        // Before review starts, and again right before the gate: a run's
2659        // review rounds can themselves take long enough for the base to move
2660        // a second time, and the gate is the one node whose "green" gets
2661        // acted on.
2662        self.sync_to_base().await?;
2663        if self.hold_base_sync().await? || self.resource_halt()? {
2664            return Ok(());
2665        }
2666        if self.state.status == RunStatus::AlreadyInBase {
2667            return Ok(());
2668        }
2669        self.review_loop().await?;
2670        if self.resource_halt()? {
2671            return Ok(());
2672        }
2673        self.sync_to_base().await?;
2674        if self.hold_base_sync().await? || self.resource_halt()? {
2675            return Ok(());
2676        }
2677        if self.state.status == RunStatus::AlreadyInBase {
2678            return Ok(());
2679        }
2680        self.gate().await?;
2681        self.merge().await?;
2682        if self.resource_halt()? {
2683            return Ok(());
2684        }
2685        self.state.save()?;
2686        Ok(())
2687    }
2688
2689    // ---------------------------------------------------------------- prep
2690
2691    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2692    /// run with the step and its output in the event; it is never swallowed.
2693    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2694    /// resume starts over instead of finding candidates and missing seats.
2695    async fn setup_seat_worktree(
2696        &mut self,
2697        repo: &Path,
2698        wt: &Path,
2699        in_prep: bool,
2700        coordination: Option<&crate::repo_lock::SeatLease>,
2701    ) -> Result<()> {
2702        let result = match ensure_setup_config(&mut self.state, repo).await {
2703            Ok(()) => {
2704                worktree_setup::prepare_with(
2705                    &self.state.config,
2706                    repo,
2707                    wt,
2708                    crate::build_target::Coordination::Held(coordination),
2709                )
2710                .await
2711            }
2712            Err(e) => Err(e),
2713        };
2714        if let Err(e) = result {
2715            git::worktree_remove_clean(repo, wt).await.ok();
2716            if in_prep {
2717                self.rollback_prep(repo).await;
2718            }
2719            self.state.status = RunStatus::Blocked;
2720            self.state.event(
2721                "setup",
2722                format!("worktree setup failed in {}: {e:#}", wt.display()),
2723            );
2724            self.state.save()?;
2725            return Err(e);
2726        }
2727        Ok(())
2728    }
2729
2730    /// Undo everything `prep` created, so a resume re-runs it whole.
2731    async fn rollback_prep(&mut self, repo: &Path) {
2732        let root = self.state.worktree_root();
2733        for c in std::mem::take(&mut self.state.candidates) {
2734            if matches!(
2735                git::worktree_remove_clean(repo, &c.worktree).await,
2736                Ok(true)
2737            ) {
2738                git::branch_delete(repo, &c.branch).await.ok();
2739            } else {
2740                self.state.candidates.push(c);
2741            }
2742        }
2743        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2744        for j in 1..=seats {
2745            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2746                .await
2747                .ok();
2748        }
2749        for k in 1..=self.state.config.graph.advisors {
2750            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2751                .await
2752                .ok();
2753        }
2754    }
2755
2756    async fn prep(&mut self) -> Result<()> {
2757        if let Some(reason) = &self.state.prep_failure {
2758            bail!(
2759                "candidate preparation previously failed: {reason}; correct the source before retrying"
2760            );
2761        }
2762        if self
2763            .state
2764            .prep_complete
2765            .unwrap_or(!self.state.candidates.is_empty())
2766        {
2767            return Ok(());
2768        }
2769        let repo = self.state.repo.clone();
2770        // Includes rollback, config, refs, checkout creation and setup. No
2771        // repository mutation may precede the real shared lock acquisition.
2772        let _coordination = self.coordinate(&repo).await?;
2773        let base = self.state.base_commit.clone();
2774        let plan = self.state.sources.plan(&repo, &base).await?;
2775        self.rollback_prep(&repo).await;
2776        if !self.state.candidates.is_empty() {
2777            bail!(
2778                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2779            );
2780        }
2781        self.state.prep_complete = Some(false);
2782        self.state.status = RunStatus::Prep;
2783        self.state.save()?;
2784        let repo = self.state.repo.clone();
2785        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2786        let root = self.state.worktree_root();
2787        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2788
2789        // The hook is the write-time half of the blindness contract; the
2790        // presentation filter in `blind` is the half that cannot be bypassed.
2791        let hooks_dir = self.state.dir().join("hooks");
2792        if self.state.config.blind.commit_msg_hook {
2793            std::fs::create_dir_all(&hooks_dir)
2794                .with_context(|| format!("create {}", hooks_dir.display()))?;
2795            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2796            let path = hooks_dir.join("commit-msg");
2797            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2798            make_executable(&path)?;
2799            // Ref-counted rather than a plain idempotent set: with more than
2800            // one run able to be in flight in the same repository at once
2801            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2802            // true?" check cannot tell "another run of mine still needs
2803            // this" from "nobody does", and the run that happens to finish
2804            // first would disable the hook out from under a sibling still
2805            // relying on it.
2806            git::acquire_worktree_config(&repo).await?;
2807            self.state.enabled_worktree_config = true;
2808        }
2809
2810        // `[worktree] setup` hides its products per worktree, which needs the
2811        // same per-worktree config the hook does. Held until fold, like it.
2812        ensure_setup_config(&mut self.state, &repo).await?;
2813
2814        for (index, (spec, label)) in self
2815            .roles
2816            .implementers
2817            .clone()
2818            .into_iter()
2819            .zip(labels)
2820            .enumerate()
2821        {
2822            let branch = self.state.branch_for(label);
2823            let worktree = root.join(format!("cand-{label}"));
2824            // Persist intent before Git can leave a partially created tree.
2825            // Candidate registration follows setup, so it cannot inventory
2826            // crashes or refusals during creation itself.
2827            self.state.event(
2828                "prep-intent",
2829                serde_json::json!({
2830                    "branch": branch,
2831                    "worktree": worktree,
2832                    "start": start,
2833                    "picks": plan.picks,
2834                })
2835                .to_string(),
2836            );
2837            self.state.save()?;
2838            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2839            if self.state.config.blind.commit_msg_hook {
2840                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2841            }
2842            git::local_exclude(&worktree, "/.magi/").await?;
2843            if let Err(e) = worktree_setup::prepare_with(
2844                &self.state.config,
2845                &repo,
2846                &worktree,
2847                crate::build_target::Coordination::Held(_coordination.as_ref()),
2848            )
2849            .await
2850            {
2851                // Nothing of this prep may survive: a resume must start over,
2852                // not find half the candidates and skip the rest.
2853                git::worktree_remove_clean(&repo, &worktree).await.ok();
2854                git::branch_delete(&repo, &branch).await.ok();
2855                self.rollback_prep(&repo).await;
2856                self.state.status = RunStatus::Blocked;
2857                self.state
2858                    .event("prep", format!("worktree setup failed: {e:#}"));
2859                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2860                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2861                }
2862                self.state.save()?;
2863                return Err(e);
2864            }
2865            self.state.candidates.push(Candidate {
2866                index,
2867                label,
2868                agent: spec.id.clone(),
2869                branch,
2870                worktree,
2871                summary: String::new(),
2872                stat: String::new(),
2873                files: 0,
2874                commits: 0,
2875                empty: false,
2876                failed: None,
2877                verified_noop: None,
2878                duration_ms: 0,
2879                folded: false,
2880            });
2881            self.state.save()?;
2882            for pick in &plan.picks {
2883                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2884                {
2885                    self.state.status = RunStatus::Blocked;
2886                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2887                    self.state
2888                        .event("prep", format!("cannot apply referenced commit: {e}"));
2889                    self.state.save()?;
2890                    return Err(e);
2891                }
2892            }
2893        }
2894
2895        for j in 1..=self.roles.judges.len() {
2896            let wt = root.join(format!("judge-{j}"));
2897            if !wt.exists() {
2898                git::worktree_add_detached(&repo, &wt, &base).await?;
2899                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2900                    .await?;
2901            }
2902        }
2903
2904        // Disposable, detached checkouts for the design-deliberation stage's
2905        // advisor seats — the same shape as the judges' above, at the same
2906        // base commit, since advisors also only ever read. Sized off the
2907        // configured count directly rather than a resolved roster: unlike
2908        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2909        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2910        // `prep` has no `ResolvedRoles` field to read a count from here.
2911        if self.state.config.graph.advise {
2912            for k in 1..=self.state.config.graph.advisors {
2913                let wt = root.join(format!("advisor-{k}"));
2914                if !wt.exists() {
2915                    git::worktree_add_detached(&repo, &wt, &base).await?;
2916                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2917                        .await?;
2918                }
2919            }
2920        }
2921
2922        // A judge cannot tell it is looking at its own patch — the seats keep
2923        // separate conversations — but a panel that shares agents with the
2924        // field is less independent than it looks, and that is worth saying out
2925        // loud once per run rather than leaving it in the config.
2926        let authors: Vec<&str> = self
2927            .roles
2928            .implementers
2929            .iter()
2930            .map(|a| a.id.as_str())
2931            .collect();
2932        let overlap: Vec<String> = self
2933            .roles
2934            .judges
2935            .iter()
2936            .enumerate()
2937            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2938            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2939            .collect();
2940        if !overlap.is_empty() {
2941            let note = format!(
2942                "{} also authored a candidate; blind, but the panel is less \
2943                 independent than {} distinct agents would be",
2944                overlap.join(", "),
2945                self.roles.judges.len()
2946            );
2947            self.state.event("prep", note);
2948        }
2949
2950        self.state.event(
2951            "prep",
2952            format!(
2953                "{} candidates, {} judges, base {} ({})",
2954                self.state.candidates.len(),
2955                self.roles.judges.len(),
2956                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2957                self.state.base_branch
2958            ),
2959        );
2960        self.state.prep_complete = Some(true);
2961        self.state.status = RunStatus::Implementing;
2962        self.state.save()?;
2963        Ok(())
2964    }
2965
2966    // -------------------------------------------------------------- advise
2967
2968    /// The design-deliberation stage: independent, read-only advisor seats
2969    /// each sketch a design before any implementer touches the repository,
2970    /// and (when at least one produced a usable proposal) a synthesis seat
2971    /// blends them into a brief `implement` carries in every candidate's
2972    /// prompt.
2973    ///
2974    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2975    /// advisors` is the proposal count. Everything here is best-effort and
2976    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2977    /// that cannot reach quota, or a synthesis seat that produced nothing
2978    /// usable all leave `implement` exactly as it was before this stage
2979    /// existed — the task instruction alone — rather than failing the whole
2980    /// competition over an enrichment stage. Every outcome is still recorded
2981    /// as an event, so a run that got nothing from this stage says why.
2982    ///
2983    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2984    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2985    /// resumed run whose stage failed would re-run it, and re-spend the
2986    /// agent calls, on every reentry before `implement`.
2987    ///
2988    /// Also skipped once any candidate shows implementation progress — the
2989    /// exact predicate `implement` itself uses to decide a candidate is no
2990    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2991    /// is not enough: a run created by an older binary that predates this
2992    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2993    /// an already-`Implementing`-or-later run under this build would
2994    /// otherwise walk straight back through `prep` (a no-op once candidates
2995    /// exist) into this node and spawn every advisor seat against worktrees
2996    /// `prep` never recreated — after implementation has already started,
2997    /// which is exactly the invariant this stage exists to guarantee.
2998    async fn advise(&mut self) -> Result<()> {
2999        let implement_untouched = self
3000            .state
3001            .candidates
3002            .iter()
3003            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3004        if !self.state.config.graph.advise || self.state.advise_attempted {
3005            return Ok(());
3006        }
3007        if !implement_untouched {
3008            self.state.event(
3009                "advise",
3010                "skipping the design-deliberation stage: at least one \
3011                 candidate already shows implementation progress, so this \
3012                 run is past the point the stage exists to run before"
3013                    .to_owned(),
3014            );
3015            self.state.advise_attempted = true;
3016            self.state.save()?;
3017            return Ok(());
3018        }
3019        let run_id = self.state.id.clone();
3020        let prompts = self.state.config.prompts.clone();
3021        let instruction = self.state.instruction.clone();
3022        let language = self.state.config.graph.language.clone();
3023        let root = self.state.worktree_root();
3024        let n = self.state.config.graph.advisors;
3025        let where_recorded = self.state.dir().join("run.json");
3026
3027        let seats = match self.state.config.advisors() {
3028            Ok(seats) if !seats.is_empty() => seats,
3029            Ok(_) => {
3030                self.state.event(
3031                    "advise",
3032                    format!(
3033                        "[graph] advisors is 0; skipping the design-deliberation \
3034                         stage and continuing without a synthesis brief (see {})",
3035                        where_recorded.display()
3036                    ),
3037                );
3038                self.state.advise_attempted = true;
3039                self.state.save()?;
3040                return Ok(());
3041            }
3042            Err(e) => {
3043                self.state.event(
3044                    "advise",
3045                    format!(
3046                        "could not resolve advisor seats ({e:#}); continuing \
3047                         without a design-deliberation brief (see {})",
3048                        where_recorded.display()
3049                    ),
3050                );
3051                self.state.advise_attempted = true;
3052                self.state.save()?;
3053                return Ok(());
3054            }
3055        };
3056
3057        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3058        let artifacts = agent::artifacts_dir(&self.state.dir());
3059        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3060
3061        let mut jobs = Vec::new();
3062        for (i, spec) in seats.iter().cloned().enumerate() {
3063            let seat_key = format!("advisor-{}", i + 1);
3064            let seat = self.seat(&seat_key, &spec.id);
3065            jobs.push(SeatJob {
3066                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3067                spec,
3068                seat,
3069                cwd: worktrees[i % worktrees.len()].clone(),
3070                timeout,
3071                allow_write: false,
3072                sessions: false,
3073                artifacts: artifacts.clone(),
3074                stem: seat_key,
3075                handover: None,
3076            });
3077        }
3078
3079        self.state.event(
3080            "advise",
3081            format!(
3082                "{} advisor seat(s) sketching a design in parallel",
3083                jobs.len()
3084            ),
3085        );
3086        let mut quota_losses = Vec::new();
3087        let cache = self.state.config.cache_dir();
3088        let ctx = WaveCtx {
3089            carry_seats: false,
3090            pauses: Some((&self.pause, &self.interrupt)),
3091            run: &run_id,
3092            node: "advise",
3093            prompts: &prompts,
3094            cache: cache.as_deref(),
3095            round: None,
3096        };
3097        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3098        let results = ask_json_wave::<Proposal>(
3099            jobs,
3100            Arc::clone(&self.sem),
3101            self.state.config.graph.retries,
3102            &advisor_roster,
3103            &ctx,
3104            &mut quota_losses,
3105            &mut self.state,
3106            &|p: &Proposal| p.validate(),
3107        )
3108        .await;
3109        if self.state.resource_block.is_some() {
3110            return self.stop_for_resource();
3111        }
3112        self.state.quota.extend(quota_losses);
3113
3114        let mut records = Vec::with_capacity(results.len());
3115        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3116            let agent_id = seat.agent.clone();
3117            self.state.seats.insert(seat.key.clone(), seat);
3118            match res {
3119                Ok((proposal, out)) => {
3120                    self.state
3121                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3122                    records.push(advise::AdvisorRecord::proposed(
3123                        i + 1,
3124                        agent_id,
3125                        proposal,
3126                        out.duration_ms,
3127                    ));
3128                }
3129                Err(e) => {
3130                    self.state.event(
3131                        "advise",
3132                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3133                    );
3134                    records.push(advise::AdvisorRecord::failed(
3135                        i + 1,
3136                        agent_id,
3137                        e.to_string(),
3138                    ));
3139                }
3140            }
3141        }
3142
3143        let mut advice = advise::Advice {
3144            records,
3145            synthesis: None,
3146        };
3147        if advice.proposals().is_empty() {
3148            self.state.event(
3149                "advise",
3150                "no advisor produced a usable proposal; continuing without a \
3151                 synthesis brief"
3152                    .to_owned(),
3153            );
3154        } else {
3155            match self
3156                .synthesize_brief(
3157                    &advice,
3158                    &instruction,
3159                    &language,
3160                    &worktrees[0],
3161                    &artifacts,
3162                    &run_id,
3163                    &prompts,
3164                    cache.as_deref(),
3165                )
3166                .await
3167            {
3168                Ok(Some(text)) => {
3169                    self.state.event(
3170                        "advise",
3171                        "synthesized a design brief for the implementer".to_owned(),
3172                    );
3173                    advice.synthesis = Some(text);
3174                }
3175                Ok(None) => {
3176                    self.state.event(
3177                        "advise",
3178                        "the synthesis seat produced nothing usable; continuing \
3179                         without a design brief"
3180                            .to_owned(),
3181                    );
3182                }
3183                Err(e) => {
3184                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3185                        return Err(e);
3186                    }
3187                    self.state.event(
3188                        "advise",
3189                        format!("could not synthesize a design brief: {e:#}"),
3190                    );
3191                }
3192            }
3193        }
3194        advise::apply_reflection(&mut advice);
3195
3196        self.state.advice = Some(advice);
3197        self.state.advise_attempted = true;
3198        self.state.save()?;
3199        Ok(())
3200    }
3201
3202    /// The synthesis seat: reads every advisor's proposal and blends them
3203    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3204    /// out of [`Runner::advise`] only for readability — it is not called
3205    /// anywhere else.
3206    ///
3207    /// Picked the same way [`crate::talk`]'s standing conversation and
3208    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3209    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3210    /// order (a claude seat, else the first runnable agent in roster order)
3211    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3212    /// in [`crate::config`] for why a dedicated field exists here at all.
3213    #[allow(clippy::too_many_arguments)]
3214    async fn synthesize_brief(
3215        &mut self,
3216        advice: &advise::Advice,
3217        instruction: &str,
3218        language: &str,
3219        cwd: &Path,
3220        artifacts: &Path,
3221        run_id: &str,
3222        prompts: &Prompts,
3223        cache: Option<&Path>,
3224    ) -> Result<Option<String>> {
3225        let chain = agent::pick_chain(
3226            &self.state.config.agents,
3227            self.state.config.roles.synthesizer.as_ref(),
3228            &agent::installed,
3229            "synthesizer",
3230        )?;
3231        let proposals = advice.proposals();
3232        let mut prompt = prompt::with_overlay(
3233            prompt::synthesize_brief(instruction, &proposals, language),
3234            prompts.overlay("advise"),
3235        );
3236        if cache.is_some() {
3237            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3238            // below — see `prompt::build_cache_note`'s doc for why telling a
3239            // read-only seat to build through the shared cache is exactly how
3240            // a sandbox's write refusal gets misread as a defect.
3241            prompt.push('\n');
3242            prompt.push_str(&prompt::build_cache_note("advise", false));
3243        }
3244        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3245        // Each id is tried once, in order; a quota hit, error or unusable
3246        // answer moves to the next. The seat is single-turn (`sessions:
3247        // false`) and the prompt is the whole context, so a fallback agent
3248        // needs nothing carried over.
3249        let mut last = None;
3250        for (n, spec) in chain.iter().enumerate() {
3251            if n > 0 {
3252                self.state
3253                    .event("advise", format!("synthesis falling back to {}", spec.id));
3254            }
3255            let mut seat = self.seat("advise-synthesis", &spec.id);
3256            let wait = self.repository_wait();
3257            let outcome = wait
3258                .scope(agent::invoke(
3259                    spec,
3260                    &mut seat,
3261                    &Invocation {
3262                        coordination: self.state.config.coordination.as_ref(),
3263                        fetched_base: None,
3264                        cwd,
3265                        prompt: &prompt,
3266                        timeout,
3267                        allow_write: false,
3268                        sessions: false,
3269                        artifacts,
3270                        stem: &if n == 0 {
3271                            "advise-synthesis".to_owned()
3272                        } else {
3273                            format!("advise-synthesis-{}", spec.id)
3274                        },
3275                        run: run_id,
3276                        node: "advise",
3277                        cache_dir: None,
3278                        attachments: &[],
3279                        writable: &[],
3280                    },
3281                ))
3282                .await;
3283            if outcome.is_ok() {
3284                self.state.seats.insert(seat.key.clone(), seat);
3285            }
3286            let advance = agent::chain_advances(&outcome);
3287            last = Some(outcome);
3288            if !advance {
3289                break;
3290            }
3291        }
3292        // Exhausted: the last attempt's result is what a single failed seat
3293        // would have produced.
3294        let out = last.expect("a chain holds at least one agent")?;
3295        if !out.usable() {
3296            return Ok(None);
3297        }
3298        let text =
3299            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3300        Ok((!text.trim().is_empty()).then_some(text))
3301    }
3302
3303    // ----------------------------------------------------------- implement
3304
3305    async fn implement(&mut self) -> Result<()> {
3306        self.persist_candidates().await?;
3307        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3308        // agent files with `magi task add` name the run that paid for it. The
3309        // prompt overlay is cloned alongside it because the waves borrow it
3310        // while `self` is mutably borrowed by the node's own bookkeeping.
3311        let run_id = self.state.id.clone();
3312        let prompts = self.state.config.prompts.clone();
3313        let todo: Vec<usize> = self
3314            .state
3315            .candidates
3316            .iter()
3317            .enumerate()
3318            .filter(|(_, c)| {
3319                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3320                    && c.failed.is_none()
3321                    && !c.empty
3322            })
3323            .map(|(i, _)| i)
3324            .collect();
3325        if todo.is_empty() {
3326            return self.after_implement();
3327        }
3328        self.state.status = RunStatus::Implementing;
3329
3330        let language = self.state.config.graph.language.clone();
3331        let github_language = self.state.config.graph.github_language.clone();
3332        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3333        let sessions = self.state.config.graph.sessions;
3334        let artifacts = agent::artifacts_dir(&self.state.dir());
3335        // The design-deliberation stage's blended brief, when `advise` found
3336        // one — carried into every implementer's prompt the same way
3337        // regardless of which candidate it is.
3338        let brief = self
3339            .state
3340            .advice
3341            .as_ref()
3342            .and_then(|a| a.synthesis.as_deref())
3343            .map(str::to_owned);
3344        let attachments = self.state.attachments.clone();
3345
3346        let mut jobs = Vec::new();
3347        for &i in &todo {
3348            let (index, label, worktree) = {
3349                let c = &self.state.candidates[i];
3350                (c.index, c.label, c.worktree.clone())
3351            };
3352            let spec = self.roles.implementers[index].clone();
3353            let seat_key = format!("impl-{label}");
3354            let seat = self.seat(&seat_key, &spec.id);
3355            let instruction = seeded_instruction(&self.state);
3356            jobs.push(SeatJob {
3357                spec,
3358                seat,
3359                prompt: prompt::implement_in(
3360                    &instruction,
3361                    &worktree.to_string_lossy(),
3362                    &language,
3363                    &github_language,
3364                    brief.as_deref(),
3365                    &attachments,
3366                ),
3367                cwd: worktree,
3368                timeout,
3369                allow_write: true,
3370                sessions,
3371                artifacts: artifacts.clone(),
3372                stem: format!("impl-{label}"),
3373                handover: None,
3374            });
3375        }
3376
3377        self.state.event(
3378            "implement",
3379            format!("{} candidates in parallel", jobs.len()),
3380        );
3381        // Kept so a seat whose CLI hung up can be asked again from the same
3382        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3383        // can update a seat's own entry once a fallback agent takes it over —
3384        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3385        // whichever agent actually answered, not the one that quota'd out.
3386        let mut sent = jobs.clone();
3387        let cache = self.state.config.cache_dir();
3388        let ctx = WaveCtx {
3389            carry_seats: false,
3390            pauses: Some((&self.pause, &self.interrupt)),
3391            run: &run_id,
3392            node: "implement",
3393            prompts: &prompts,
3394            cache: cache.as_deref(),
3395            round: None,
3396        };
3397        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3398        if !wave_blocked(&results) {
3399            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3400                .await;
3401            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3402                .await?;
3403            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3404                .await;
3405        }
3406        // Do not finalize failed candidates when the entire wave needs machine
3407        // recovery: leaving them pending resumes this node with its work intact.
3408        if !results.is_empty()
3409            && results
3410                .iter()
3411                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3412        {
3413            let losses: Vec<_> = results
3414                .iter()
3415                .map(|(_, seat, out)| {
3416                    let AgentOutcome::Quota(o) = out else {
3417                        unreachable!()
3418                    };
3419                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3420                })
3421                .collect();
3422            self.state.quota.extend(losses.clone());
3423            for (_, seat, _) in results {
3424                self.state.seats.insert(seat.key.clone(), seat);
3425            }
3426            for &i in &todo {
3427                let label = self.state.candidates[i].label;
3428                self.state.interrupted_implementations.insert(label);
3429                self.state
3430                    .candidate_preservation
3431                    .insert(label, "machine outage awaiting persistence".into());
3432            }
3433            // Preserve partial edits too, while keeping every interrupted seat
3434            // pending even when its tree already contains an inherited patch.
3435            block_machine_outage(&mut self.state, "implement", &losses);
3436            self.state.save()?;
3437            self.persist_candidates().await?;
3438            for &i in &todo {
3439                self.state
3440                    .interrupted_implementations
3441                    .insert(self.state.candidates[i].label);
3442            }
3443            return self.stop_for_resource();
3444        }
3445        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3446
3447        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3448            && results
3449                .iter()
3450                .any(|(_, _, out)| FailClass::of(out).is_some());
3451        let base_commit = self.state.base_commit.clone();
3452        let blind_cfg = self.state.config.blind.clone();
3453        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3454        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3455            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3456                // Executed turns interrupted by disk pressure already carry
3457                // a preservation barrier from wave. Admission-only waits do
3458                // not. Keep the interrupted seat's session for recovery too.
3459                if self
3460                    .state
3461                    .candidate_preservation
3462                    .contains_key(&self.state.candidates[i].label)
3463                {
3464                    self.state.seats.insert(seat.key.clone(), seat);
3465                }
3466                continue;
3467            }
3468            let seat_key = seat.key.clone();
3469            // A quota fallback (`resume_seat_handovers`) may have handed this
3470            // seat to a different agent than the one `prep` recorded on the
3471            // candidate; the stats tables and any later fixer-defaults-to-
3472            // winner's-author lookup must credit whoever actually answered —
3473            // unless every fallback also quota'd out, in which case nobody
3474            // actually answered and crediting the last agent tried would
3475            // erase every earlier agent's own quota loss from the stats
3476            // tables instead of just this one seat's.
3477            let agent = seat.agent.clone();
3478            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3479            self.state.seats.insert(seat.key.clone(), seat);
3480            let label = self.state.candidates[i].label;
3481            let worktree = self.state.candidates[i].worktree.clone();
3482            self.state.interrupted_implementations.remove(&label);
3483
3484            let (sanitized_summary, duration, failed, verified_claim) = match out {
3485                AgentOutcome::Ok(o) => {
3486                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3487                    let failed = (!o.usable()).then(|| {
3488                        if o.timed_out {
3489                            "agent timed out".to_owned()
3490                        } else {
3491                            format!(
3492                                "agent exited with {}",
3493                                crate::notices::exit_status(o.exit_code)
3494                            )
3495                        }
3496                    });
3497                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3498                    let verified_claim = match verified_noop_claim_in_worktree(
3499                        failed.is_none(),
3500                        &o.commands,
3501                        &text,
3502                        &worktree,
3503                        &base_commit,
3504                    )
3505                    .await
3506                    {
3507                        NoopClaimVerdict::Accepted => {
3508                            if matches!(
3509                                verdict::parse_verified_noop(&sanitized_summary),
3510                                Some(Ok(_))
3511                            ) {
3512                                Some(sanitized_summary.clone())
3513                            } else {
3514                                rejected_noops.push((
3515                                    label,
3516                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3517                                ));
3518                                None
3519                            }
3520                        }
3521                        NoopClaimVerdict::Rejected(reason) => {
3522                            rejected_noops.push((label, reason));
3523                            None
3524                        }
3525                        NoopClaimVerdict::Absent => None,
3526                    };
3527                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3528                }
3529                // Left un-resumed by `resume_undelivered` (a dirty tree
3530                // already rescues the work, or there was no session left to
3531                // resume into) — reported like the ordinary failure it is,
3532                // never as if `o.text` (the CLI's raw error JSON) were an
3533                // answer.
3534                AgentOutcome::Dropped(o) => {
3535                    let why = o
3536                        .dropped
3537                        .as_ref()
3538                        .map(|d| d.why.as_str())
3539                        .unwrap_or("the CLI ended the stream without delivering its answer");
3540                    (
3541                        String::new(),
3542                        o.duration_ms,
3543                        Some(format!("the CLI dropped the stream ({why})")),
3544                        None,
3545                    )
3546                }
3547                AgentOutcome::Quota(o) => {
3548                    self.state.quota.push(QuotaLoss::from_report(
3549                        seat_key,
3550                        "implement",
3551                        o.quota.as_ref(),
3552                    ));
3553                    (
3554                        String::new(),
3555                        o.duration_ms,
3556                        Some("rate limited (quota); produced no change".to_owned()),
3557                        None,
3558                    )
3559                }
3560                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3561                    (String::new(), 0, Some(e), None)
3562                }
3563            };
3564
3565            // Save every completed turn before any fallible Git operation. A failed
3566            // rescue must not erase the reply or prevent collection of other seats.
3567            let c = &mut self.state.candidates[i];
3568            if !exhausted_the_fallback_chain {
3569                c.agent = agent;
3570            }
3571            c.summary = sanitized_summary;
3572            c.duration_ms = duration;
3573            c.failed = failed;
3574            c.verified_noop = verified_claim;
3575            self.state
3576                .candidate_preservation
3577                .insert(label, "awaiting persistence".to_owned());
3578        }
3579        self.state.save()?;
3580        self.persist_candidates().await?;
3581
3582        let mut recorded_rejection = false;
3583        for (label, reason) in rejected_noops {
3584            if self.state.interrupted_implementations.contains(&label) {
3585                continue;
3586            }
3587            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3588                && c.empty
3589            {
3590                c.verified_noop = None;
3591                c.failed
3592                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3593                self.state.event(
3594                    "implement",
3595                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3596                );
3597                recorded_rejection = true;
3598            }
3599        }
3600        if recorded_rejection {
3601            self.state.save()?;
3602        }
3603
3604        if resource_blocked {
3605            return self.stop_for_resource();
3606        }
3607        if selected_failed {
3608            self.state.status = RunStatus::Blocked;
3609            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3610            self.state.save()?;
3611            bail!(
3612                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3613            );
3614        }
3615        self.after_implement()
3616    }
3617
3618    /// Retry only persistence after a completed implementation turn.
3619    async fn persist_candidates(&mut self) -> Result<()> {
3620        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3621        for label in labels {
3622            let i = self
3623                .state
3624                .candidates
3625                .iter()
3626                .position(|c| c.label == label)
3627                .context("pending candidate is missing")?;
3628            let c = self.state.candidates[i].clone();
3629            let interrupted = self.state.interrupted_implementations.contains(&label);
3630            let result = async {
3631                let wait = crate::repo_lock::WaitPolicy::new(
3632                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3633                    || false,
3634                );
3635                let _coordination =
3636                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3637                // Best effort evidence requires no index writes. A successful snapshot
3638                // never authorizes removal of a tree whose rescue failed.
3639                if let Err(e) = git::snapshot_uncommitted(
3640                    &c.worktree,
3641                    &self
3642                        .state
3643                        .dir()
3644                        .join("artifacts")
3645                        .join(format!("candidate-{label}-recovery")),
3646                )
3647                .await
3648                {
3649                    self.state.event(
3650                        "preserve",
3651                        format!("candidate {label} snapshot incomplete: {e:#}"),
3652                    );
3653                }
3654                let rescued = git::rescue_commit(
3655                    &c.worktree,
3656                    &format!("magi: candidate {label} (uncommitted work)"),
3657                )
3658                .await?;
3659                self.state.note_withheld("implement", &rescued.withheld);
3660                let base = &self.state.base_commit;
3661                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3662                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3663                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3664                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3665                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3666                if c.empty && commits > 0 && !patch.trim().is_empty()
3667                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3668                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3669                        || self.state.tally.is_some())
3670                {
3671                    // Keep the old classification and pending marker so every
3672                    // retry stops too. Retain decisions as recovery evidence;
3673                    // only a supported recovery operation may replace them.
3674                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3675                }
3676                let c = &mut self.state.candidates[i];
3677                c.commits = commits;
3678                c.stat = stat;
3679                c.files = files;
3680                let no_changes = commits == 0 || patch.trim().is_empty();
3681                c.empty = no_changes && !interrupted;
3682                if interrupted && no_changes {
3683                    c.failed = None;
3684                    c.verified_noop = None;
3685                }
3686                if !c.empty {
3687                    c.failed = None;
3688                    c.verified_noop = None;
3689                }
3690                self.state.event(
3691                    "preserve",
3692                    format!("candidate {label}: {files} files, {commits} commits"),
3693                );
3694                Ok::<_, anyhow::Error>(())
3695            }
3696            .await;
3697            match result {
3698                Ok(()) => {
3699                    self.state.candidate_preservation.remove(&label);
3700                    if !interrupted || self.state.candidates[i].files > 0 {
3701                        self.state.interrupted_implementations.remove(&label);
3702                    }
3703                }
3704                Err(e) => {
3705                    let reason = format!("candidate {label} preservation failed: {e:#}");
3706                    self.state.event("preserve", &reason);
3707                    self.state.candidate_preservation.insert(label, reason);
3708                }
3709            }
3710            if self.state.candidate_preservation.is_empty()
3711                && self.state.status == RunStatus::Blocked
3712                && self.state.candidates.iter().all(|c| c.failed.is_none())
3713            {
3714                // Persist the recovered phase with the cleared pending marker;
3715                // a crash between saves must not turn this into a selected-seat
3716                // failure hold on the next resume.
3717                self.state.status = RunStatus::Implementing;
3718                self.state.event(
3719                    "preserve",
3720                    "candidate persistence recovered; implementation can continue",
3721                );
3722            }
3723            self.state.save()?;
3724        }
3725        if !self.state.candidate_preservation.is_empty() {
3726            self.state.status = RunStatus::Blocked;
3727            self.state.save()?;
3728            bail!(
3729                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3730            );
3731        }
3732        Ok(())
3733    }
3734
3735    /// Ask again, once, for work a CLI did and then failed to hand over.
3736    ///
3737    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3738    /// status with an empty response and a usage report showing output tokens,
3739    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3740    /// seven minutes and 14,267 output tokens that arrived as an empty
3741    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3742    ///
3743    /// Two conditions, and both matter:
3744    ///
3745    /// - **Only when the tree is untouched.** Often the agent has already
3746    ///   written its files and only the closing message was lost; the rescue
3747    ///   commit below picks that up and there is nothing to ask for. Re-asking
3748    ///   then would pay for a second implementation of work already on disk.
3749    /// - **Once.** A CLI that drops one stream can drop the next, and this
3750    ///   node is the most expensive in the graph.
3751    ///
3752    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3753    /// dropped reply still carried its `conversation_id`, so the seat is asked
3754    /// to finish what it was doing rather than sent the whole task again. It
3755    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3756    /// node's - for the same reason a re-ranked judge does: restating finished
3757    /// work is not the work.
3758    ///
3759    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3760    /// same way until it resets, while an abandoned conversation is still
3761    /// there to be picked up.
3762    async fn resume_undelivered(
3763        &mut self,
3764        results: &mut [(usize, SeatState, AgentOutcome)],
3765        sent: &[SeatJob],
3766        prompts: &Prompts,
3767        run_id: &str,
3768    ) {
3769        for (wi, seat, out) in results.iter_mut() {
3770            let Some(dropped) = (match &*out {
3771                AgentOutcome::Dropped(o) => o.dropped.clone(),
3772                _ => None,
3773            }) else {
3774                continue;
3775            };
3776            let Some(job) = sent.get(*wi) else { continue };
3777            // Already on disk? Then only the closing message was lost.
3778            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3779                self.state.event(
3780                    "implement",
3781                    format!(
3782                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3783                         work is in the tree",
3784                        seat.key, dropped.output_tokens, dropped.why
3785                    ),
3786                );
3787                continue;
3788            }
3789            // The re-ask only makes sense as a resume: `resume_after_drop`
3790            // says nothing about the task, trusting the seat to still hold it.
3791            // Without a session to resume — sessions disabled, or this CLI's
3792            // drop shape happened not to carry a session id — that prompt
3793            // would open a brand-new conversation with no context at all,
3794            // which is worse than leaving this as the ordinary failure it
3795            // already is.
3796            if !has_context(&job.spec, seat, job.sessions) {
3797                self.state.event(
3798                    "implement",
3799                    format!(
3800                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3801                         is no session left to resume",
3802                        seat.key, dropped.output_tokens, dropped.why
3803                    ),
3804                );
3805                continue;
3806            }
3807            self.state.event(
3808                "implement",
3809                format!(
3810                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3811                     conversation",
3812                    seat.key, dropped.output_tokens, dropped.why
3813                ),
3814            );
3815            let mut retry = job.clone();
3816            retry.seat = seat.clone();
3817            retry.prompt = prompt::resume_after_drop(&dropped.why);
3818            retry.timeout = retry_budget(job.timeout, true);
3819            retry.stem = format!("{}-resume", job.stem);
3820            let cache = self.state.config.cache_dir();
3821            let ctx = WaveCtx {
3822                carry_seats: false,
3823                pauses: Some((&self.pause, &self.interrupt)),
3824                run: run_id,
3825                node: "implement",
3826                prompts,
3827                cache: cache.as_deref(),
3828                round: None,
3829            };
3830            let (resumed_seat, resumed) =
3831                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3832            *seat = resumed_seat;
3833            *out = resumed;
3834        }
3835    }
3836
3837    /// Fall an implement seat through to the next untried agent in the
3838    /// implementer roster when it lost to quota — or, since the handover was
3839    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3840    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3841    /// quota path itself being unchanged — instead of leaving the
3842    /// seat's loss final the moment one agent's account runs dry.
3843    ///
3844    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3845    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3846    /// truncates to the single slot rotation picked, so a solo task whose one
3847    /// implementer hits quota mid-run used to have nothing else to try. This
3848    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3849    /// unrotated roster — which is the only place the *other* candidates in
3850    /// the machine's roster still exist once `implementers` has been cut down
3851    /// to size.
3852    ///
3853    /// Walks forward from just past the seat's own original position in the
3854    /// roster, never wrapping back to the front: a later candidate slot (say
3855    /// `beta`, the roster's second entry) must fall through to the *next*
3856    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3857    /// almost certainly a different candidate's own agent already — and once
3858    /// the roster's tail is exhausted there is nothing left to fall through
3859    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3860    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3861    /// let this retry that id forever. The loop keeps falling through until
3862    /// an attempt lands something other than `Quota` or the roster's tail
3863    /// runs out of untried ids, at which point the seat is left exactly as
3864    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3865    /// `QuotaLoss` recorded, the candidate failed/empty.
3866    ///
3867    /// `sent` is taken mutably and updated with the fallback agent's spec:
3868    /// `resume_unconfirmed_commands`, which runs after this and also reads
3869    /// `sent`, must see whichever agent actually ended up answering the seat
3870    /// — reading the stale, original spec there would check session
3871    /// eligibility against the wrong CLI and could hand a fallback agent's
3872    /// session id to the agent that just lost the seat to quota.
3873    ///
3874    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3875    /// — `self.seat` only reuses state when the agent id is unchanged, so
3876    /// handing it a different id already gets this for free. Reusing the old
3877    /// seat would resume a different CLI's session as if it were a
3878    /// continuation of this one.
3879    ///
3880    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3881    /// a quota loss cuts an agent off mid-turn, so anything already in the
3882    /// tree is unfinished work, not a completed candidate a re-ask would pay
3883    /// for twice. A dirty tree is rescued into a commit first (the same
3884    /// neutral-identity rescue `implement`'s own outcome loop gives every
3885    /// candidate) so the next agent starts clean.
3886    ///
3887    /// The new agent gets the implementer's full prompt and full
3888    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3889    /// it has no session and no context, and is implementing the task from
3890    /// nothing, unlike a resumed drop which is only restating work already
3891    /// done.
3892    ///
3893    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3894    /// `implement` event, never into `self.state.quota` — that is what
3895    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3896    /// go unspent, and a seat that ultimately recovered on its second or
3897    /// third agent is not the stalled panel that check exists to catch. Only
3898    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3899    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3900    /// outcome loop already has — this helper never pushes to it itself.
3901    async fn resume_seat_handovers(
3902        &mut self,
3903        results: &mut [(usize, SeatState, AgentOutcome)],
3904        sent: &mut [SeatJob],
3905        prompts: &Prompts,
3906        run_id: &str,
3907    ) -> Result<()> {
3908        let instruction = seeded_instruction(&self.state);
3909        let language = self.state.config.graph.language.clone();
3910        let github_language = self.state.config.graph.github_language.clone();
3911        let brief = self
3912            .state
3913            .advice
3914            .as_ref()
3915            .and_then(|a| a.synthesis.as_deref())
3916            .map(str::to_owned);
3917        let attachments = self.state.attachments.clone();
3918        for (wi, seat, out) in results.iter_mut() {
3919            // Who holds the other candidate seats of this wave right now
3920            // (earlier handovers already written back to `sent`).
3921            let others: BTreeSet<String> = sent
3922                .iter()
3923                .enumerate()
3924                .filter(|(j, _)| j != wi)
3925                .map(|(_, j)| j.spec.id.clone())
3926                .collect();
3927            let Some(job) = sent.get_mut(*wi) else {
3928                continue;
3929            };
3930            // Where the seat's own original agent sits in the roster — the
3931            // fallback walk starts just past here, never at the front, so a
3932            // later candidate slot's quota loss does not fall back onto an
3933            // earlier slot's own agent.
3934            let start = self
3935                .roles
3936                .implementer_roster
3937                .iter()
3938                .position(|s| s.id == job.spec.id)
3939                .unwrap_or(0);
3940            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3941            let mut fallback_attempt = 0usize;
3942            let mut prev: Option<FailClass> = None;
3943            while let Some(cur) = FailClass::of(&*out) {
3944                if !should_hand_over(prev.as_ref(), &cur) {
3945                    break;
3946                }
3947                let Some(next) =
3948                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3949                        .cloned()
3950                else {
3951                    break;
3952                };
3953                tried.insert(next.id.clone());
3954                fallback_attempt += 1;
3955
3956                let coordination = self.coordinate(&job.cwd).await?;
3957                if let Ok(r) = git::rescue_commit(
3958                    &job.cwd,
3959                    &format!(
3960                        "magi: candidate {} (uncommitted work before {} fallback)",
3961                        seat.key,
3962                        if cur == FailClass::Quota {
3963                            "quota"
3964                        } else {
3965                            "handover"
3966                        }
3967                    ),
3968                )
3969                .await
3970                {
3971                    self.state.note_withheld("implement", &r.withheld);
3972                }
3973                drop(coordination);
3974
3975                record_handover(
3976                    &mut self.state,
3977                    "implement",
3978                    &seat.key,
3979                    &seat.agent,
3980                    &next.id,
3981                    &cur,
3982                    &fail_reason(&*out),
3983                );
3984                prev = Some(cur.clone());
3985
3986                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3987                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3988                // Kept in sync on `sent` itself, not just the local retry: a
3989                // later helper (`resume_unconfirmed_commands`) reads `sent`
3990                // after this one returns and must see whichever agent is now
3991                // occupying the seat, not the one that just quota'd out —
3992                // otherwise it would judge session/continuation eligibility
3993                // by the wrong CLI and could resend a fallback's session id
3994                // to the agent that lost it the seat in the first place.
3995                job.spec = next.clone();
3996                let mut retry = job.clone();
3997                retry.seat = new_seat;
3998                retry.prompt = prompt::implement_in(
3999                    &instruction,
4000                    &job.cwd.to_string_lossy(),
4001                    &language,
4002                    &github_language,
4003                    brief.as_deref(),
4004                    &attachments,
4005                );
4006                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4007                let cache = self.state.config.cache_dir();
4008                let ctx = WaveCtx {
4009                    carry_seats: false,
4010                    pauses: Some((&self.pause, &self.interrupt)),
4011                    run: run_id,
4012                    node: "implement",
4013                    prompts,
4014                    cache: cache.as_deref(),
4015                    round: None,
4016                };
4017                let (fallback_seat, fallback_out) = run_one(
4018                    retry,
4019                    Arc::clone(&self.sem),
4020                    &ctx,
4021                    &mut self.state,
4022                    fallback_attempt,
4023                )
4024                .await;
4025                *seat = fallback_seat;
4026                *out = fallback_out;
4027            }
4028        }
4029        Ok(())
4030    }
4031
4032    /// Ask an implement seat's own CLI to confirm what it started, once, when
4033    /// its reply reported a command whose completion status it never
4034    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4035    /// that does and does not mean.
4036    ///
4037    /// The completion contract this task asks for, extended to `implement`
4038    /// with the same signal `continue_fix_report` reads for the fixer,
4039    /// rather than a keyword search over the reply or a hard requirement on
4040    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4041    /// a candidate's CLI turn ended cleanly while a test run it had started
4042    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4043    /// named in it at all is untouched by this: `commands` is empty, so
4044    /// there is nothing to be unconfirmed.
4045    ///
4046    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4047    /// this is not about recovering edits that might already be on disk, it
4048    /// is about a result the seat itself never vouched for, which resuming
4049    /// asks for regardless of what the tree already holds. Bounded to one
4050    /// attempt for the same reason `resume_undelivered` is — this is the
4051    /// most expensive node in the graph — and a seat that still cannot
4052    /// confirm on that attempt is left as whatever its (possibly still
4053    /// unconfirmed) reply says; this does not invent a new "failed" reason
4054    /// for a candidate that otherwise produced a real, committed change.
4055    async fn resume_unconfirmed_commands(
4056        &mut self,
4057        results: &mut [(usize, SeatState, AgentOutcome)],
4058        sent: &[SeatJob],
4059        prompts: &Prompts,
4060        run_id: &str,
4061    ) {
4062        for (wi, seat, out) in results.iter_mut() {
4063            let AgentOutcome::Ok(o) = &*out else {
4064                continue;
4065            };
4066            if !has_unconfirmed_command(&o.commands) {
4067                continue;
4068            }
4069            let Some(job) = sent.get(*wi) else { continue };
4070            if !has_context(&job.spec, seat, job.sessions) {
4071                self.state.event(
4072                    "implement",
4073                    format!(
4074                        "{}: the reply named a command whose own CLI never confirmed the exit \
4075                         status of, but there is no session left to resume",
4076                        seat.key
4077                    ),
4078                );
4079                continue;
4080            }
4081            self.state.event(
4082                "implement",
4083                format!(
4084                    "{}: the reply named a command whose own CLI never confirmed the exit \
4085                     status of; resuming the conversation",
4086                    seat.key
4087                ),
4088            );
4089            let mut retry = job.clone();
4090            retry.seat = seat.clone();
4091            retry.prompt = prompt::resume_incomplete(
4092                "a command in your last reply had no confirmed exit status",
4093            );
4094            retry.timeout = retry_budget(job.timeout, true);
4095            retry.stem = format!("{}-confirm", job.stem);
4096            let cache = self.state.config.cache_dir();
4097            let ctx = WaveCtx {
4098                carry_seats: false,
4099                pauses: Some((&self.pause, &self.interrupt)),
4100                run: run_id,
4101                node: "implement",
4102                prompts,
4103                cache: cache.as_deref(),
4104                round: None,
4105            };
4106            let (resumed_seat, resumed) =
4107                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4108            *seat = resumed_seat;
4109            *out = resumed;
4110        }
4111    }
4112
4113    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4114    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4115    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4116    /// that motivated this.
4117    ///
4118    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4119    /// own nudge loop already covers for judge/review/vote seats, and not a
4120    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4121    /// implement seats: here the CLI turn genuinely finished while the node's
4122    /// own work — the fixer's account of what it did — had not. Gated purely
4123    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4124    /// reply, never on any wording in it, so a fixer whose valid, first-try
4125    /// `FixReport` happens to mention having waited on a background test is
4126    /// never resumed — the `Ok(report)` branch at the call site returns
4127    /// before this is ever invoked.
4128    ///
4129    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4130    /// attempt ([`retry_budget`]), nothing attempted once the session is
4131    /// gone, and a quota hit ends the loop immediately rather than retrying a
4132    /// rate limit that fails the same way again.
4133    async fn continue_fix_report(
4134        &mut self,
4135        mut seat: SeatState,
4136        parse_err: String,
4137        job: &SeatJob,
4138        prompts: &Prompts,
4139        run_id: &str,
4140        round: usize,
4141    ) -> (
4142        SeatState,
4143        Option<FixReport>,
4144        Option<String>,
4145        ContinuationRecord,
4146    ) {
4147        let mut last_err = parse_err;
4148        let mut cumulative_wait_ms = 0u64;
4149        let mut attempts = 0usize;
4150        loop {
4151            if !has_context(&job.spec, &seat, job.sessions) {
4152                self.state.event(
4153                    "fix",
4154                    format!(
4155                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4156                         session left to resume into"
4157                    ),
4158                );
4159                let outcome = if attempts == 0 {
4160                    ContinuationOutcome::NoSession
4161                } else {
4162                    ContinuationOutcome::Exhausted
4163                };
4164                return (
4165                    seat,
4166                    None,
4167                    Some(format!("unparsable fix report: {last_err}")),
4168                    ContinuationRecord {
4169                        attempts,
4170                        cumulative_wait_ms,
4171                        outcome,
4172                    },
4173                );
4174            }
4175            if attempts >= MAX_FIX_CONTINUATIONS {
4176                self.state.event(
4177                    "fix",
4178                    format!(
4179                        "round {round}: fixer's reply still had no adoption report after \
4180                         {attempts} continuation(s) ({last_err}); giving up"
4181                    ),
4182                );
4183                return (
4184                    seat,
4185                    None,
4186                    Some(format!(
4187                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4188                    )),
4189                    ContinuationRecord {
4190                        attempts,
4191                        cumulative_wait_ms,
4192                        outcome: ContinuationOutcome::Exhausted,
4193                    },
4194                );
4195            }
4196            attempts += 1;
4197            self.state.event(
4198                "fix",
4199                format!(
4200                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4201                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4202                ),
4203            );
4204            let mut retry = job.clone();
4205            retry.seat = seat.clone();
4206            retry.prompt = prompt::resume_incomplete(&last_err);
4207            retry.timeout = retry_budget(job.timeout, true);
4208            retry.stem = format!("{}-continue{attempts}", job.stem);
4209            let cache = self.state.config.cache_dir();
4210            let ctx = WaveCtx {
4211                carry_seats: false,
4212                pauses: Some((&self.pause, &self.interrupt)),
4213                run: run_id,
4214                node: "fix",
4215                prompts,
4216                cache: cache.as_deref(),
4217                round: Some(round),
4218            };
4219            let (resumed_seat, resumed_out) = run_one(
4220                retry,
4221                Arc::clone(&self.sem),
4222                &ctx,
4223                &mut self.state,
4224                attempts,
4225            )
4226            .await;
4227            seat = resumed_seat;
4228            match resumed_out {
4229                AgentOutcome::Ok(o) => {
4230                    cumulative_wait_ms += o.duration_ms;
4231                    match verdict::extract_json::<FixReport>(&o.text) {
4232                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4233                            self.state.event(
4234                                "fix",
4235                                format!(
4236                                    "round {round}: fixer's adoption report recovered after \
4237                                     {attempts} continuation(s)"
4238                                ),
4239                            );
4240                            return (
4241                                seat,
4242                                Some(report),
4243                                None,
4244                                ContinuationRecord {
4245                                    attempts,
4246                                    cumulative_wait_ms,
4247                                    outcome: ContinuationOutcome::Resumed,
4248                                },
4249                            );
4250                        }
4251                        // The report parsed, but this same reply's own
4252                        // CommandEvidence — the identical record `state.jobs`
4253                        // renders — names a command whose CLI never
4254                        // confirmed an exit status. Read together, that is
4255                        // not a resolved answer: keep nudging rather than
4256                        // accept a report standing next to a command the
4257                        // seat's own CLI cannot vouch for.
4258                        Ok(_) => {
4259                            last_err = "the reply parsed, but it reported a command whose own CLI \
4260                                 never confirmed an exit status"
4261                                .to_owned();
4262                        }
4263                        Err(e) => last_err = e.to_string(),
4264                    }
4265                }
4266                AgentOutcome::Quota(o) => {
4267                    cumulative_wait_ms += o.duration_ms;
4268                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4269                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4270                    self.state.quota.push(loss);
4271                    self.state.event(
4272                        "fix",
4273                        format!(
4274                            "round {round}: continuation rate limited (quota); not retrying now"
4275                        ),
4276                    );
4277                    return (
4278                        seat,
4279                        None,
4280                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4281                        ContinuationRecord {
4282                            attempts,
4283                            cumulative_wait_ms,
4284                            outcome: ContinuationOutcome::QuotaLost,
4285                        },
4286                    );
4287                }
4288                AgentOutcome::Dropped(o) => {
4289                    cumulative_wait_ms += o.duration_ms;
4290                    let why = o
4291                        .dropped
4292                        .as_ref()
4293                        .map(|d| d.why.as_str())
4294                        .unwrap_or("the CLI ended the stream without delivering its answer");
4295                    last_err = format!("the CLI dropped the stream ({why})");
4296                }
4297                AgentOutcome::Failed(e) => last_err = e,
4298                // The continuation was never started; the report stays lost
4299                // and the caller records that, without any handover.
4300                AgentOutcome::ResourceBlocked(e) => {
4301                    return (
4302                        seat,
4303                        None,
4304                        Some(format!("the continuation was not started: {e}")),
4305                        ContinuationRecord {
4306                            attempts: attempts.saturating_sub(1),
4307                            cumulative_wait_ms,
4308                            outcome: ContinuationOutcome::NoSession,
4309                        },
4310                    );
4311                }
4312            }
4313        }
4314    }
4315
4316    fn after_implement(&mut self) -> Result<()> {
4317        if !self.state.candidate_preservation.is_empty() {
4318            bail!("candidate preservation incomplete; judging is unsafe");
4319        }
4320        // Scan every candidate patch once the set is complete.
4321        if self.state.leaks.is_empty() {
4322            let cfg = self.state.config.blind.clone();
4323            let mut leaks = Vec::new();
4324            for c in &self.state.candidates {
4325                let Some(patch) =
4326                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4327                else {
4328                    continue;
4329                };
4330                leaks.extend(blind::scan(
4331                    &format!("candidate {} patch", c.label),
4332                    &patch,
4333                    &cfg.vendor_tokens,
4334                ));
4335            }
4336            if !leaks.is_empty() {
4337                let summary = leaks
4338                    .iter()
4339                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4340                    .collect::<Vec<_>>()
4341                    .join(", ");
4342                match cfg.on_leak {
4343                    LeakPolicy::Fail => {
4344                        self.state.status = RunStatus::Failed;
4345                        self.state
4346                            .event("blind", format!("vendor text in a patch: {summary}"));
4347                        self.state.leaks = leaks;
4348                        self.state.save()?;
4349                        self.settle_questions();
4350                        bail!(
4351                            "blind.on_leak = \"fail\" and vendor text reached a \
4352                             judged patch: {summary}"
4353                        );
4354                    }
4355                    LeakPolicy::Redact => self.state.event(
4356                        "blind",
4357                        format!("redacting vendor text for judging: {summary}"),
4358                    ),
4359                    LeakPolicy::Warn => self.state.event(
4360                        "blind",
4361                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4362                    ),
4363                }
4364                self.state.leaks = leaks;
4365            }
4366        }
4367
4368        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4369        // incomplete or inconsistent saved state cannot bypass the strict contract.
4370        let mut invalidated = Vec::new();
4371        for c in &mut self.state.candidates {
4372            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4373                c.verified_noop = None;
4374                if c.empty && c.failed.is_none() {
4375                    c.failed = Some(
4376                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4377                            .to_owned(),
4378                    );
4379                }
4380                invalidated.push(c.label);
4381            }
4382        }
4383        for label in invalidated {
4384            self.state.event(
4385                "implement",
4386                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4387            );
4388        }
4389
4390        if self.state.viable().is_empty() {
4391            if self.state.all_candidates_verified_noop() {
4392                // Every candidate agreed, with evidence the adoption guard
4393                // accepted, that nothing belongs in this worktree. That is
4394                // not the same fact as a candidate that simply failed to
4395                // write anything, and settling it as an ordinary `Failed`
4396                // (see `SCHEMA`'s doc for schema 10) is what let two of
4397                // task 391f's attempts burn a retry each re-discovering the
4398                // same already-landed fix. Terminal either way, so `judge`
4399                // must never run over an empty candidate set — unlike the
4400                // `Failed` branch below this returns `Ok`, not an error:
4401                // nothing here failed.
4402                self.state.status = RunStatus::VerifiedNoop;
4403                self.state.save()?;
4404                self.settle_questions();
4405                return Ok(());
4406            }
4407            self.state.status = RunStatus::Failed;
4408            self.state.save()?;
4409            self.settle_questions();
4410            bail!("no candidate produced a change; nothing to judge");
4411        }
4412        self.state.status = RunStatus::Judging;
4413        self.state.save()?;
4414        Ok(())
4415    }
4416
4417    // --------------------------------------------------------------- judge
4418
4419    async fn judge(&mut self) -> Result<()> {
4420        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4421        // agent files with `magi task add` name the run that paid for it. The
4422        // prompt overlay is cloned alongside it because the waves borrow it
4423        // while `self` is mutably borrowed by the node's own bookkeeping.
4424        let run_id = self.state.id.clone();
4425        let prompts = self.state.config.prompts.clone();
4426        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4427            return Ok(());
4428        }
4429        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4430        if viable.len() == 1 {
4431            // Recorded so this is a one-time event: `judgements` stays empty
4432            // either way, which without this flag is indistinguishable from
4433            // "not yet judged" on the next reentry — and status is left
4434            // untouched, so a later node's conclusion (e.g. `Blocked` after
4435            // the review budget ran out) survives a resume instead of being
4436            // clobbered back to `Judging` by this node running again.
4437            self.state.judge_skipped = true;
4438            self.state.event(
4439                "judge",
4440                format!(
4441                    "only candidate {} produced a change; judging skipped",
4442                    viable[0].label
4443                ),
4444            );
4445            self.state.save()?;
4446            return Ok(());
4447        }
4448        self.state.status = RunStatus::Judging;
4449
4450        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4451        let language = self.state.config.graph.language.clone();
4452        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4453        let sessions = self.state.config.graph.sessions;
4454        let artifacts = agent::artifacts_dir(&self.state.dir());
4455        let root = self.state.worktree_root();
4456        let base_short = short(&self.state.base_commit);
4457
4458        let mut jobs = Vec::new();
4459        let mut orders = Vec::new();
4460        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4461            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4462            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4463            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4464            let seat_key = format!("judge-{}", j + 1);
4465            let seat = self.seat(&seat_key, &spec.id);
4466            jobs.push(SeatJob {
4467                prompt: prompt::judge(
4468                    &self.state.instruction,
4469                    &views,
4470                    self.roles.judges.len(),
4471                    &base_short,
4472                    &language,
4473                ),
4474                spec,
4475                seat,
4476                cwd: root.join(format!("judge-{}", j + 1)),
4477                timeout,
4478                allow_write: false,
4479                sessions,
4480                artifacts: artifacts.clone(),
4481                stem: format!("judge-{}", j + 1),
4482                handover: None,
4483            });
4484        }
4485
4486        self.state.event(
4487            "judge",
4488            format!(
4489                "{} judges ranking {} candidates blind",
4490                jobs.len(),
4491                viable.len()
4492            ),
4493        );
4494        let labels_for_check = labels.clone();
4495        let mut quota_losses = Vec::new();
4496        let cache = self.state.config.cache_dir();
4497        let ctx = WaveCtx {
4498            carry_seats: false,
4499            pauses: Some((&self.pause, &self.interrupt)),
4500            run: &run_id,
4501            node: "judge",
4502            prompts: &prompts,
4503            cache: cache.as_deref(),
4504            round: None,
4505        };
4506        let results = ask_json_wave::<Ranking>(
4507            jobs,
4508            Arc::clone(&self.sem),
4509            self.state.config.graph.retries,
4510            &self.roles.judge_roster,
4511            &ctx,
4512            &mut quota_losses,
4513            &mut self.state,
4514            &move |r: &Ranking| r.validate(&labels_for_check),
4515        )
4516        .await;
4517        if self.state.resource_block.is_some() {
4518            return self.stop_for_resource();
4519        }
4520        self.state.quota.extend(quota_losses);
4521
4522        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4523            let agent_id = seat.agent.clone();
4524            self.state.seats.insert(seat.key.clone(), seat);
4525            let mut record = Judgement {
4526                judge: j + 1,
4527                seat: format!("judge-{}", j + 1),
4528                agent: agent_id,
4529                ranking: Vec::new(),
4530                reasons: BTreeMap::new(),
4531                confidence: None,
4532                strengths: BTreeMap::new(),
4533                order: orders[j].clone(),
4534                failed: None,
4535                duration_ms: 0,
4536            };
4537            match res {
4538                Ok((ranking, out)) => {
4539                    record.ranking = ranking.normalized();
4540                    record.reasons = ranking.reasons;
4541                    record.strengths = ranking.strengths;
4542                    record.confidence = ranking.confidence;
4543                    record.duration_ms = out.duration_ms;
4544                    self.state.event(
4545                        "judge",
4546                        format!(
4547                            "judge {} ranked {}",
4548                            j + 1,
4549                            record.ranking.iter().collect::<String>()
4550                        ),
4551                    );
4552                }
4553                Err(e) => {
4554                    record.failed = Some(e.to_string());
4555                    self.state
4556                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4557                }
4558            }
4559            self.state.judgements.push(record);
4560            self.state.save()?;
4561        }
4562        Ok(())
4563    }
4564
4565    // ---------------------------------------------------------- deliberate
4566
4567    async fn deliberate(&mut self) -> Result<()> {
4568        if self.hold_base_sync().await? {
4569            return Ok(());
4570        }
4571        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4572        // agent files with `magi task add` name the run that paid for it. The
4573        // prompt overlay is cloned alongside it because the waves borrow it
4574        // while `self` is mutably borrowed by the node's own bookkeeping.
4575        let run_id = self.state.id.clone();
4576        let prompts = self.state.config.prompts.clone();
4577        let rounds = self.state.config.graph.deliberate_rounds;
4578        // Resume unfinished rounds after an outage, but never reopen a tally.
4579        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4580            return Ok(());
4581        }
4582        let tops: Vec<char> = self
4583            .state
4584            .judgements
4585            .iter()
4586            .filter_map(|j| j.ranking.first().copied())
4587            .collect();
4588        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4589            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4590                self.state.event(
4591                    "deliberate",
4592                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4593                );
4594            }
4595            self.state.status = RunStatus::Voting;
4596            self.state.save()?;
4597            return Ok(());
4598        }
4599
4600        self.state.status = RunStatus::Deliberating;
4601        self.state.event(
4602            "deliberate",
4603            format!(
4604                "split: first choices were {} — opening {rounds} round(s)",
4605                tops.iter().collect::<String>()
4606            ),
4607        );
4608
4609        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4610        let language = self.state.config.graph.language.clone();
4611        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4612        let sessions = self.state.config.graph.sessions;
4613        let artifacts = agent::artifacts_dir(&self.state.dir());
4614        let root = self.state.worktree_root();
4615        let base_short = short(&self.state.base_commit);
4616
4617        // Judges argue in sequence so that a turn can answer the one before it;
4618        // that is the difference between deliberation and three parallel
4619        // monologues.
4620        for round in self.state.deliberation.len() + 1..=rounds {
4621            let mut turns: Vec<DeliberationTurn> = Vec::new();
4622            let mut round_losses = Vec::new();
4623            let mut asked = 0;
4624            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4625                if self.state.judgements[j].failed.is_some() {
4626                    continue;
4627                }
4628                let seat_key = format!("judge-{}", j + 1);
4629                let spec = self.occupant(&seat_key, spec);
4630                let mut seat = self.seat(&seat_key, &spec.id);
4631                let transcript = self.transcript(&turns, j);
4632                let build = |context: Option<&str>| {
4633                    prompt::deliberate(
4634                        &self.state.instruction,
4635                        context,
4636                        &transcript,
4637                        round,
4638                        rounds,
4639                        &language,
4640                    )
4641                };
4642                let block = self.candidate_block(&viable, &base_short);
4643                let full = build(Some(&block));
4644                let text = if has_context(&spec, &seat, sessions) {
4645                    build(None)
4646                } else {
4647                    full.clone()
4648                };
4649                let job = SeatJob {
4650                    spec,
4651                    seat: seat.clone(),
4652                    prompt: text,
4653                    cwd: root.join(format!("judge-{}", j + 1)),
4654                    timeout,
4655                    allow_write: false,
4656                    sessions,
4657                    artifacts: artifacts.clone(),
4658                    stem: format!("delib-{round}-judge-{}", j + 1),
4659                    handover: Some(full),
4660                };
4661                let cache = self.state.config.cache_dir();
4662                let ctx = WaveCtx {
4663                    carry_seats: false,
4664                    pauses: Some((&self.pause, &self.interrupt)),
4665                    run: &run_id,
4666                    node: "deliberate",
4667                    prompts: &prompts,
4668                    cache: cache.as_deref(),
4669                    round: None,
4670                };
4671                // A turn is never nudged (`retries` 0): a failed seat is
4672                // handed to the next roster agent, which gets the full
4673                // context. An empty answer is a turn, not a failure.
4674                let mut losses = Vec::new();
4675                asked += 1;
4676                let mut results = ask_wave_with::<String>(
4677                    vec![job],
4678                    Arc::clone(&self.sem),
4679                    0,
4680                    &self.roles.judge_roster,
4681                    &ctx,
4682                    &mut losses,
4683                    &mut self.state,
4684                    &|text: &str| {
4685                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4686                    },
4687                )
4688                .await;
4689                if self.state.resource_block.is_some() {
4690                    return self.stop_for_resource();
4691                }
4692                round_losses.extend(losses.iter().cloned());
4693                self.state.quota.extend(losses);
4694                let (updated, res, _) = results.pop().expect("one job in, one result out");
4695                seat = updated;
4696                let agent_id = seat.agent.clone();
4697                self.state.seats.insert(seat.key.clone(), seat);
4698                let body = match res {
4699                    Ok((body, _)) => body,
4700                    // Skip the seat; a CLI's raw error JSON is never read as
4701                    // this judge's position.
4702                    Err(e) => {
4703                        self.state
4704                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4705                        continue;
4706                    }
4707                };
4708                let tentative = verdict::extract_json::<Position>(&body)
4709                    .ok()
4710                    .and_then(|p| p.tentative)
4711                    .and_then(|s| s.trim().chars().next())
4712                    .map(|c| c.to_ascii_uppercase());
4713                self.state.event(
4714                    "deliberate",
4715                    format!(
4716                        "round {round}: judge {} now favours {}",
4717                        j + 1,
4718                        tentative.map_or("—".to_owned(), |c| c.to_string())
4719                    ),
4720                );
4721                turns.push(DeliberationTurn {
4722                    judge: j + 1,
4723                    agent: agent_id,
4724                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4725                    tentative,
4726                });
4727            }
4728            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4729                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4730                return self.stop_for_resource();
4731            }
4732            self.state
4733                .deliberation
4734                .push(DeliberationRound { round, turns });
4735            self.state.save()?;
4736        }
4737
4738        self.state.status = RunStatus::Voting;
4739        self.state.save()?;
4740        Ok(())
4741    }
4742
4743    // ---------------------------------------------------------------- vote
4744
4745    async fn vote(&mut self) -> Result<()> {
4746        if self.hold_base_sync().await? {
4747            return Ok(());
4748        }
4749        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4750        // agent files with `magi task add` name the run that paid for it. The
4751        // prompt overlay is cloned alongside it because the waves borrow it
4752        // while `self` is mutably borrowed by the node's own bookkeeping.
4753        let run_id = self.state.id.clone();
4754        let prompts = self.state.config.prompts.clone();
4755        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4756            return Ok(());
4757        }
4758        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4759        if viable.len() == 1 {
4760            return Ok(());
4761        }
4762        self.state.status = RunStatus::Voting;
4763
4764        let language = self.state.config.graph.language.clone();
4765        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4766        let sessions = self.state.config.graph.sessions;
4767        let artifacts = agent::artifacts_dir(&self.state.dir());
4768        let root = self.state.worktree_root();
4769        let base_short = short(&self.state.base_commit);
4770        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4771
4772        let mut jobs = Vec::new();
4773        let mut seats_at = Vec::new();
4774        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4775            if self
4776                .state
4777                .judgements
4778                .get(j)
4779                .is_some_and(|r| r.failed.is_some())
4780            {
4781                continue;
4782            }
4783            let seat_key = format!("judge-{}", j + 1);
4784            let spec = self.occupant(&seat_key, spec);
4785            let seat = self.seat(&seat_key, &spec.id);
4786            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4787            let text = if has_context(&spec, &seat, sessions) {
4788                prompt::final_vote(&viable, &language)
4789            } else {
4790                full.clone()
4791            };
4792            jobs.push(SeatJob {
4793                spec,
4794                seat,
4795                prompt: text,
4796                cwd: root.join(format!("judge-{}", j + 1)),
4797                timeout,
4798                allow_write: false,
4799                sessions,
4800                artifacts: artifacts.clone(),
4801                stem: format!("vote-judge-{}", j + 1),
4802                handover: Some(full),
4803            });
4804            seats_at.push(j);
4805        }
4806
4807        self.state.event(
4808            "vote",
4809            format!(
4810                "collecting {} final votes one by one, privately",
4811                jobs.len()
4812            ),
4813        );
4814        let allowed = viable.clone();
4815        let mut quota_losses = Vec::new();
4816        let cache = self.state.config.cache_dir();
4817        let ctx = WaveCtx {
4818            carry_seats: false,
4819            pauses: Some((&self.pause, &self.interrupt)),
4820            run: &run_id,
4821            node: "vote",
4822            prompts: &prompts,
4823            cache: cache.as_deref(),
4824            round: None,
4825        };
4826        let results = ask_json_wave::<FinalVote>(
4827            jobs,
4828            Arc::clone(&self.sem),
4829            self.state.config.graph.retries,
4830            &self.roles.judge_roster,
4831            &ctx,
4832            &mut quota_losses,
4833            &mut self.state,
4834            &move |v: &FinalVote| match v.label() {
4835                Some(c) if allowed.contains(&c) => Ok(()),
4836                other => bail!("vote {other:?} is not one of {allowed:?}"),
4837            },
4838        )
4839        .await;
4840        if self.state.resource_block.is_some() {
4841            return self.stop_for_resource();
4842        }
4843        self.state.quota.extend(quota_losses);
4844
4845        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4846            let agent_id = seat.agent.clone();
4847            self.state.seats.insert(seat.key.clone(), seat);
4848            let initial = self
4849                .state
4850                .judgements
4851                .get(j)
4852                .and_then(|r| r.ranking.first().copied());
4853            let mut record = VoteRecord {
4854                judge: j + 1,
4855                agent: agent_id,
4856                vote: None,
4857                reason: String::new(),
4858                changed: false,
4859            };
4860            match res {
4861                Ok((v, _)) => {
4862                    record.vote = v.label();
4863                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4864                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4865                    self.state.event(
4866                        "vote",
4867                        format!(
4868                            "judge {} voted {}{}",
4869                            j + 1,
4870                            record.vote.unwrap_or('?'),
4871                            if record.changed { " (changed)" } else { "" }
4872                        ),
4873                    );
4874                }
4875                Err(e) => {
4876                    self.state
4877                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4878                }
4879            }
4880            self.state.votes.push(record);
4881            self.state.save()?;
4882        }
4883        Ok(())
4884    }
4885
4886    // --------------------------------------------------------------- tally
4887
4888    fn tally(&mut self) -> Result<()> {
4889        if self.state.tally.is_some() {
4890            return Ok(());
4891        }
4892        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4893        let tops: Vec<char> = self
4894            .state
4895            .judgements
4896            .iter()
4897            .filter_map(|j| j.ranking.first().copied())
4898            .collect();
4899        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4900
4901        // A judge whose private vote failed still counted once, in the initial
4902        // ranking; using it beats discarding a whole seat.
4903        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4904        let mut cast: Vec<char> = Vec::new();
4905        for (i, j) in self.state.judgements.iter().enumerate() {
4906            let vote = self
4907                .state
4908                .votes
4909                .iter()
4910                .find(|v| v.judge == i + 1)
4911                .and_then(|v| v.vote)
4912                .or_else(|| j.ranking.first().copied());
4913            if let Some(v) = vote {
4914                *first_choice.entry(v).or_insert(0) += 1;
4915                cast.push(v);
4916            }
4917        }
4918
4919        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4920        for j in &self.state.judgements {
4921            let n = j.ranking.len();
4922            for (pos, label) in j.ranking.iter().enumerate() {
4923                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4924            }
4925        }
4926
4927        let best = first_choice.values().copied().max().unwrap_or(0);
4928        let mut leaders: Vec<char> = first_choice
4929            .iter()
4930            .filter(|(_, v)| **v == best)
4931            .map(|(k, _)| *k)
4932            .collect();
4933        let mut tie_break = None;
4934        if leaders.len() > 1 {
4935            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4936            let borda_leaders: Vec<char> = leaders
4937                .iter()
4938                .copied()
4939                .filter(|l| borda[l] == top_borda)
4940                .collect();
4941            tie_break = Some(if borda_leaders.len() == 1 {
4942                format!(
4943                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4944                    leaders.len()
4945                )
4946            } else {
4947                format!(
4948                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4949                    leaders.len()
4950                )
4951            });
4952            leaders = borda_leaders;
4953            leaders.sort_unstable();
4954        }
4955        let winner = *leaders
4956            .first()
4957            .or(viable.first())
4958            .context("no candidate to declare a winner from")?;
4959
4960        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4961        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4962        let deliberated = !self.state.deliberation.is_empty();
4963
4964        // Whose verdict is this? A rate-limited seat is absent even if it
4965        // ranked before the limit hit, so presence is measured against the
4966        // recorded losses, not just "did a ranking ever appear".
4967        let quota_seats: std::collections::BTreeSet<&str> =
4968            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4969        let mut present = 0usize;
4970        for (i, j) in self.state.judgements.iter().enumerate() {
4971            if quota_seats.contains(j.seat.as_str()) {
4972                continue;
4973            }
4974            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4975            let voted = self
4976                .state
4977                .votes
4978                .iter()
4979                .any(|v| v.judge == i + 1 && v.vote.is_some());
4980            if ranked || voted {
4981                present += 1;
4982            }
4983        }
4984        // Strict majority of the configured panel. A bare majority is real
4985        // signal we can act on, while a minority verdict must never stand in
4986        // for a healthy one. A one-candidate run needs no panel at all, and
4987        // `judges` stays `0` rather than the roster size a panel that never
4988        // sat would otherwise be credited with.
4989        let needs_quorum = viable.len() > 1;
4990        let judges_total = if needs_quorum {
4991            self.roles.judges.len()
4992        } else {
4993            0
4994        };
4995        let quorum = if needs_quorum {
4996            judges_total / 2 + 1
4997        } else {
4998            0
4999        };
5000        let met_quorum = !needs_quorum || present >= quorum;
5001        let uncontested = (!needs_quorum).then(|| {
5002            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5003        });
5004
5005        self.state.event(
5006            "tally",
5007            match &uncontested {
5008                Some(reason) => format!("winner {winner} — {reason}"),
5009                None => format!(
5010                    "winner {winner} — votes {} | initial {} | {} changed | \
5011                     {present}/{judges_total} judges{}",
5012                    first_choice
5013                        .iter()
5014                        .map(|(k, v)| format!("{k}:{v}"))
5015                        .collect::<Vec<_>>()
5016                        .join(" "),
5017                    if unanimous_initial {
5018                        "unanimous"
5019                    } else {
5020                        "split"
5021                    },
5022                    changed_votes,
5023                    if met_quorum {
5024                        String::new()
5025                    } else {
5026                        format!(" — below quorum ({quorum} required)")
5027                    },
5028                ),
5029            },
5030        );
5031        if !met_quorum {
5032            self.state.event(
5033                "stall",
5034                format!(
5035                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5036                     the run stops here, resumable"
5037                ),
5038            );
5039        }
5040        self.state.tally = Some(Tally {
5041            first_choice,
5042            borda,
5043            winner,
5044            rankings: tops.len(),
5045            unanimous_initial,
5046            deliberated,
5047            changed_votes,
5048            unanimous_final,
5049            tie_break,
5050            judges: judges_total,
5051            present,
5052            quorum,
5053            met_quorum,
5054            uncontested,
5055        });
5056        self.state.status = if met_quorum {
5057            RunStatus::Reviewing
5058        } else {
5059            RunStatus::Stalled
5060        };
5061        self.state.save()?;
5062        Ok(())
5063    }
5064
5065    // ------------------------------------------------------------- recover
5066
5067    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5068    /// resumed toward completion once the transient cause clears.
5069    ///
5070    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5071    /// it toward the quorum, which is exactly the set of seats whose absence
5072    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5073    /// not depend on which node happened to hit the limit), or an ordinary
5074    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5075    /// seat is never disturbed.
5076    ///
5077    /// A seat that now answers with a usable ranking is "recovered": its
5078    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5079    /// `tally` counts it present again), and its vote re-collected. A seat that
5080    /// still fails keeps its loss and stays absent.
5081    ///
5082    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5083    /// to review/gate/merge), `false` when it is still below quorum (the run
5084    /// stays `Stalled`, still resumable for a later retry).
5085    #[allow(clippy::too_many_lines)]
5086    async fn recover_stall(&mut self) -> Result<bool> {
5087        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5088        // agent files with `magi task add` name the run that paid for it. The
5089        // prompt overlay is cloned alongside it because the waves borrow it
5090        // while `self` is mutably borrowed by the node's own bookkeeping.
5091        let run_id = self.state.id.clone();
5092        let prompts = self.state.config.prompts.clone();
5093        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5094        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5095        // is what keeps a non-quota collapse — or a quota loss recorded at the
5096        // deliberate node — from being a permanent dead-end on `--resume`.
5097        let quota_seats: BTreeSet<&str> =
5098            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5099        let absent: Vec<String> = self
5100            .state
5101            .judgements
5102            .iter()
5103            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5104            .map(|j| j.seat.clone())
5105            .collect();
5106        if absent.is_empty() {
5107            return Ok(false);
5108        }
5109        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5110        if viable.len() <= 1 {
5111            return Ok(false);
5112        }
5113        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5114        let language = self.state.config.graph.language.clone();
5115        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5116        let sessions = self.state.config.graph.sessions;
5117        let artifacts = agent::artifacts_dir(&self.state.dir());
5118        let root = self.state.worktree_root();
5119        let base_short = short(&self.state.base_commit);
5120        let candidates: Vec<Candidate> = viable.clone();
5121
5122        // Map each absent seat key to its 0-based position in `roles.judges`.
5123        let mut positions: Vec<usize> = absent
5124            .iter()
5125            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5126            .collect();
5127        if positions.is_empty() {
5128            return Ok(false);
5129        }
5130        positions.sort_unstable();
5131        positions.dedup();
5132
5133        // Re-rank the lost seats, one blind prompt each.
5134        let mut judge_jobs = Vec::new();
5135        for &j in &positions {
5136            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5137            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5138            let seat_key = format!("judge-{}", j + 1);
5139            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5140            let seat = self.seat(&seat_key, &spec.id);
5141            judge_jobs.push(SeatJob {
5142                spec,
5143                seat,
5144                prompt: prompt::judge(
5145                    &self.state.instruction,
5146                    &views,
5147                    self.roles.judges.len(),
5148                    &base_short,
5149                    &language,
5150                ),
5151                cwd: root.join(seat_key),
5152                timeout,
5153                allow_write: false,
5154                sessions,
5155                artifacts: artifacts.clone(),
5156                stem: format!("judge-{}-recover", j + 1),
5157                handover: None,
5158            });
5159        }
5160
5161        let labels_for_check = labels.clone();
5162        let mut judge_losses = Vec::new();
5163        let retries = self.state.config.graph.retries;
5164        let cache = self.state.config.cache_dir();
5165        let ctx = WaveCtx {
5166            carry_seats: false,
5167            pauses: Some((&self.pause, &self.interrupt)),
5168            run: &run_id,
5169            node: "judge",
5170            prompts: &prompts,
5171            cache: cache.as_deref(),
5172            round: None,
5173        };
5174        let results = ask_json_wave::<Ranking>(
5175            judge_jobs,
5176            Arc::clone(&self.sem),
5177            retries,
5178            &self.roles.judge_roster,
5179            &ctx,
5180            &mut judge_losses,
5181            &mut self.state,
5182            &move |r: &Ranking| r.validate(&labels_for_check),
5183        )
5184        .await;
5185        if self.state.resource_block.is_some() {
5186            self.stop_for_resource()?;
5187            return Ok(false);
5188        }
5189
5190        // Refresh the judgement of every seat that ranked again.
5191        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5192        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5193            let agent_id = seat.agent.clone();
5194            self.state.seats.insert(seat.key.clone(), seat);
5195            let record = &mut self.state.judgements[j];
5196            match res {
5197                Ok((ranking, out)) => {
5198                    record.agent = agent_id;
5199                    record.ranking = ranking.normalized();
5200                    record.reasons = ranking.reasons;
5201                    record.strengths = ranking.strengths;
5202                    record.confidence = ranking.confidence;
5203                    record.failed = None;
5204                    record.duration_ms = out.duration_ms;
5205                    recovered.insert(j);
5206                    self.state.event(
5207                        "recover",
5208                        format!("judge {} ranked again after the limit", j + 1),
5209                    );
5210                }
5211                Err(e) => {
5212                    self.state
5213                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5214                }
5215            }
5216        }
5217
5218        // Re-ask the votes of the seats that recovered a ranking.
5219        let mut vote_jobs = Vec::new();
5220        let mut vote_pos: Vec<usize> = Vec::new();
5221        for &j in &recovered {
5222            let seat_key = format!("judge-{}", j + 1);
5223            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5224            let seat = self.seat(&seat_key, &spec.id);
5225            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5226            let text = if has_context(&spec, &seat, sessions) {
5227                prompt::final_vote(&labels, &language)
5228            } else {
5229                full.clone()
5230            };
5231            vote_jobs.push(SeatJob {
5232                spec,
5233                seat,
5234                prompt: text,
5235                cwd: root.join(seat_key),
5236                timeout,
5237                allow_write: false,
5238                sessions,
5239                artifacts: artifacts.clone(),
5240                stem: format!("vote-judge-{}-recover", j + 1),
5241                handover: Some(full),
5242            });
5243            vote_pos.push(j);
5244        }
5245        let allowed = labels.clone();
5246        let mut vote_losses = Vec::new();
5247        let vote_retries = self.state.config.graph.retries;
5248        let vote_cache = self.state.config.cache_dir();
5249        let ctx = WaveCtx {
5250            carry_seats: false,
5251            pauses: Some((&self.pause, &self.interrupt)),
5252            run: &run_id,
5253            node: "vote",
5254            prompts: &prompts,
5255            cache: vote_cache.as_deref(),
5256            round: None,
5257        };
5258        let votes = ask_json_wave::<FinalVote>(
5259            vote_jobs,
5260            Arc::clone(&self.sem),
5261            vote_retries,
5262            &self.roles.judge_roster,
5263            &ctx,
5264            &mut vote_losses,
5265            &mut self.state,
5266            &move |v: &FinalVote| match v.label() {
5267                Some(c) if allowed.contains(&c) => Ok(()),
5268                other => bail!("vote {other:?} is not one of {allowed:?}"),
5269            },
5270        )
5271        .await;
5272        if self.state.resource_block.is_some() {
5273            self.stop_for_resource()?;
5274            return Ok(false);
5275        }
5276        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5277            let agent_id = seat.agent.clone();
5278            self.state.seats.insert(seat.key.clone(), seat);
5279            match res {
5280                Ok((v, _)) => {
5281                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5282                        rec.vote = v.label();
5283                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5284                    } else {
5285                        self.state.votes.push(VoteRecord {
5286                            judge: j + 1,
5287                            agent: agent_id,
5288                            vote: v.label(),
5289                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5290                            changed: false,
5291                        });
5292                    }
5293                    self.state.event(
5294                        "recover",
5295                        format!("judge {} voted again after the limit", j + 1),
5296                    );
5297                }
5298                Err(e) => {
5299                    self.state
5300                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5301                }
5302            }
5303        }
5304
5305        // A seat that ranked again is present even if its re-vote failed —
5306        // `tally` falls back to the initial ranking's first choice — so clear
5307        // its quota loss. Seats that still fail keep theirs and stay absent.
5308        let recovered_keys: BTreeSet<String> = recovered
5309            .iter()
5310            .map(|&j| format!("judge-{}", j + 1))
5311            .collect();
5312        self.state
5313            .quota
5314            .retain(|q| !recovered_keys.contains(&q.seat));
5315        // A seat that hit the limit again is a fresh loss, not the old one:
5316        // replace the stale entry so the history stays one-per-seat and the
5317        // daemon can tell this attempt's loss from a previous session's.
5318        for loss in judge_losses.into_iter().chain(vote_losses) {
5319            if recovered_keys.contains(&loss.seat) {
5320                continue;
5321            }
5322            self.state.quota.retain(|q| q.seat != loss.seat);
5323            self.state.quota.push(loss);
5324        }
5325
5326        // Recompute the verdict from the refreshed panel.
5327        self.state.tally = None;
5328        self.tally()?;
5329        Ok(self
5330            .state
5331            .tally
5332            .as_ref()
5333            .map(|t| t.met_quorum)
5334            .unwrap_or(false))
5335    }
5336
5337    // ---------------------------------------------------------------- graft
5338
5339    /// Port the strengths the judges attributed to the losing candidates onto
5340    /// the winner, once, between the tally and the review loop.
5341    ///
5342    /// Best-effort by construction: it returns nothing and fails nothing. A
5343    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5344    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5345    /// the run carries on as if the phase were off. See [`graft`] for the
5346    /// decisions and `AGENTS.md` for the invariants.
5347    ///
5348    /// The one exception is a rollback that could not be confirmed: the
5349    /// rejected commit may still be the winner's tip, so the run is blocked
5350    /// (resumable; the record stays `Running`, which makes a resume retry the
5351    /// restore) instead of reviewing, gating and merging it.
5352    async fn graft(&mut self) -> Result<()> {
5353        let Err(e) = self.graft_inner().await else {
5354            return Ok(());
5355        };
5356        if e.is::<crate::repo_lock::ResourceBlocked>() {
5357            return Err(e);
5358        }
5359        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5360            self.state.status = RunStatus::Blocked;
5361            self.state.event("graft", format!("blocked: {e:#}"));
5362            self.state.save()?;
5363            return Err(e);
5364        }
5365        // An error after the `Running` record was saved may have left the
5366        // fixer's work in the tree: the record must not stay unsettled
5367        // (a later resume would reset past the review fixes), so confirm the
5368        // restore now, or block.
5369        if let Some(rec) = self.state.graft.clone()
5370            && !rec.outcome.settled()
5371        {
5372            if let Some(winner) = self.state.winner().cloned() {
5373                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5374                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5375                        return Err(re);
5376                    }
5377                    self.state.status = RunStatus::Blocked;
5378                    self.state.event("graft", format!("blocked: {re:#}"));
5379                    self.state.save()?;
5380                    return Err(re);
5381                }
5382            }
5383            if let Some(g) = self.state.graft.as_mut() {
5384                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5385            }
5386        }
5387        self.state.event("graft", format!("skipped: {e:#}"));
5388        if let Err(e) = self.state.save() {
5389            tracing::warn!("save after graft: {e:#}");
5390        }
5391        Ok(())
5392    }
5393
5394    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5395    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5396    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5397        let _coordination = self.coordinate(wt).await?;
5398        crate::recovery::restore_repair(wt, pre)
5399            .await
5400            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5401    }
5402
5403    /// A skip is a run event, recorded once however often the node is re-entered.
5404    fn graft_skipped(&mut self, why: &str) {
5405        let message = format!("skipped: {why}");
5406        if !self
5407            .state
5408            .events
5409            .iter()
5410            .any(|e| e.node == "graft" && e.message == message)
5411        {
5412            self.state.event("graft", message);
5413        }
5414    }
5415
5416    async fn graft_inner(&mut self) -> Result<()> {
5417        // A round that was started and never finished (crash, kill): the
5418        // fixer may have left anything in the tree, so put the winner back.
5419        if let Some(rec) = self.state.graft.clone()
5420            && !rec.outcome.settled()
5421        {
5422            // Reviews exist only if the graft ended without its record being
5423            // settled (a swallowed error): the tree has moved on since, and
5424            // a reset to `pre` would discard the review fixes.
5425            if self.state.reviews.is_empty()
5426                && let Some(winner) = self.state.winner().cloned()
5427            {
5428                self.graft_restore(&winner.worktree, &rec.pre).await?;
5429            }
5430            if rec.outcome == GraftOutcome::WaitingForRestore {
5431                self.state.graft = None;
5432                self.state.save()?;
5433            } else {
5434                if let Some(g) = self.state.graft.as_mut() {
5435                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5436                }
5437                self.state.event(
5438                    "graft",
5439                    "rolled back: the previous round was interrupted; the winner is untouched",
5440                );
5441                self.state.save()?;
5442                return Ok(());
5443            }
5444        }
5445        let plan = match graft::plan(&self.state) {
5446            Ok(plan) => plan,
5447            Err(skip) => {
5448                if skip != graft::Skip::AlreadyDone {
5449                    self.graft_skipped(skip.reason());
5450                    self.state.save()?;
5451                }
5452                return Ok(());
5453            }
5454        };
5455        let Some(winner) = self.state.winner().cloned() else {
5456            return Ok(());
5457        };
5458        let wt = winner.worktree.clone();
5459        if !git::is_clean(&wt).await? {
5460            self.graft_skipped("the winner's worktree has uncommitted changes");
5461            self.state.save()?;
5462            return Ok(());
5463        }
5464        let pre = git::rev_parse(&wt, "HEAD").await?;
5465        // Saved before the fixer is called: a stop from here on is repaired
5466        // by the branch above on the next entry.
5467        self.state.graft = Some(GraftRecord {
5468            pre: pre.clone(),
5469            post: None,
5470            lines: None,
5471            limit: None,
5472            agent: None,
5473            outcome: GraftOutcome::Running,
5474            requested: graft::requested(&plan),
5475            adoption: None,
5476            adoption_error: None,
5477        });
5478        self.state.event(
5479            "graft",
5480            format!(
5481                "porting strengths of candidate(s) {} onto {}",
5482                plan.strengths
5483                    .iter()
5484                    .map(|(l, _, _)| l.to_string())
5485                    .collect::<Vec<_>>()
5486                    .join(", "),
5487                plan.winner
5488            ),
5489        );
5490        self.state.save()?;
5491
5492        let fix_prompt = prompt::graft(
5493            &self.state.instruction,
5494            plan.winner,
5495            &plan.strengths,
5496            &self.state.config.graph.language,
5497        );
5498        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5499        let sessions = self.state.config.graph.sessions;
5500        let artifacts = agent::artifacts_dir(&self.state.dir());
5501        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5502        let (_, seat, out) = self
5503            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5504                SeatJob {
5505                    prompt: fix_prompt.clone(),
5506                    spec,
5507                    seat,
5508                    cwd: wt.clone(),
5509                    timeout,
5510                    allow_write: true,
5511                    sessions,
5512                    artifacts: artifacts.clone(),
5513                    stem: "graft".to_owned(),
5514                    handover: None,
5515                }
5516            })
5517            .await;
5518        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5519            // Preserve the need to restore earlier fallback edits without
5520            // confusing an unstarted seat with an interrupted invocation.
5521            self.state.graft.as_mut().expect("graft record").outcome =
5522                GraftOutcome::WaitingForRestore;
5523            return self.stop_for_resource();
5524        }
5525        let mut why: Option<String> = None;
5526        match &out {
5527            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5528                why = Some("the fixer produced nothing usable".to_owned());
5529            }
5530            AgentOutcome::Ok(_) => {}
5531            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5532            AgentOutcome::Quota(o) => {
5533                self.state.quota.push(QuotaLoss::from_report(
5534                    seat.key.clone(),
5535                    "graft",
5536                    o.quota.as_ref(),
5537                ));
5538                why = Some("rate limited (quota)".to_owned());
5539            }
5540            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5541                why = Some(format!(
5542                    "the fixer failed: {}",
5543                    e.lines()
5544                        .next()
5545                        .unwrap_or("")
5546                        .chars()
5547                        .take(160)
5548                        .collect::<String>()
5549                ));
5550            }
5551        }
5552        let agent_id = seat.agent.clone();
5553        self.state.seats.insert(seat.key.clone(), seat);
5554
5555        let mut post = None;
5556        let mut lines = None;
5557        let _coordination = self.coordinate(&wt).await?;
5558        if why.is_none() {
5559            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5560            if let Ok(r) = &rescued {
5561                self.state.note_withheld("graft", &r.withheld);
5562            }
5563            let head = git::rev_parse(&wt, "HEAD").await?;
5564            // What is measured must be what gets reviewed and gated: a failed
5565            // rescue, or anything still uncommitted (withheld lockfiles
5566            // aside, which are never part of the tree), rejects the graft.
5567            let dirty = match &rescued {
5568                Ok(r) => git::status_porcelain(&wt)
5569                    .await
5570                    .map(|st| {
5571                        st.lines().any(|l| {
5572                            !r.withheld
5573                                .iter()
5574                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5575                        })
5576                    })
5577                    .unwrap_or(true),
5578                Err(_) => true,
5579            };
5580            if dirty {
5581                why = Some("the fixer left changes that could not be committed".to_owned());
5582            } else if head == pre {
5583                why = Some("the fixer changed nothing".to_owned());
5584            } else {
5585                lines = git::changed_lines(&wt, &pre, &head).await;
5586                post = Some(head);
5587            }
5588        }
5589        let (adoption, adoption_error) = match &out {
5590            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5591            _ => (None, None),
5592        };
5593        let requested = graft::requested(&plan);
5594        let outcome = match why {
5595            None => {
5596                self.state.event(
5597                    "graft",
5598                    format!(
5599                        "applied: {}",
5600                        lines.map_or_else(
5601                            || "changed lines unavailable".to_owned(),
5602                            |n| format!("{n} changed lines")
5603                        )
5604                    ),
5605                );
5606                GraftOutcome::Applied
5607            }
5608            Some(why) => {
5609                // Not settled until the restore is confirmed: the record
5610                // stays `Running`, so a resume retries it.
5611                crate::recovery::restore_repair(&wt, &pre)
5612                    .await
5613                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5614                self.state.event(
5615                    "graft",
5616                    format!("rolled back: {why}; the winner is untouched"),
5617                );
5618                GraftOutcome::RolledBack(why)
5619            }
5620        };
5621        self.state.graft = Some(GraftRecord {
5622            pre,
5623            post,
5624            lines,
5625            limit: None,
5626            agent: Some(agent_id),
5627            outcome,
5628            requested,
5629            adoption,
5630            adoption_error,
5631        });
5632        self.state.save()?;
5633        Ok(())
5634    }
5635
5636    // ----------------------------------------------------------------- fold
5637
5638    async fn fold_losers(&mut self) -> Result<()> {
5639        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5640            return Ok(());
5641        };
5642        if !self.state.candidate_preservation.is_empty() {
5643            bail!("candidate preservation incomplete; refusing cleanup");
5644        }
5645        let repo = self.state.repo.clone();
5646        let _coordination = self.coordinate(&repo).await?;
5647        let home = crate::run::home();
5648        let root = self.state.worktree_root();
5649        let isolated = crate::build_target::isolated(&self.state.config);
5650        let mut folded = Vec::new();
5651        for i in 0..self.state.candidates.len() {
5652            let c = &self.state.candidates[i];
5653            if c.label == winner || c.folded {
5654                continue;
5655            }
5656            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5657            let target = fold_target(&home, &root, &wt, isolated);
5658            remove_preserved_worktree(&repo, &wt).await?;
5659            reclaim_fold_target(&home, target);
5660            if git::branch_exists(&repo, &branch).await?
5661                && !git::branch_delete(&repo, &branch).await?
5662            {
5663                bail!("candidate branch removal refused");
5664            }
5665            self.state.candidates[i].folded = true;
5666            self.state.save()?;
5667            folded.push(label.to_string());
5668        }
5669        // The judges are finished; their checkouts are pure cost from here.
5670        for j in 1..=self.roles.judges.len() {
5671            let wt = root.join(format!("judge-{j}"));
5672            if wt.exists() {
5673                let target = fold_target(&home, &root, &wt, isolated);
5674                remove_read_seat_worktree(&mut self.state, &wt).await?;
5675                reclaim_fold_target(&home, target);
5676                self.state.save()?;
5677            }
5678        }
5679        // The design-deliberation stage is finished by the time a tally
5680        // exists — same reasoning as the judges above.
5681        if self.state.config.graph.advise {
5682            for k in 1..=self.state.config.graph.advisors {
5683                let wt = root.join(format!("advisor-{k}"));
5684                if wt.exists() {
5685                    let target = fold_target(&home, &root, &wt, isolated);
5686                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5687                    reclaim_fold_target(&home, target);
5688                    self.state.save()?;
5689                }
5690            }
5691        }
5692        if !folded.is_empty() {
5693            self.state
5694                .event("fold", format!("folded candidates {}", folded.join(", ")));
5695            self.state.save()?;
5696        }
5697        Ok(())
5698    }
5699
5700    // ------------------------------------------------------------ base sync
5701
5702    async fn hold_base_sync(&mut self) -> Result<bool> {
5703        self.hold_base_sync_as(None).await
5704    }
5705
5706    async fn hold_base_sync_kind(
5707        &mut self,
5708        kind: crate::base_sync_recovery::StopKind,
5709    ) -> Result<()> {
5710        self.hold_base_sync_as(Some(kind)).await?;
5711        Ok(())
5712    }
5713
5714    async fn hold_base_sync_as(
5715        &mut self,
5716        kind: Option<crate::base_sync_recovery::StopKind>,
5717    ) -> Result<bool> {
5718        if !self.state.base_sync_blocked() {
5719            self.state.base_sync_recovery.stop = None;
5720            return Ok(false);
5721        }
5722        let head = match self.state.winner() {
5723            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5724                .await
5725                .unwrap_or_default(),
5726            None => String::new(),
5727        };
5728        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5729            && !authorization.consumed
5730            && authorization.stop.head != head
5731        {
5732            authorization.refuse(format!(
5733                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5734                authorization.stop.head
5735            ));
5736        }
5737        self.state.record_base_sync_stop(&head);
5738        if let Some(kind) = kind {
5739            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5740            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5741                stop.kind = kind;
5742            }
5743        }
5744        self.state.save()?;
5745        Ok(true)
5746    }
5747
5748    async fn resume_legacy_sequencer_stop(
5749        &mut self,
5750        winner: &Candidate,
5751        scratch: &Path,
5752        head: &str,
5753    ) -> Result<()> {
5754        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5755
5756        if !resumable_sequencer_stop(&self.state)
5757            || legacy_sequencer_head(&self.state) != Some(head)
5758            || self.state.base_recovery_pending()
5759            || self
5760                .state
5761                .repair_grants
5762                .iter()
5763                .any(|grant| !grant.succeeded)
5764        {
5765            return Ok(());
5766        }
5767        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5768            return Ok(());
5769        };
5770        let owner = crate::queue::Queue::open().get(task)?;
5771        if owner.execution_runs().last() != Some(&self.state.id)
5772            || owner.status == crate::queue::TaskStatus::Done
5773            || owner.fresh_start
5774            || owner.review_branch.is_some()
5775            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5776        {
5777            return Ok(());
5778        }
5779
5780        let repo = self.state.repo.clone();
5781        let wait = repository_wait(&self.state, None);
5782        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5783        let common = crate::repo_lock::common_dir(&repo).await?;
5784        let op = self.state.base_sync_recovery.operations.last().unwrap();
5785        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5786            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5787            || git::current_branch(&winner.worktree).await?.as_deref()
5788                != Some(winner.branch.as_str())
5789            || common.is_none()
5790            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5791            || crate::repo_lock::common_dir(&owner.repo).await? != common
5792            || !git::is_clean(&winner.worktree).await?
5793        {
5794            return Ok(());
5795        }
5796        if scratch.try_exists()? {
5797            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5798            if admin.join("locked").try_exists()?
5799                || !git::git(
5800                    scratch,
5801                    &[
5802                        "status",
5803                        "--porcelain",
5804                        "--untracked-files=all",
5805                        "--ignored",
5806                    ],
5807                )
5808                .await?
5809                .is_empty()
5810            {
5811                return Ok(());
5812            }
5813            if git::checked_rebase_in_progress(scratch).await? {
5814                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5815                    || crate::rebase::rebase_target(scratch).await? != op.tip
5816                    || !git::unmerged_paths(scratch).await?.is_empty()
5817                {
5818                    return Ok(());
5819                }
5820            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5821                || git::rev_parse(scratch, "HEAD").await? != head
5822            {
5823                return Ok(());
5824            }
5825        }
5826
5827        self.state
5828            .base_sync_recovery
5829            .operations
5830            .last_mut()
5831            .unwrap()
5832            .finished = false;
5833        let diagnostic = self
5834            .state
5835            .base_sync
5836            .as_mut()
5837            .unwrap()
5838            .conflict
5839            .take()
5840            .unwrap();
5841        self.state.base_sync_recovery.stop = None;
5842        self.state.event(
5843            "rebase",
5844            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5845        );
5846        self.state.save()
5847    }
5848
5849    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5850    /// anything verifies it.
5851    ///
5852    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5853    /// read whatever is checked out in the winner's worktree. Left alone that
5854    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5855    /// it when the run *branched* - and a run takes long enough that the base
5856    /// has usually moved by the time it gets here. A gate that ran there
5857    /// answers "green on the commit this run started from", not "green on
5858    /// what is about to land", and the difference showed up three times in
5859    /// one day as a green run whose merge would have reverted a file another
5860    /// pull request had already landed.
5861    ///
5862    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5863    /// `land::Step::Rebase` calls, rather than a second implementation of the
5864    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5865    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5866    /// doc warns about ("two answers to a question nobody notices until a
5867    /// diff is wrong").
5868    ///
5869    /// Foreign-checkout reviews instead merge the base into the owned shadow
5870    /// worktree, preserving the ancestry required for fast-forward delivery.
5871    /// A conflicting merge is aborted and held for operator resolution.
5872    ///
5873    /// A conflict is not the end of the road: the standing rebase is handed
5874    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5875    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5876    /// land). Once it finishes, review and the gate run as usual on the
5877    /// rebased tree, which is where a breakage the new base caused is caught
5878    /// by the ordinary gate-fix round. magi resolves nothing itself.
5879    ///
5880    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5881    /// the current durable recovery interval, bounds how often the base is
5882    /// synchronized during active recovery (lifetime attempts remain evidence).
5883    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5884    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5885    /// what was tried (rounds spent, paths still conflicted) and the branch
5886    /// and worktree stay exactly as they were - untouched, for a person to
5887    /// look at - which is also what makes re-entering this function
5888    /// afterwards a no-op instead of a second attempt at the same wall. A
5889    /// push failure ends the same way.
5890    async fn sync_to_base(&mut self) -> Result<()> {
5891        if self.state.status == RunStatus::AlreadyInBase {
5892            return Ok(());
5893        }
5894        self.hold_base_sync().await?;
5895        let Some(winner) = self.state.winner().cloned() else {
5896            return Ok(());
5897        };
5898
5899        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5900
5901        let repo = self.state.repo.clone();
5902        let remote = self.state.config.merge.remote.clone();
5903        let base_branch = self.state.base_branch.clone();
5904        let tracking = format!("{remote}/{base_branch}");
5905
5906        let fetched_base =
5907            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5908        if !fetched_base
5909            && self
5910                .state
5911                .base_sync_recovery
5912                .stop
5913                .as_ref()
5914                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5915        {
5916            self.state.event(
5917                "land",
5918                "cannot recheck recorded public branch divergence without a fresh base",
5919            );
5920            self.state.save()?;
5921            return Ok(());
5922        }
5923        // No network, or the remote never had this branch: the run already
5924        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5925        // otherwise), and one that got this far is not blocked by a fetch
5926        // that fails now. It just has no newer tip to compare against.
5927        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5928            return Ok(());
5929        };
5930
5931        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5932        self.state.ensure_base_episode();
5933        let scratch = self.state.dir().join("base-sync");
5934        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
5935            .await?;
5936        let conflicted = self
5937            .state
5938            .base_sync
5939            .as_ref()
5940            .is_some_and(|s| s.conflict.is_some());
5941        let mut pending = self.state.pending_base_operation().cloned();
5942        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
5943        {
5944            Ok(active) => active,
5945            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
5946            Err(error) => return Err(error),
5947        };
5948        if in_progress {
5949            // Older resource stops predate operation reservations. Import the
5950            // standing Git operation, never retarget it to today's main.
5951            if pending.is_none()
5952                && self.state.base_sync_recovery.operations.is_empty()
5953                && !conflicted
5954                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5955                    .await
5956                    .ok()
5957                    .as_deref()
5958                    == Some(head.as_str())
5959                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5960                && git::is_clean(&winner.worktree).await?
5961            {
5962                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5963                if self.state.base_sync.is_none() {
5964                    self.state.base_sync = Some(BaseSync {
5965                        tip: saved_tip.clone(),
5966                        behind: 0,
5967                        attempts: 0,
5968                        conflict: None,
5969                        already_in: None,
5970                    });
5971                }
5972                self.state.reserve_base_operation(&head, &saved_tip);
5973                self.state.event(
5974                    "base-recovery",
5975                    "imported standing legacy rebase as a spent synchronization reservation",
5976                );
5977                self.state.save()?;
5978                pending = self.state.base_sync_recovery.operations.last().cloned();
5979            }
5980            let expected = pending.as_ref().map(|op| op.tip.as_str());
5981            if expected.is_none()
5982                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5983            {
5984                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5985                if self.state.base_sync.is_none() {
5986                    self.state.base_sync = Some(BaseSync {
5987                        tip: tip.clone(),
5988                        behind: 0,
5989                        attempts: 0,
5990                        conflict: None,
5991                        already_in: None,
5992                    });
5993                }
5994                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5995                self.state.event("land", why);
5996                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5997                    .await?;
5998                return Ok(());
5999            }
6000        }
6001        if let Some(op) = &pending {
6002            // A replay may add the pinned base's commits, never foreign work.
6003            let mut replay_proven =
6004                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6005            if !replay_proven && !in_progress && scratch.try_exists()? {
6006                let wait = repository_wait(&self.state, None);
6007                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6008                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6009                    Ok(true) => {
6010                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6011                        self.state.save()?;
6012                        git::worktree_remove(&repo, &scratch).await.ok();
6013                        replay_proven = true;
6014                    }
6015                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6016                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6017                }
6018            }
6019            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6020                if self.state.foreign_checkout.is_some() {
6021                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6022                        .await
6023                        .ok()
6024                        .as_deref()
6025                        == Some(op.head.as_str())
6026                        && git::rev_parse(&repo, &format!("{head}^2"))
6027                            .await
6028                            .ok()
6029                            .as_deref()
6030                            == Some(op.tip.as_str());
6031                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6032                    .await
6033                    .is_ok_and(|m| m.is_empty())
6034                    && let Ok(added) =
6035                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6036                {
6037                    replay_proven = true;
6038                    for commit in added {
6039                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6040                            replay_proven = false;
6041                            break;
6042                        }
6043                    }
6044                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6045                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6046                }
6047            }
6048            // Never retarget an operation across a crash, even if main moved.
6049            // sync_to_head resets and cleans with -x, so even ignored untracked
6050            // files must stop recovery independently of the old tracked tree.
6051            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6052                || (head != op.head
6053                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6054                        .await?
6055                        .is_empty())
6056                || (!git::is_clean(&winner.worktree).await?
6057                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6058                        .await
6059                        .is_ok_and(|o| o.ok()))
6060                || !replay_proven
6061            {
6062                let why = format!(
6063                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6064                    op.id
6065                );
6066                let sync = self
6067                    .state
6068                    .base_sync
6069                    .as_mut()
6070                    .context("reserved synchronization has no lifetime accounting")?;
6071                sync.conflict = Some(why.clone());
6072                self.state.event("land", why);
6073                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6074                    .await?;
6075                return Ok(());
6076            }
6077            if head != op.head {
6078                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6079            }
6080            tip = op.tip.clone();
6081        }
6082        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6083        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6084        if pending.is_none()
6085            && !conflicted
6086            && fetched_base
6087            && self
6088                .state
6089                .base_sync_recovery
6090                .episodes
6091                .last()
6092                .is_some_and(|e| e.boundary.is_some())
6093            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6094            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6095            && owner.execution_runs().last() == Some(&self.state.id)
6096            && owner.status != crate::queue::TaskStatus::Done
6097            && !owner.fresh_start
6098            && owner.review_branch.is_none()
6099            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6100            && let Some(approval) = owner.resumption.as_ref()
6101            && approval.instruction == owner.instruction
6102            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6103            && git::is_clean(&winner.worktree).await?
6104            && self.state.renew_base_episode(&task, approval, &head, &tip)
6105        {
6106            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6107            self.state.save()?;
6108        }
6109
6110        // Before any rebase, and before a recorded conflict is honoured: a
6111        // branch whose change reached the base under other commit ids has
6112        // nothing to rebase and nothing to conflict with, and a run that
6113        // already stopped on that phantom conflict recovers here on resume.
6114        // `behind == 0` with head == tip is a branch the base has since taken
6115        // in whole, whether or not a conflict was ever recorded: the ancestry
6116        // proof must still run (`classify` ignores a head still on the start
6117        // commit).
6118        if (behind > 0 || conflicted || head == tip)
6119            && self
6120                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6121                .await?
6122        {
6123            return Ok(());
6124        }
6125        if conflicted && self.state.base_recovery_pending() {
6126            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6127            let owner =
6128                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6129            let owner_valid = owner.as_ref().is_ok_and(|t| {
6130                t.execution_runs().last() == Some(&self.state.id)
6131                    && t.assignment_accepts(&self.state)
6132                    && t.status != crate::queue::TaskStatus::Done
6133                    && !t.fresh_start
6134                    && t.review_branch.is_none()
6135            });
6136            let invalidation = if !owner_valid {
6137                Some("latest task ownership changed")
6138            } else if !owner.as_ref().is_ok_and(|t| {
6139                authorization
6140                    .generation
6141                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6142            }) {
6143                Some("owner approval generation changed")
6144            } else if authorization.question.as_ref().is_some_and(|question| {
6145                !crate::base_recovery_control::decision_current(
6146                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6147                    &self.state,
6148                    &authorization.task,
6149                    question,
6150                )
6151            }) {
6152                Some("recovery decision ownership, routing or stop evidence changed")
6153            } else if authorization.request.is_some()
6154                && !owner
6155                    .as_ref()
6156                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6157            {
6158                Some("owner decision changed")
6159            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6160                && !authorization.scope.as_ref().is_some_and(|scope| {
6161                    scope.preparation_digest.is_some()
6162                        && scope.preparation_digest == self.state.preparation_digest(&head)
6163                })
6164            {
6165                Some("scratch preparation stop evidence changed")
6166            } else if let Some(scope) = &authorization.scope {
6167                if scope.tip != tip {
6168                    Some("fetched base changed")
6169                } else if !self
6170                    .state
6171                    .base_sync_recovery
6172                    .episodes
6173                    .last()
6174                    .is_some_and(|e| e.id == scope.episode)
6175                {
6176                    Some("active synchronization interval changed")
6177                } else if !owner
6178                    .as_ref()
6179                    .is_ok_and(|t| t.instruction == scope.instruction)
6180                {
6181                    Some("task instruction changed")
6182                } else {
6183                    None
6184                }
6185            } else {
6186                None
6187            };
6188            if let Some(reason) = invalidation {
6189                let authorization = self
6190                    .state
6191                    .base_sync_recovery
6192                    .authorizations
6193                    .last_mut()
6194                    .unwrap();
6195                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6196                self.state.save()?;
6197                return Ok(());
6198            }
6199            if !fetched_base
6200                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6201                || !git::is_clean(&winner.worktree).await?
6202                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6203            {
6204                return Ok(());
6205            }
6206            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6207                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6208            }
6209        }
6210        let recovery = conflicted && self.state.consume_base_recovery(&head);
6211        if conflicted {
6212            // Consumption (including a refused changed HEAD) is durable before Git.
6213            self.state.save()?;
6214            if !recovery {
6215                return Ok(());
6216            }
6217        }
6218
6219        if behind == 0 {
6220            // A fixer-finished rebase moves the branch ref before the
6221            // winner's worktree is told (`sync_to_head` below). A run that
6222            // died in between resumes here with `behind == 0` and a tree still
6223            // holding the pre-rebase files, which review and the gate would
6224            // then read. That state is exactly: HEAD moved off the tip the
6225            // rebase started from, yet the tree is still identical to that
6226            // tip. A tree with edits of its own differs from it, so nothing
6227            // is thrown away.
6228            if let Some(from) = self
6229                .state
6230                .rebase_fixes
6231                .iter()
6232                .rev()
6233                .find_map(|r| r.from.clone())
6234                && from != head
6235                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6236                    .await
6237                    .is_ok_and(|o| o.ok())
6238            {
6239                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6240            }
6241            // An earlier attempt may have rebased the branch locally and died
6242            // before pushing it (only the fresh-rebase arm below pushes).
6243            // Publish it now, so the plain push at PR time is not refused as
6244            // a non-fast-forward. A run already holding a recorded conflict
6245            // never reaches here; that case is out of scope.
6246            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6247            if let Some(why) = &conflict {
6248                self.state.status = RunStatus::Blocked;
6249                self.state.event("land", why.clone());
6250            }
6251            self.state.base_sync = Some(BaseSync {
6252                tip,
6253                behind: 0,
6254                attempts,
6255                conflict,
6256                already_in: None,
6257            });
6258            if pending.is_some() {
6259                self.state.finish_base_operation(Some(&head));
6260            }
6261            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6262                .await?;
6263            self.state.save()?;
6264            return Ok(());
6265        }
6266
6267        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6268            let why = format!(
6269                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6270                 synchronization(s); synchronizing again would only race it",
6271                winner.branch
6272            );
6273            self.state.status = RunStatus::Blocked;
6274            self.state.base_sync = Some(BaseSync {
6275                tip,
6276                behind,
6277                attempts,
6278                conflict: Some(why.clone()),
6279                already_in: None,
6280            });
6281            self.state.event("land", why);
6282            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6283                .await?;
6284            self.state.save()?;
6285            return Ok(());
6286        }
6287
6288        if self.state.foreign_checkout.is_some() {
6289            // Delivery to the operator's checkout is fast-forward only. A
6290            // rebase here would discard its saved head from our ancestry.
6291            let wait = repository_wait(&self.state, None);
6292            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6293            if self.state.base_sync.is_none() {
6294                self.state.base_sync = Some(BaseSync {
6295                    tip: tip.clone(),
6296                    behind,
6297                    attempts: 0,
6298                    conflict: None,
6299                    already_in: None,
6300                });
6301            }
6302            self.state.reserve_base_operation(&head, &tip);
6303            self.state.save()?;
6304            let merged = git::git_raw(
6305                &winner.worktree,
6306                &[
6307                    "-c",
6308                    "core.hooksPath=/dev/null",
6309                    "merge",
6310                    "--no-ff",
6311                    "--no-autostash",
6312                    "--no-edit",
6313                    "-m",
6314                    &format!("Merge {tracking} before verifying"),
6315                    &tip,
6316                ],
6317            )
6318            .await?;
6319            let conflict = if merged.ok() {
6320                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6321                self.state.event(
6322                    "land",
6323                    format!("merged {tracking} into {} before verifying", winner.branch),
6324                );
6325                None
6326            } else {
6327                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6328                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6329                }
6330                let why = format!(
6331                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6332                    winner.branch,
6333                    merged.stderr.chars().take(600).collect::<String>()
6334                );
6335                self.state.status = RunStatus::Blocked;
6336                self.state.event("land", &why);
6337                Some(why)
6338            };
6339            let synced = conflict.is_none();
6340            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6341            self.state
6342                .finish_base_operation(synced.then_some(fresh.as_str()));
6343            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6344            self.state.base_sync = Some(BaseSync {
6345                tip,
6346                behind: if synced { 0 } else { behind },
6347                attempts,
6348                conflict,
6349                already_in: None,
6350            });
6351            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6352                .await?;
6353            self.state.save()?;
6354            return Ok(());
6355        }
6356
6357        self.state.event(
6358            "land",
6359            format!(
6360                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6361                winner.branch
6362            ),
6363        );
6364        self.state.save()?;
6365
6366        // The remote's copy of the branch, read now and only if the fetch
6367        // really succeeded (a stale tracking ref must never pin a lease). It is
6368        // pushed over after a rebase only when it is a commit this branch
6369        // already contains, by ancestry or by patch (an earlier rebase of ours
6370        // that never reached the remote): anything else is somebody else's work.
6371        let branch_tracking = format!("{remote}/{}", winner.branch);
6372        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6373        let remote_tip = if self.state.task_pr_branch().is_none()
6374            && matches!(&fetched_branch, Ok(o) if o.ok())
6375        {
6376            git::rev_parse(&repo, &branch_tracking).await.ok()
6377        } else {
6378            None
6379        };
6380        // A remote tip this branch does not contain is somebody else's work:
6381        // rebasing would leave a local tip that can never be pushed. Stop
6382        // before touching anything and say so.
6383        if let Some(theirs) = &remote_tip
6384            && !git::is_ancestor(&repo, theirs, &head).await
6385            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6386                .await
6387                .is_ok_and(|missing| missing.is_empty())
6388        {
6389            let why = format!(
6390                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6391                 them",
6392                short(theirs),
6393                winner.branch
6394            );
6395            self.state.status = RunStatus::Blocked;
6396            self.state.base_sync = Some(BaseSync {
6397                tip,
6398                behind,
6399                attempts,
6400                conflict: Some(why.clone()),
6401                already_in: None,
6402            });
6403            self.state.event("land", why);
6404            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6405                .await?;
6406            self.state.save()?;
6407            return Ok(());
6408        }
6409
6410        if self.state.base_sync.is_none() {
6411            self.state.base_sync = Some(BaseSync {
6412                tip: tip.clone(),
6413                behind,
6414                attempts: 0,
6415                conflict: None,
6416                already_in: None,
6417            });
6418        }
6419        let scratch = self.state.dir().join("base-sync");
6420        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6421        {
6422            if error.is::<crate::repo_lock::ResourceBlocked>() {
6423                return Ok(());
6424            }
6425            return Err(error);
6426        }
6427        self.state.reserve_base_operation(&head, &tip);
6428        self.state.save()?;
6429        let rebased =
6430            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6431                .await
6432            {
6433                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6434                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6435                Err(e) => Err(e),
6436            };
6437        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6438        let stop_kind = match &rebased {
6439            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6440            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6441            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6442        };
6443        match rebased {
6444            Ok(None) => {
6445                // The branch ref moved, but a worktree that already had it
6446                // checked out (the winner's) was not told; sync its index and
6447                // files before anything reads them.
6448                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6449                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6450                self.state.finish_base_operation(Some(&fresh));
6451                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6452                let mut conflict = None;
6453                if let Some(pinned) = &remote_tip {
6454                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6455                    match pushed {
6456                        Ok(o) if o.ok() => self.state.event(
6457                            "land",
6458                            format!("pushed rebased {} to {remote}", winner.branch),
6459                        ),
6460                        Ok(o) => {
6461                            conflict = Some(format!(
6462                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6463                                winner.branch,
6464                                short(pinned),
6465                                o.stderr.chars().take(600).collect::<String>()
6466                            ));
6467                        }
6468                        Err(e) => {
6469                            conflict = Some(format!(
6470                                "rebased {} locally but could not push it: {e:#}",
6471                                winner.branch
6472                            ));
6473                        }
6474                    }
6475                }
6476                if let Some(why) = &conflict {
6477                    self.state.status = RunStatus::Blocked;
6478                    self.state.event("land", why.clone());
6479                }
6480                self.state.base_sync = Some(BaseSync {
6481                    tip: tip.clone(),
6482                    behind: 0,
6483                    attempts,
6484                    conflict,
6485                    already_in: None,
6486                });
6487                self.state
6488                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6489            }
6490            Ok(Some(conflict)) => {
6491                self.state.finish_base_operation(None);
6492                let why = format!(
6493                    "{} conflicts with {tracking} and did not rebase: {}",
6494                    winner.branch,
6495                    conflict.chars().take(600).collect::<String>()
6496                );
6497                self.state.status = RunStatus::Blocked;
6498                self.state.base_sync = Some(BaseSync {
6499                    tip,
6500                    behind,
6501                    attempts,
6502                    conflict: Some(why.clone()),
6503                    already_in: None,
6504                });
6505                self.state.event("land", why);
6506            }
6507            // A refused Git write or a busy repository: nothing is wrong with
6508            // the branch. The scratch rebase stays standing and the run
6509            // resumes into it (`base_sync` must not claim a conflict).
6510            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6511                self.state.save()?;
6512                return Ok(());
6513            }
6514            Err(e) => {
6515                self.state.finish_base_operation(None);
6516                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6517                self.state.status = RunStatus::Blocked;
6518                self.state.base_sync = Some(BaseSync {
6519                    tip,
6520                    behind,
6521                    attempts,
6522                    conflict: Some(why.clone()),
6523                    already_in: None,
6524                });
6525                self.state.event("land", why);
6526            }
6527        }
6528        if !self.state.base_sync_blocked() {
6529            self.state.base_sync_recovery.stop = None;
6530        }
6531        self.hold_base_sync_kind(stop_kind).await?;
6532        self.state.save()?;
6533        Ok(())
6534    }
6535
6536    /// Push a branch an earlier attempt rebased locally but never published,
6537    /// pinned to the remote tip read right after a successful fetch. Returns
6538    /// the reason when the run must stop; `None` when there was nothing to do
6539    /// (no remote copy, the same tip, or a remote copy this branch already
6540    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6541    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6542        // Task competitions publish only after the PR text gate, to their
6543        // public head; never resurrect a candidate branch on the remote.
6544        if self.state.task_pr_branch().is_some() {
6545            return None;
6546        }
6547        let repo = self.state.repo.clone();
6548        let remote = self.state.config.merge.remote.clone();
6549        let fetched = git::fetch(&repo, &remote, branch).await;
6550        if !matches!(&fetched, Ok(o) if o.ok()) {
6551            return None;
6552        }
6553        let branch_tracking = format!("{remote}/{branch}");
6554        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6555        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6556            return None;
6557        }
6558        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6559            .await
6560            .is_ok_and(|missing| missing.is_empty())
6561        {
6562            return Some(format!(
6563                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6564                 them",
6565                short(&theirs)
6566            ));
6567        }
6568        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6569            Ok(o) if o.ok() => {
6570                self.state
6571                    .event("land", format!("pushed rebased {branch} to {remote}"));
6572                None
6573            }
6574            Ok(o) => Some(format!(
6575                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6576                 someone may have pushed): {}",
6577                short(&theirs),
6578                o.stderr.chars().take(600).collect::<String>()
6579            )),
6580            Err(e) => Some(format!(
6581                "{branch} is rebased locally but could not be pushed: {e:#}"
6582            )),
6583        }
6584    }
6585
6586    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6587    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6588    /// whether it did.
6589    ///
6590    /// Checked only when the base is ahead of the branch. A failing check is
6591    /// "not proven" - the ordinary rebase path then decides - never a reason to
6592    /// stop the run.
6593    ///
6594    /// The remote copy of the branch is held to the same standard as the local
6595    /// one: if it carries a tip this worktree does not, that tip must itself be
6596    /// proven in the base, or nothing is settled (a pull request would
6597    /// otherwise be closed over commits nobody checked). The pull request is
6598    /// closed *before* the terminal status is saved; if that fails for a
6599    /// reason other than a refusal (no network, a `gh` error) the run is left
6600    /// `Blocked` with the reason as its conflict, which a resume retries -
6601    /// the same recovery a phantom conflict gets.
6602    async fn settle_already_in(
6603        &mut self,
6604        branch: &str,
6605        tip: &str,
6606        head: &str,
6607        attempts: usize,
6608        behind: usize,
6609    ) -> Result<bool> {
6610        let repo = self.state.repo.clone();
6611        let remote = self.state.config.merge.remote.clone();
6612        let start = self.state.base_commit.clone();
6613        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6614            Ok(Some(e)) => e,
6615            Ok(None) => return Ok(false),
6616            Err(e) => {
6617                tracing::warn!("already-in-base check for {branch}: {e:#}");
6618                return Ok(false);
6619            }
6620        };
6621        let mut verified = vec![head.to_owned()];
6622        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6623        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6624        let divergence = self
6625            .state
6626            .base_sync_recovery
6627            .stop
6628            .as_ref()
6629            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6630        if matches!(&fetched, Ok(o) if o.ok()) {
6631            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6632                Ok(theirs) if theirs != head => {
6633                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6634                        Ok(Some(_)) => verified.push(theirs),
6635                        _ => return Ok(false),
6636                    }
6637                }
6638                Err(_) if divergence => return Ok(false),
6639                _ => {}
6640            }
6641        } else if divergence
6642            && !matches!(
6643                git::remote_has_branch(&repo, &remote, &public_branch).await,
6644                Ok(false)
6645            )
6646        {
6647            // A failed fetch cannot discharge a recorded divergence.
6648            return Ok(false);
6649        }
6650        let base_branch = self.state.base_branch.clone();
6651        let message = format!(
6652            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6653             land",
6654            evidence.names(),
6655            evidence.proof.as_str()
6656        );
6657        let closed =
6658            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6659                .await;
6660        match closed {
6661            Ok(Ok(url)) => self
6662                .state
6663                .event("land", format!("closed {url}: superseded on {base_branch}")),
6664            Ok(Err(why)) => self
6665                .state
6666                .event("land", format!("did not close a pull request: {why}")),
6667            Err(e) => {
6668                let why = format!(
6669                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6670                     not be closed ({e:#}); resume to retry"
6671                );
6672                self.state.status = RunStatus::Blocked;
6673                self.state.base_sync = Some(BaseSync {
6674                    tip: tip.to_owned(),
6675                    behind,
6676                    attempts,
6677                    conflict: Some(why.clone()),
6678                    already_in: None,
6679                });
6680                self.state.event("land", why);
6681                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6682                    .await?;
6683                self.state.save()?;
6684                return Ok(true);
6685            }
6686        }
6687        self.state.status = RunStatus::AlreadyInBase;
6688        self.state.base_sync_recovery.stop = None;
6689        self.state.base_sync = Some(BaseSync {
6690            tip: tip.to_owned(),
6691            behind,
6692            attempts,
6693            conflict: None,
6694            already_in: Some(evidence),
6695        });
6696        self.state.event("land", message);
6697        self.state.save()?;
6698        self.settle_questions();
6699        Ok(true)
6700    }
6701
6702    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6703    /// last landed the winner on, once it has run, else the commit the run
6704    /// branched from.
6705    ///
6706    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6707    /// and `vote` all happen before there is a winner to rebase, so they
6708    /// compare every candidate against the branch point on purpose, and a
6709    /// base that moves after they are already done cannot change an answer
6710    /// they already gave.
6711    fn landing_base(&self) -> String {
6712        self.state
6713            .base_sync
6714            .as_ref()
6715            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6716    }
6717
6718    // ------------------------------------------------------- operator fix
6719
6720    /// Route specific, already-recorded review findings to a fixer for a
6721    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6722    /// entry point.
6723    ///
6724    /// Distinct from `review_loop`'s own fix step in three ways: it never
6725    /// runs a reviewer wave, it never spends review-round budget, and what
6726    /// happened is recorded as an [`OperatorFixRequest`] appended to
6727    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6728    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6729    /// and vote must never be rewritten to look like a manufactured blocking
6730    /// verdict.
6731    ///
6732    /// Only meaningful once review has actually concluded: `Ready` (handed
6733    /// off with findings still open, or simply concluded clean while minor
6734    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6735    /// gate failed). Everything else is refused: a run still in progress
6736    /// should simply be resumed, and a `Merged` run's branch has already
6737    /// landed — reopening *this* run's own record cannot change that, so the
6738    /// answer there is a fresh `magi review <branch>`.
6739    ///
6740    /// A real commit here re-verifies through a fresh, ordinary review-only
6741    /// run on the same branch ([`Self::review`]) rather than reopening this
6742    /// run's own `review_loop`: once any round in this run's history went
6743    /// clean, `review_conclusion` treats that as permanent by design (the
6744    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6745    /// way to force one more genuine reviewer wave out of *this* run without
6746    /// either rewriting history or weakening that guarantee for every other
6747    /// caller. A review-only run costs nothing extra — no implementation, no
6748    /// judging, no vote — and exercises the exact same review → verify →
6749    /// gate → (human) merge path, unmodified.
6750    pub async fn fix_selected(
6751        &mut self,
6752        ids: &[String],
6753        reason: &str,
6754        allow_stale: bool,
6755    ) -> Result<()> {
6756        let reason = reason.trim();
6757        if reason.is_empty() {
6758            bail!("a fix request needs a reason — that is the operator's own record of why");
6759        }
6760        if ids.is_empty() {
6761            bail!("no finding id given");
6762        }
6763        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6764            bail!(
6765                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6766                 has already concluded — can be given a targeted fix. A run still \
6767                 in progress should simply be resumed; a `merged` run's branch has \
6768                 already landed, so its answer is a fresh `magi review <branch>`, \
6769                 not reopening this run's own record",
6770                self.state.id,
6771                self.state.status.as_str()
6772            );
6773        }
6774        // Reassignment shares this claim through its atomic task save. Check
6775        // the canonical run identity inside it, before preflight or any await.
6776        let _claim = FixClaim::acquire(&self.state.dir())?;
6777        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6778        let home = crate::run::home();
6779        // The ordinary driver takes these same locks at admission. Keep the
6780        // execution lease through the fix, but never the owner lock across Git
6781        // or agent awaits.
6782        let execution = {
6783            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6784            let disk = RunState::load(&self.state.id)?;
6785            crate::pr_head::ensure_owner(&disk)?;
6786            anyhow::ensure!(
6787                disk.status == self.state.status && disk.released_to.is_none(),
6788                "run changed since it was loaded; reload before fixing"
6789            );
6790            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6791            anyhow::ensure!(
6792                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6793                "run {} is currently being worked on or its ownership is unknown",
6794                disk.id
6795            );
6796            let lease = crate::driver::maintenance(&home, &disk.id).context(
6797                "run is currently being worked on or its execution lease is unavailable",
6798            )?;
6799            self.state = disk;
6800            lease
6801        };
6802        let Some(winner) = self.state.winner().cloned() else {
6803            bail!("run {} has no winning candidate to fix", self.state.id);
6804        };
6805        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6806            bail!(
6807                "branch `{}` no longer exists; this run cannot be extended",
6808                winner.branch
6809            );
6810        }
6811        // Resolve every id before spending anything — an unknown id refuses
6812        // the whole request rather than silently dropping it — and dedup
6813        // while keeping the operator's own order.
6814        let mut seen = BTreeSet::new();
6815        let mut findings = Vec::new();
6816        let mut missing = Vec::new();
6817        for id in ids {
6818            if !seen.insert(id.clone()) {
6819                continue;
6820            }
6821            match self.state.finding(id) {
6822                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6823                    id: f.id.clone(),
6824                    severity: f.severity,
6825                    reviewer_vote: rec.vote,
6826                    round: round.round,
6827                    round_head: round.head.clone(),
6828                    reviewer: rec.reviewer,
6829                    agent: rec.agent.clone(),
6830                    file: f.file.clone(),
6831                    line: f.line,
6832                    title: f.title.clone(),
6833                    detail: f.detail.clone(),
6834                    outcome: OperatorFixOutcome::Pending,
6835                }),
6836                None => missing.push(id.clone()),
6837            }
6838        }
6839        if !missing.is_empty() {
6840            bail!(
6841                "unknown finding id(s): {}; nothing was changed",
6842                missing.join(", ")
6843            );
6844        }
6845
6846        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6847        let stale_details: Vec<(String, String)> = findings
6848            .iter()
6849            .filter(|f| f.round_head != head_at_request)
6850            .map(|f| (f.id.clone(), f.round_head.clone()))
6851            .collect();
6852        let stale = !stale_details.is_empty();
6853        if stale && !allow_stale {
6854            bail!(
6855                "the branch has moved since some finding(s) were raised — {} — now \
6856                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6857                stale_details
6858                    .iter()
6859                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6860                    .collect::<Vec<_>>()
6861                    .join(", "),
6862                short(&head_at_request)
6863            );
6864        }
6865
6866        let request = OperatorFixRequest {
6867            requested_at: Timestamp::now(),
6868            reason: reason.to_owned(),
6869            findings,
6870            head_at_request: head_at_request.clone(),
6871            allow_stale,
6872            stale,
6873            fix: None,
6874            result_head: None,
6875            follow_up_review_run: None,
6876        };
6877        self.state.event(
6878            "fix",
6879            format!(
6880                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6881                request.findings.len(),
6882                request
6883                    .findings
6884                    .iter()
6885                    .map(|f| f.id.as_str())
6886                    .collect::<Vec<_>>()
6887                    .join(", "),
6888            ),
6889        );
6890        // Recorded now, before any worktree work or the fixer call itself —
6891        // and re-saved at each checkpoint below: a crash at any point after
6892        // this (mid fixer call, mid follow-up review) must not lose the fact
6893        // that this was requested, for which findings, and why. Everything
6894        // past this point reads and writes through `request_index` rather
6895        // than a local variable, since `request` itself is moved here.
6896        self.state.operator_fixes.push(request);
6897        self.state.save()?;
6898        let request_index = self.state.operator_fixes.len() - 1;
6899
6900        // A fresh, dedicated worktree for this one call, never the winner's
6901        // own worktree in place: that one may already be gone (folded away),
6902        // and reusing it in place would leave the branch checked out there
6903        // when the follow-up review below tries to check it out again. Freed
6904        // immediately after, either way — but only once confirmed clean:
6905        // `worktree_remove` is a `git worktree remove --force`, which would
6906        // otherwise discard uncommitted work left there by the operator or
6907        // another process before this had a chance to even look at it.
6908        let repo = self.state.repo.clone();
6909        let coordination = self.coordinate(&repo).await?;
6910        if winner.worktree.exists() {
6911            // Lockfiles a rescue commit withheld stay untracked on purpose and
6912            // are already recorded; they are not the operator's work to protect.
6913            let dirty = git::git(
6914                &winner.worktree,
6915                &["status", "--porcelain", "--untracked-files=all"],
6916            )
6917            .await?;
6918            let only_withheld = dirty.lines().all(|l| {
6919                l.strip_prefix("?? ")
6920                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6921            });
6922            if !only_withheld {
6923                bail!(
6924                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6925                     discard them first",
6926                    winner.worktree.display()
6927                );
6928            }
6929            git::worktree_remove(&self.state.repo, &winner.worktree)
6930                .await
6931                .ok();
6932        }
6933        let fix_worktree = self.state.worktree_root().join("operator-fix");
6934        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6935        git::git(
6936            &self.state.repo,
6937            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6938        )
6939        .await
6940        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6941        if !git::is_clean(&fix_worktree).await? {
6942            git::worktree_remove(&self.state.repo, &fix_worktree)
6943                .await
6944                .ok();
6945            bail!(
6946                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6947                winner.branch
6948            );
6949        }
6950        let repo_for_setup = self.state.repo.clone();
6951        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6952            Ok(()) => {
6953                worktree_setup::prepare_with(
6954                    &self.state.config,
6955                    &repo_for_setup,
6956                    &fix_worktree,
6957                    crate::build_target::Coordination::Held(coordination.as_ref()),
6958                )
6959                .await
6960            }
6961            Err(e) => Err(e),
6962        };
6963        if let Err(e) = setup {
6964            git::worktree_remove(&self.state.repo, &fix_worktree)
6965                .await
6966                .ok();
6967            return Err(e);
6968        }
6969
6970        // This explicit operator request retries availability independently
6971        // of execute(); the previous call has already saved and cleaned up.
6972        self.state.resource_block = None;
6973
6974        let run_id = self.state.id.clone();
6975        let prompts = self.state.config.prompts.clone();
6976        let language = self.state.config.graph.language.clone();
6977        let sessions = self.state.config.graph.sessions;
6978        let artifacts = agent::artifacts_dir(&self.state.dir());
6979        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6980            .findings
6981            .iter()
6982            .map(|f| Finding {
6983                id: f.id.clone(),
6984                severity: f.severity,
6985                file: f.file.clone(),
6986                line: f.line,
6987                title: f.title.clone(),
6988                detail: f.detail.clone(),
6989            })
6990            .collect();
6991        let fix_prompt = prompt::operator_fix_in(
6992            &self.state.instruction,
6993            &finding_list,
6994            reason,
6995            &stale_details,
6996            &head_at_request,
6997            &language,
6998            &self.state.config.graph.github_language,
6999        );
7000        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7001        drop(coordination);
7002        let (job, seat, out) = self
7003            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7004                prompt: fix_prompt.clone(),
7005                spec,
7006                seat,
7007                cwd: fix_worktree.clone(),
7008                timeout,
7009                allow_write: true,
7010                sessions,
7011                artifacts: artifacts.clone(),
7012                stem: "operator-fix".to_owned(),
7013                handover: None,
7014            })
7015            .await;
7016        let agent_id = seat.agent.clone();
7017
7018        let mut fix = FixRecord {
7019            agent: agent_id,
7020            addressed: Vec::new(),
7021            rejected: Vec::new(),
7022            notes: String::new(),
7023            committed: false,
7024            failed: None,
7025            duration_ms: 0,
7026            continuation: None,
7027        };
7028        let mut final_seat = seat.clone();
7029        match out {
7030            AgentOutcome::Ok(o) => {
7031                fix.duration_ms = o.duration_ms;
7032                let parsed = verdict::extract_json::<FixReport>(&o.text);
7033                let incomplete_reason = match &parsed {
7034                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7035                        "the reply parsed, but it reported a command whose own CLI \
7036                         never confirmed an exit status"
7037                            .to_owned(),
7038                    ),
7039                    Ok(_) => None,
7040                    Err(e) => Some(e.to_string()),
7041                };
7042                match incomplete_reason {
7043                    None => {
7044                        let report = parsed.expect("checked Ok above");
7045                        fix.addressed = report.addressed;
7046                        fix.rejected = report.rejected;
7047                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7048                    }
7049                    Some(reason) => {
7050                        let (resumed_seat, resolved, failure, cont) = self
7051                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7052                            .await;
7053                        fix.duration_ms += cont.cumulative_wait_ms;
7054                        fix.continuation = Some(cont);
7055                        final_seat = resumed_seat;
7056                        match resolved {
7057                            Some(report) => {
7058                                fix.addressed = report.addressed;
7059                                fix.rejected = report.rejected;
7060                                fix.notes =
7061                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7062                            }
7063                            None => fix.failed = failure,
7064                        }
7065                    }
7066                }
7067            }
7068            AgentOutcome::Dropped(o) => {
7069                fix.duration_ms = o.duration_ms;
7070                let why = o
7071                    .dropped
7072                    .as_ref()
7073                    .map(|d| d.why.as_str())
7074                    .unwrap_or("the CLI ended the stream without delivering its answer");
7075                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7076            }
7077            AgentOutcome::Quota(o) => {
7078                self.state.quota.push(QuotaLoss::from_report(
7079                    final_seat.key.clone(),
7080                    "fix",
7081                    o.quota.as_ref(),
7082                ));
7083                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7084            }
7085            AgentOutcome::Failed(e) => fix.failed = Some(e),
7086            AgentOutcome::ResourceBlocked(e) => {
7087                fix.failed = Some(format!("the fixer was not started: {e}"));
7088            }
7089        }
7090        // Even a deferred call must rescue edits, release the worktree and
7091        // finalize its record below so an explicit `magi fix` can retry.
7092        if fix.continuation.is_none() {
7093            fix.continuation = Some(ContinuationRecord::not_needed());
7094        }
7095        self.state.seats.insert(final_seat.key.clone(), final_seat);
7096
7097        let rescue_message = format!(
7098            "magi: operator-selected fix ({}) (uncommitted work)",
7099            self.state.operator_fixes[request_index]
7100                .findings
7101                .iter()
7102                .map(|f| f.id.as_str())
7103                .collect::<Vec<_>>()
7104                .join(", ")
7105        );
7106        let repo = self.state.repo.clone();
7107        let coordination = self.coordinate(&repo).await?;
7108        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7109            self.state.note_withheld("fix", &r.withheld);
7110        }
7111        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7112        fix.committed = after != head_at_request;
7113        git::worktree_remove(&self.state.repo, &fix_worktree)
7114            .await
7115            .ok();
7116        drop(coordination);
7117
7118        self.state.event(
7119            "fix",
7120            match &fix.failed {
7121                Some(reason) => format!(
7122                    "operator fix: adoption report was lost ({reason}); {}",
7123                    if fix.committed {
7124                        "committed"
7125                    } else {
7126                        "NO new commit"
7127                    }
7128                ),
7129                None => format!(
7130                    "operator fix: {} addressed, {} rejected, {}",
7131                    fix.addressed.len(),
7132                    fix.rejected.len(),
7133                    if fix.committed {
7134                        "committed"
7135                    } else {
7136                        "NO new commit"
7137                    }
7138                ),
7139            },
7140        );
7141
7142        // Every selected finding gets an outcome — never left `Pending` once
7143        // the fixer's own turn is over. A report that never came back at all
7144        // marks every one of them `Unreported`, not silently "not addressed":
7145        // quota, a dropped stream, or an exhausted continuation are gaps in
7146        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7147        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7148        for f in &mut self.state.operator_fixes[request_index].findings {
7149            f.outcome = if fix.failed.is_some() {
7150                OperatorFixOutcome::Unreported
7151            } else if fix.addressed.contains(&f.id) {
7152                OperatorFixOutcome::Addressed
7153            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7154                OperatorFixOutcome::Rejected { why: r.why.clone() }
7155            } else {
7156                OperatorFixOutcome::Unreported
7157            };
7158        }
7159
7160        let committed = fix.committed;
7161        if committed {
7162            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7163        }
7164        self.state.operator_fixes[request_index].fix = Some(fix);
7165        // Saved again now that the fixer's own outcome is final, on top of
7166        // the save right after the request was first pushed above.
7167        self.state.save()?;
7168        if self.state.resource_block.is_some() {
7169            return self.stop_for_resource();
7170        }
7171
7172        if committed {
7173            self.state.event(
7174                "fix",
7175                format!(
7176                    "operator fix committed {}; opening a follow-up review-only run",
7177                    short(&after)
7178                ),
7179            );
7180            self.state.save()?;
7181            drop(execution);
7182            // The new review owns its own execution. Update only its audit link
7183            // afterwards, since publication may have changed the old record.
7184            let event_count = self.state.events.len();
7185            let save_follow_up = |state: &mut RunState| -> Result<()> {
7186                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7187                let _execution = crate::driver::maintenance(&home, &state.id)?;
7188                let mut disk = RunState::load(&state.id)?;
7189                disk.events.extend(state.events.drain(event_count..));
7190                let follow_up = state.operator_fixes[request_index]
7191                    .follow_up_review_run
7192                    .clone();
7193                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7194                disk.save()?;
7195                *state = disk;
7196                Ok(())
7197            };
7198            // The operator asked for the fix, and the follow-up serves whatever
7199            // task the run it follows served.
7200            let origin =
7201                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7202            match Self::review(
7203                &self.state.repo,
7204                &winner.branch,
7205                self.state.config.clone(),
7206                origin,
7207            )
7208            .await
7209            {
7210                Ok(mut follow_up) => {
7211                    follow_up.state.event(
7212                        "start",
7213                        format!(
7214                            "requested by an operator fix on run {} for finding(s) {}",
7215                            self.state.id,
7216                            self.state.operator_fixes[request_index]
7217                                .findings
7218                                .iter()
7219                                .map(|f| f.id.as_str())
7220                                .collect::<Vec<_>>()
7221                                .join(", "),
7222                        ),
7223                    );
7224                    follow_up.state.save()?;
7225                    let follow_up_id = follow_up.state.id.clone();
7226                    // The follow-up is a run like any other: it belongs to the
7227                    // task of the run it follows, or to one filed for it.
7228                    let adopted = match crate::direct::adopt(
7229                        &follow_up.state,
7230                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7231                    ) {
7232                        Ok(a) => a,
7233                        Err(e) => {
7234                            // An ownerless run must not spend agent calls; it
7235                            // stays saved, and `magi run --resume` adopts it.
7236                            self.state.event(
7237                                "fix",
7238                                format!(
7239                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7240                                ),
7241                            );
7242                            save_follow_up(&mut self.state)?;
7243                            return Ok(());
7244                        }
7245                    };
7246                    let executed = follow_up.execute().await;
7247                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7248                    if let Some(a) = adopted {
7249                        a.finish(&follow_up.state, executed);
7250                    }
7251                    if let Some(e) = failure {
7252                        self.state.event(
7253                            "fix",
7254                            format!(
7255                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7256                            ),
7257                        );
7258                    }
7259                    self.state.operator_fixes[request_index].follow_up_review_run =
7260                        Some(follow_up_id);
7261                }
7262                Err(e) => {
7263                    self.state.event(
7264                        "fix",
7265                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7266                    );
7267                }
7268            }
7269            save_follow_up(&mut self.state)?;
7270        }
7271
7272        Ok(())
7273    }
7274
7275    // --------------------------------------------------------------- review
7276
7277    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7278    /// names, in order, each at most once, moving on only when the call
7279    /// advances (an error, a quota hit or nothing usable - the same decision
7280    /// point `agent::chain_advances` is for the other chained roles).
7281    ///
7282    /// Each agent gets its own seat from `Runner::seat`: the same agent
7283    /// continues its conversation (the winner's own implementer seat when it
7284    /// is the winner's author, now that the competition is over), another
7285    /// takes a fresh one so the full prompt is sent again. A handover is
7286    /// recorded under `node`, which is what makes the fallback stick for the
7287    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7288    /// is returned, so an exhausted chain reads exactly like a single failed
7289    /// fixer: one quota loss, the same wording, the same refund. An earlier
7290    /// attempt's edits are left in the tree and judged, with the final
7291    /// attempt's, by what git says afterwards.
7292    ///
7293    /// Returns the job that produced the outcome, for `continue_fix_report`.
7294    async fn ask_fixer(
7295        &mut self,
7296        winner: &Candidate,
7297        node: &'static str,
7298        round: Option<usize>,
7299        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7300    ) -> (SeatJob, SeatState, AgentOutcome) {
7301        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7302        self.ask_fixer_among(attempts, node, round, None, build)
7303            .await
7304    }
7305
7306    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7307    /// worktree and a commit: before the next agent is asked after one that
7308    /// did not satisfy the call, the worktree is put back on that commit, so
7309    /// a failed agent's partial edits are not carried into the next one.
7310    async fn ask_fixer_among(
7311        &mut self,
7312        attempts: Vec<(AgentSpec, String)>,
7313        node: &'static str,
7314        round: Option<usize>,
7315        restore: Option<(&Path, &str)>,
7316        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7317    ) -> (SeatJob, SeatState, AgentOutcome) {
7318        let run_id = self.state.id.clone();
7319        let prompts = self.state.config.prompts.clone();
7320        let cache = self.state.config.cache_dir();
7321        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7322        let mut last = None;
7323        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7324            let seat = self.seat(&key, &spec.id);
7325            let mut job = build(spec.clone(), seat);
7326            if i > 0 {
7327                job.stem = format!("{}-{}", job.stem, spec.id);
7328            }
7329            let ctx = WaveCtx {
7330                carry_seats: false,
7331                pauses: Some((&self.pause, &self.interrupt)),
7332                run: &run_id,
7333                node,
7334                prompts: &prompts,
7335                cache: cache.as_deref(),
7336                round,
7337            };
7338            let (seat, out) =
7339                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7340            // A resource block never advances the chain: the chosen agent
7341            // was not asked, so it must be the one asked again on resume.
7342            let advances = match &out {
7343                AgentOutcome::Ok(o) => agent::output_advances(o),
7344                AgentOutcome::ResourceBlocked(_) => false,
7345                _ => true,
7346            };
7347            if let Some(next) = ids.get(i + 1)
7348                && advances
7349            {
7350                self.state.seats.insert(seat.key.clone(), seat.clone());
7351                let class =
7352                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7353                let reason = match &out {
7354                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7355                    other => fail_reason(other),
7356                };
7357                // A failed agent's edits must not reach the next one, and a
7358                // restore that did not work ends the chain: the call fails
7359                // and the caller's own (confirmed) restore decides.
7360                if let Some((wt, rev)) = restore
7361                    && let Err(e) = self.graft_restore(wt, rev).await
7362                {
7363                    let why =
7364                        format!("could not restore the worktree before the next fixer: {e:#}");
7365                    tracing::warn!("{why}");
7366                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7367                        AgentOutcome::ResourceBlocked(why)
7368                    } else {
7369                        AgentOutcome::Failed(why)
7370                    };
7371                    last = Some((job, seat, out));
7372                    break;
7373                }
7374                record_handover(
7375                    &mut self.state,
7376                    node,
7377                    &seat.key,
7378                    &spec.id,
7379                    next,
7380                    &class,
7381                    &reason,
7382                );
7383                continue;
7384            }
7385            last = Some((job, seat, out));
7386            break;
7387        }
7388        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7389        if let AgentOutcome::Quota(output) = &out
7390            && node != "graft"
7391        {
7392            // Graft is best effort: its caller records the loss and restores
7393            // the pre-graft tree, then proceeds to review and gate.
7394            // Every fallback was tried. Machine outages cannot be repaired by
7395            // spending a fix round; use each caller's resumable resource path.
7396            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7397            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7398            self.state.quota.push(loss);
7399            self.state.seats.insert(seat.key.clone(), seat.clone());
7400            self.state.status = RunStatus::Blocked;
7401            return (
7402                job,
7403                seat,
7404                AgentOutcome::ResourceBlocked(
7405                    "fixer unavailable; restore agent availability and resume".into(),
7406                ),
7407            );
7408        }
7409        (job, seat, out)
7410    }
7411
7412    /// The one repair a verification-only failure earns (see
7413    /// [`crate::recovery`]), before the first review round of a run that took
7414    /// a branch over.
7415    ///
7416    /// Saved as started *before* the fixer is called, so a resume never
7417    /// repairs twice; a start found on re-entry is rolled back to the commit
7418    /// it began from. A failed or unusable fixer leaves the tree as it was and
7419    /// the review goes on over it, so the first round's own verification
7420    /// reports the failure again. The failure is never carried into a round as
7421    /// a result: verification is re-run on whatever commit this leaves.
7422    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7423        use crate::recovery::{Mode, Repair};
7424        if !self.state.reviews.is_empty() {
7425            return Ok(());
7426        }
7427        let Some(mut rec) = self.state.recovery.clone() else {
7428            return Ok(());
7429        };
7430        if rec.mode != Mode::VerifyRepair {
7431            return Ok(());
7432        }
7433        let wt = winner.worktree.clone();
7434        let mut head = git::rev_parse(&wt, "HEAD").await?;
7435        match rec.repair.clone() {
7436            Repair::Done { .. } => return Ok(()),
7437            Repair::WaitingForRestore { before } => {
7438                self.graft_restore(&wt, &before).await?;
7439                head = before;
7440                rec.repair = Repair::NotStarted;
7441                self.state.recovery = Some(rec.clone());
7442                self.state.save()?;
7443            }
7444            Repair::Started { before } => {
7445                // Interrupted: the unfinished edits are not trusted.
7446                // An unconfirmed rollback blocks the run with `Started` kept,
7447                // so a resume retries it; the tree is never reviewed as is.
7448                if let Err(e) = self.graft_restore(&wt, &before).await {
7449                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7450                        return Err(e);
7451                    }
7452                    return self
7453                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7454                        .await;
7455                }
7456                rec.repair = Repair::Done {
7457                    before: before.clone(),
7458                    after: before,
7459                    committed: false,
7460                    failed: Some("interrupted; rolled back".to_owned()),
7461                };
7462                self.state
7463                    .event("recovery", "the repair was interrupted and rolled back");
7464                self.state.recovery = Some(rec);
7465                self.state.save()?;
7466                return Ok(());
7467            }
7468            Repair::NotStarted => {}
7469        }
7470        if crate::recovery::recheck(&mut rec, &head) {
7471            self.state.event("recovery", rec.summary());
7472            self.state.recovery = Some(rec);
7473            self.state.save()?;
7474            return Ok(());
7475        }
7476        rec.repair = Repair::Started {
7477            before: head.clone(),
7478        };
7479        self.state.recovery = Some(rec.clone());
7480        self.state.save()?;
7481
7482        let language = self.state.config.graph.language.clone();
7483        let sessions = self.state.config.graph.sessions;
7484        let artifacts = agent::artifacts_dir(&self.state.dir());
7485        let fix_prompt = prompt::recovery_fix(
7486            &self.state.instruction,
7487            &rec,
7488            self.state.config.graph.review_rounds,
7489            &language,
7490        );
7491        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7492        self.state.event(
7493            "recovery",
7494            format!(
7495                "repair: the fixer starts from the failed verification on {}",
7496                short(&head)
7497            ),
7498        );
7499        let (_job, seat, out) = self
7500            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7501                prompt: fix_prompt.clone(),
7502                spec,
7503                seat,
7504                cwd: wt.clone(),
7505                timeout,
7506                allow_write: true,
7507                sessions,
7508                artifacts: artifacts.clone(),
7509                stem: "fix-recovery".to_owned(),
7510                handover: None,
7511            })
7512            .await;
7513        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7514            rec.repair = Repair::WaitingForRestore { before: head };
7515            self.state.recovery = Some(rec);
7516            return self.stop_for_resource();
7517        }
7518        let failed = match &out {
7519            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7520            AgentOutcome::Quota(o) => {
7521                self.state.quota.push(QuotaLoss::from_report(
7522                    seat.key.clone(),
7523                    "fix",
7524                    o.quota.as_ref(),
7525                ));
7526                Some("rate limited (quota); the fixer could not run".to_owned())
7527            }
7528            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7529            AgentOutcome::Failed(e) => Some(e.clone()),
7530        };
7531        self.state.seats.insert(seat.key.clone(), seat);
7532        let coordination = self.coordinate(&wt).await?;
7533        let failed = match failed {
7534            // The agent's partial edits are not kept.
7535            Some(why) => {
7536                if let Err(e) = git::restore_to(&wt, &head).await {
7537                    return self
7538                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7539                        .await;
7540                }
7541                Some(why)
7542            }
7543            None => {
7544                if let Ok(r) = git::rescue_commit(
7545                    &wt,
7546                    "magi: recovery repair of the failed verification (uncommitted work)",
7547                )
7548                .await
7549                {
7550                    self.state.note_withheld("fix", &r.withheld);
7551                }
7552                None
7553            }
7554        };
7555        let after = git::rev_parse(&wt, "HEAD").await?;
7556        drop(coordination);
7557        self.state.event(
7558            "recovery",
7559            match &failed {
7560                Some(why) => format!("repair: nothing kept ({why})"),
7561                None if after != head => {
7562                    format!("repair: committed {}", short(&after))
7563                }
7564                None => "repair: the fixer made no commit".to_owned(),
7565            },
7566        );
7567        rec.repair = Repair::Done {
7568            before: head.clone(),
7569            committed: after != head,
7570            after,
7571            failed,
7572        };
7573        self.state.recovery = Some(rec);
7574        self.state.save()?;
7575        Ok(())
7576    }
7577
7578    /// A repair whose rollback could not be confirmed: the run is blocked and
7579    /// resumable, and the unconfirmed state is never reviewed.
7580    async fn stop_recovery(
7581        &mut self,
7582        mut rec: crate::recovery::RecoveryRecord,
7583        head: &str,
7584        why: String,
7585    ) -> Result<()> {
7586        // `Started` stays recorded: a resume retries the restore.
7587        rec.repair = crate::recovery::Repair::Started {
7588            before: head.to_owned(),
7589        };
7590        self.state.recovery = Some(rec);
7591        self.state
7592            .event("recovery", format!("repair could not be undone: {why}"));
7593        self.state.status = RunStatus::Blocked;
7594        self.state.save()?;
7595        bail!("recovery repair could not be rolled back: {why}")
7596    }
7597
7598    async fn review_loop(&mut self) -> Result<()> {
7599        if self.hold_base_sync().await? {
7600            return Ok(());
7601        }
7602        loop {
7603            if self
7604                .state
7605                .base_sync
7606                .as_ref()
7607                .is_some_and(|s| s.conflict.is_some())
7608            {
7609                return Ok(());
7610            }
7611            if self.catchup_repairable() {
7612                let record = self.state.reviews.last().expect("repairable round").clone();
7613                let winner = self
7614                    .state
7615                    .winner()
7616                    .cloned()
7617                    .context("catch-up repair has no winner")?;
7618                if !self.fix_review_round(&winner, record).await? {
7619                    return Ok(());
7620                }
7621            }
7622            self.review_loop_pass().await?;
7623            if !self.catchup_repairable() {
7624                return Ok(());
7625            }
7626        }
7627    }
7628
7629    /// Derive an owed catch-up repair from durable round evidence, including
7630    /// reentry after a crash before the fixer was dispatched.
7631    fn catchup_repairable(&self) -> bool {
7632        self.state.reviews.len() < self.state.config.graph.review_rounds
7633            && self.state.reviews.last().is_some_and(|r| {
7634                !r.clean
7635                    && r.blocking == 0
7636                    && r.fix.is_none()
7637                    && r.e2e_status() == E2eStatus::Failed
7638            })
7639    }
7640
7641    async fn review_loop_pass(&mut self) -> Result<()> {
7642        // A base that would not rebase is a person's decision, not a review
7643        // round: nothing here would change the answer, and reviewers and a
7644        // fixer would be spending real budget on a tree that cannot land
7645        // regardless of what they find.
7646        if self
7647            .state
7648            .base_sync
7649            .as_ref()
7650            .is_some_and(|s| s.conflict.is_some())
7651        {
7652            return Ok(());
7653        }
7654        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7655        // agent files with `magi task add` name the run that paid for it. The
7656        // prompt overlay is cloned alongside it because the waves borrow it
7657        // while `self` is mutably borrowed by the node's own bookkeeping.
7658        let run_id = self.state.id.clone();
7659        let prompts = self.state.config.prompts.clone();
7660        let Some(winner) = self.state.winner().cloned() else {
7661            return Ok(());
7662        };
7663        let granted_review = self
7664            .state
7665            .repair_grants
7666            .last()
7667            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7668            .cloned();
7669        let fresh_review = granted_review
7670            .as_ref()
7671            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7672        let max_rounds = granted_review
7673            .as_ref()
7674            .map_or(self.state.config.graph.review_rounds, |g| {
7675                g.review_start.saturating_add(1)
7676            });
7677        // A clean round, an exhausted round budget, or a stalled tree (see
7678        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7679        // they are recorded — recomputed here, not read off `status`, so a
7680        // reentry into a run that already stopped restates the identical
7681        // verdict instead of silently handing back whatever an earlier node
7682        // in this same walk clobbered `status` to (a solo-candidate
7683        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7684        // below runs an empty range once the budget is spent, and would
7685        // otherwise fall through without touching `status` at all.
7686        if let Some(status) =
7687            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7688        {
7689            // A reentry after a crash between the last round's save and
7690            // `stop_reviewing` reaches the hand-off here, not there.
7691            if status == RunStatus::Gating {
7692                self.record_contested_handoff();
7693            }
7694            self.state.status = status;
7695            self.state.save()?;
7696            return Ok(());
7697        }
7698        self.state.status = RunStatus::Reviewing;
7699        // A last recorded round whose own verification never resolved
7700        // (`ResourceBlocked` — the shared build cache, not the patch) is
7701        // never a concluded round, whatever the round budget says: starting
7702        // a fresh round on top of it would spend a whole new reviewer wave
7703        // re-reading an unchanged patch instead of just retrying the one
7704        // check that actually needs it, and once the budget is spent the
7705        // loop below has nothing left to do at all (its range is empty).
7706        // Retry that check directly instead, exactly the same retry
7707        // `stop_reviewing` already does for its own catch-up case.
7708        if !fresh_review
7709            && self.state.reviews.last().is_some_and(|r| {
7710                r.e2e_status() == E2eStatus::ResourceBlocked
7711                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7712            })
7713        {
7714            let shell = self.state.config.shell();
7715            return self
7716                .stop_unresolved_review(
7717                    "the last round's own verification never resolved",
7718                    &shell,
7719                    &winner.worktree,
7720                )
7721                .await;
7722        }
7723
7724        if granted_review.is_none() {
7725            self.recovery_repair(&winner).await?;
7726        }
7727        if self.resource_halt()? {
7728            return Ok(());
7729        }
7730
7731        let repo = self.state.repo.clone();
7732        let root = self.state.worktree_root();
7733        let language = self.state.config.graph.language.clone();
7734        let sessions = self.state.config.graph.sessions;
7735        let artifacts = self.merge_repair_artifacts();
7736        let base = self.landing_base();
7737        let base_short = short(&base);
7738        let reviewers = self.roles.reviewers.clone();
7739        let shell = self.state.config.shell();
7740
7741        for round in (self.state.reviews.len() + 1)..=max_rounds {
7742            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7743            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7744            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7745            // The prior round's own record, already persisted — never a
7746            // hand-carried variable of just its failing output: that is
7747            // exactly what let a round's e2e result drift out of sync with
7748            // which commit it was actually about (see `SCHEMA`'s doc for
7749            // schema 8). Judged against `head`, the commit reviewers are
7750            // about to look at now, so the summary always reads as "an
7751            // earlier head" here — this round's own patch has not been
7752            // checked yet.
7753            let prev_verification = self
7754                .state
7755                .reviews
7756                .last()
7757                .and_then(|r| r.verification_summary(&head));
7758            // Only the first round of a run that took a branch over: later
7759            // rounds have this run's own history.
7760            let prior_section = match (&self.state.recovery, round) {
7761                (Some(rec), 1) if self.state.reviews.is_empty() => {
7762                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7763                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7764                            Some(crate::recovery::head_of(
7765                                &git::diff(&winner.worktree, reviewed, "HEAD")
7766                                    .await
7767                                    .unwrap_or_default(),
7768                                crate::recovery::SINCE_DIFF_MAX,
7769                            ))
7770                        }
7771                        _ => None,
7772                    };
7773                    Some(prompt::recovery_review(rec, since.as_deref()))
7774                }
7775                _ => None,
7776            };
7777
7778            // Each reviewer gets its own detached checkout of exactly this
7779            // commit: nobody can perturb the winner's tree, and the fixer can
7780            // keep working without racing a reviewer.
7781            let mut jobs = Vec::new();
7782            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7783                self.coordinate(&repo).await?
7784            } else {
7785                None
7786            };
7787            for (r, spec) in reviewers.iter().cloned().enumerate() {
7788                let wt = root.join(format!("review-{}", r + 1));
7789                // `clean -fdx` in a reset wipes setup's products, so every
7790                // round sets the seat up again.
7791                if wt.exists() {
7792                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7793                } else {
7794                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7795                        None
7796                    } else {
7797                        self.coordinate(&repo).await?
7798                    };
7799                    git::worktree_add_detached(&repo, &wt, &head).await?;
7800                }
7801                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7802                    None
7803                } else {
7804                    self.coordinate(&repo).await?
7805                };
7806                self.setup_seat_worktree(
7807                    &repo,
7808                    &wt,
7809                    false,
7810                    coordination.as_ref().or(_setup_lease.as_ref()),
7811                )
7812                .await?;
7813                let seat_key = format!("review-{}", r + 1);
7814                // The seat starts the round on whoever answered it last, not
7815                // on the agent the spec names, so a failure is not re-paid.
7816                let spec = pick_start_spec(
7817                    &self.roles.reviewer_roster,
7818                    spec,
7819                    self.state.seat_history.get(&seat_key),
7820                );
7821                let seat = self.seat(&seat_key, &spec.id);
7822                jobs.push(SeatJob {
7823                    prompt: prompt::review(&prompt::ReviewCtx {
7824                        instruction: &self.state.instruction,
7825                        branch: &winner.branch,
7826                        base_short: &base_short,
7827                        stat: &stat,
7828                        patch: &patch,
7829                        verification: prev_verification.as_ref(),
7830                        prior: prior_section.as_deref(),
7831                        reviewers: reviewers.len(),
7832                        round,
7833                        rounds: max_rounds,
7834                        // A review-only run has no rankings, so nothing
7835                        // competed for this patch and the reviewer is told so.
7836                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7837                        lens: Lens::for_seat(r),
7838                        language: &language,
7839                        github_language: &self.state.config.graph.github_language,
7840                    }),
7841                    spec,
7842                    seat,
7843                    cwd: wt,
7844                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7845                    allow_write: false,
7846                    sessions,
7847                    artifacts: artifacts.clone(),
7848                    stem: format!("review-{round}-{}", r + 1),
7849                    handover: None,
7850                });
7851            }
7852
7853            drop(coordination);
7854            self.state.event(
7855                "review",
7856                format!(
7857                    "round {round}: {} reviewers on {}",
7858                    jobs.len(),
7859                    short(&head)
7860                ),
7861            );
7862            let mut quota_losses = Vec::new();
7863            let review_retries = self.state.config.graph.retries;
7864            let review_cache = self.state.config.cache_dir();
7865            let ctx = WaveCtx {
7866                carry_seats: true,
7867                pauses: Some((&self.pause, &self.interrupt)),
7868                run: &run_id,
7869                node: "review",
7870                prompts: &prompts,
7871                cache: review_cache.as_deref(),
7872                round: Some(round),
7873            };
7874            let results = ask_json_wave::<Review>(
7875                jobs,
7876                Arc::clone(&self.sem),
7877                review_retries,
7878                &self.roles.reviewer_roster,
7879                &ctx,
7880                &mut quota_losses,
7881                &mut self.state,
7882                &|_: &Review| Ok(()),
7883            )
7884            .await;
7885            if self.state.resource_block.is_some() {
7886                return self.stop_for_resource();
7887            }
7888            // Counted before the move below: how many of *this* round's
7889            // reviewer seats were lost to their own rate limit, as opposed to
7890            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7891            let round_quota_missing = quota_losses.len();
7892            self.state.quota.extend(quota_losses);
7893
7894            let mut records = Vec::new();
7895            let mut all_findings = Vec::new();
7896            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7897                let agent_id = seat.agent.clone();
7898                self.state.seats.insert(seat.key.clone(), seat);
7899                let mut record = ReviewRecord {
7900                    reviewer: r + 1,
7901                    agent: agent_id,
7902                    summary: String::new(),
7903                    findings: Vec::new(),
7904                    vote: None,
7905                    failed: None,
7906                    duration_ms: 0,
7907                    // Set for both outcomes: `failed: Some(_)` with
7908                    // `attempts > 0` is a seat every retry still lost, not a
7909                    // recovered one — only `failed: None` with `attempts > 0`
7910                    // reads as "answered after a nudge" (see this field's own
7911                    // doc).
7912                    attempts,
7913                };
7914                match res {
7915                    Ok((review, out)) => {
7916                        // Sanitized here, at the point every other piece of
7917                        // agent prose in this file is (candidate summaries,
7918                        // deliberation turns, vote reasons): a reviewer's own
7919                        // words are the one thing about it that could name
7920                        // it, and reconsideration below broadcasts this same
7921                        // summary and these same findings to every other
7922                        // seat on the panel.
7923                        record.summary =
7924                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7925                        record.vote = Some(review.vote);
7926                        record.duration_ms = out.duration_ms;
7927                        for (n, mut f) in review.findings.into_iter().enumerate() {
7928                            // ids are magi's, never the agent's: the fixer's
7929                            // adoption report is keyed by them.
7930                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7931                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7932                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7933                            // `file` is agent-supplied prose too, never
7934                            // checked against the real tree — the same
7935                            // exposure `title`/`detail` above have, just in
7936                            // a field easy to forget because it looks like a
7937                            // path rather than free text.
7938                            f.file = f
7939                                .file
7940                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7941                            all_findings.push(f.clone());
7942                            record.findings.push(f);
7943                        }
7944                        self.state.event(
7945                            "review",
7946                            format!(
7947                                "round {round}: reviewer {} voted {} with {} finding(s)",
7948                                r + 1,
7949                                review.vote.label(),
7950                                record.findings.len()
7951                            ),
7952                        );
7953                    }
7954                    Err(e) => {
7955                        record.failed = Some(e.to_string());
7956                        self.state.event(
7957                            "review",
7958                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7959                        );
7960                    }
7961                }
7962                records.push(record);
7963            }
7964
7965            // Tally the round's votes and, if they split, spend the one
7966            // round of reconsideration the split -> deliberate -> revote
7967            // shape `judge`/`vote` use for the panel, sized down to what a
7968            // read-only review round can afford: one round, and a revote
7969            // rather than an argument, because the panel already wrote its
7970            // reasoning down as findings the first time around.
7971            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7972            let vote_split =
7973                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7974            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7975            if vote_split {
7976                self.state.event(
7977                    "review",
7978                    format!(
7979                        "round {round}: votes split ({}) — one round of reconsideration",
7980                        initial_votes
7981                            .iter()
7982                            .map(|v| v.label())
7983                            .collect::<Vec<_>>()
7984                            .join(", ")
7985                    ),
7986                );
7987                // Seats read every seat's findings and votes, still numbered
7988                // and never named — the same anonymity `review` itself keeps.
7989                let panel: Vec<ReviewSeatReport<'_>> = records
7990                    .iter()
7991                    .filter_map(|r| {
7992                        r.vote.map(|vote| ReviewSeatReport {
7993                            reviewer: r.reviewer,
7994                            vote,
7995                            summary: &r.summary,
7996                            findings: &r.findings,
7997                        })
7998                    })
7999                    .collect();
8000
8001                let mut jobs = Vec::new();
8002                let mut seats_at = Vec::new();
8003                for (r, spec) in reviewers.iter().cloned().enumerate() {
8004                    // A seat with no initial vote has nothing to reconsider
8005                    // from and stays absent, the same as it stayed absent
8006                    // from `panel` above.
8007                    if records[r].vote.is_none() {
8008                        continue;
8009                    }
8010                    let wt = root.join(format!("review-{}", r + 1));
8011                    let seat_key = format!("review-{}", r + 1);
8012                    let spec = self.occupant(&seat_key, spec);
8013                    let seat = self.seat(&seat_key, &spec.id);
8014                    // A seat with no live session has already forgotten the
8015                    // initial review's prompt — restate the patch it is
8016                    // voting on, the same as `deliberate`/`vote` do for a
8017                    // judge in the same position.
8018                    // The panel already carries this seat's own review and
8019                    // vote, so restating the patch makes the prompt whole for
8020                    // a seat handed to another agent.
8021                    let build = |with_patch: bool| {
8022                        prompt::review_reconsider(&ReviewReconsiderCtx {
8023                            instruction: &self.state.instruction,
8024                            reviewer: r + 1,
8025                            lens: Lens::for_seat(r),
8026                            panel: &panel,
8027                            patch: with_patch.then_some(ReviewPatch {
8028                                branch: &winner.branch,
8029                                base_short: &base_short,
8030                                stat: &stat,
8031                                patch: &patch,
8032                            }),
8033                            round,
8034                            rounds: max_rounds,
8035                            language: &language,
8036                        })
8037                    };
8038                    let full = build(true);
8039                    let prompt = if has_context(&spec, &seat, sessions) {
8040                        build(false)
8041                    } else {
8042                        full.clone()
8043                    };
8044                    jobs.push(SeatJob {
8045                        prompt,
8046                        spec,
8047                        seat,
8048                        cwd: wt,
8049                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8050                        allow_write: false,
8051                        sessions,
8052                        artifacts: artifacts.clone(),
8053                        stem: format!("review-{round}-reconsider-{}", r + 1),
8054                        handover: Some(full),
8055                    });
8056                    seats_at.push(r);
8057                }
8058
8059                let mut recon_quota_losses = Vec::new();
8060                let recon_cache = self.state.config.cache_dir();
8061                let recon_ctx = WaveCtx {
8062                    carry_seats: true,
8063                    pauses: Some((&self.pause, &self.interrupt)),
8064                    run: &run_id,
8065                    node: "review",
8066                    prompts: &prompts,
8067                    cache: recon_cache.as_deref(),
8068                    round: Some(round),
8069                };
8070                let recon_results = ask_json_wave::<ReviewRevote>(
8071                    jobs,
8072                    Arc::clone(&self.sem),
8073                    review_retries,
8074                    &self.roles.reviewer_roster,
8075                    &recon_ctx,
8076                    &mut recon_quota_losses,
8077                    &mut self.state,
8078                    &|_: &ReviewRevote| Ok(()),
8079                )
8080                .await;
8081                if self.state.resource_block.is_some() {
8082                    return self.stop_for_resource();
8083                }
8084                self.state.quota.extend(recon_quota_losses);
8085
8086                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8087                    let agent_id = seat.agent.clone();
8088                    self.state.seats.insert(seat.key.clone(), seat);
8089                    let mut rec = ReviewRevoteRecord {
8090                        reviewer: r + 1,
8091                        agent: agent_id,
8092                        vote: None,
8093                        reason: String::new(),
8094                        failed: None,
8095                    };
8096                    match res {
8097                        Ok((rv, _)) => {
8098                            rec.vote = Some(rv.vote);
8099                            rec.reason =
8100                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8101                            self.state.event(
8102                                "review",
8103                                format!(
8104                                    "round {round}: reviewer {} revoted {}",
8105                                    r + 1,
8106                                    rv.vote.label()
8107                                ),
8108                            );
8109                        }
8110                        Err(e) => {
8111                            rec.failed = Some(e.to_string());
8112                            self.state.event(
8113                                "review",
8114                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8115                            );
8116                        }
8117                    }
8118                    reconsideration.push(rec);
8119                }
8120            } else if initial_votes.len() > 1 {
8121                self.state.event(
8122                    "review",
8123                    format!(
8124                        "round {round}: votes agreed ({}) — no reconsideration",
8125                        initial_votes[0].label()
8126                    ),
8127                );
8128            }
8129
8130            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8131            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8132            // A round that already has a blocking finding and a round left to
8133            // try is going back to the fixer no matter what `verify.e2e`
8134            // says, so running it first only spends the loop's slowest step
8135            // (minutes, for a Rust repo's full test suite) on a head about
8136            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8137            // runs once a round has no blocking findings left (see
8138            // `round_is_clean`, which a deferred — empty — `e2e` can never
8139            // satisfy since `blocking` is nonzero whenever this branch is
8140            // taken), and `stop_reviewing` forces a real run before it will
8141            // ever read a deferred round as green.
8142            let defer_e2e =
8143                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8144            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8145                let reason =
8146                    format!("{blocking} blocking finding(s) already required a fix this round");
8147                self.state.event(
8148                    "verify",
8149                    format!(
8150                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8151                         {}); it will run once a round has none left",
8152                        short(&head)
8153                    ),
8154                );
8155                (Vec::new(), false, true, Some(reason))
8156            } else {
8157                let e2e_commands = self.state.config.verify.e2e.clone();
8158                let cache_dir = self.state.config.cache_dir();
8159                let context = format!("round {round}");
8160                let wait = self.repository_wait();
8161                let (e2e, verify_retried) = with_cache_lease(
8162                    &mut self.state,
8163                    cache_dir.as_deref(),
8164                    "e2e",
8165                    "e2e",
8166                    &winner.worktree,
8167                    &head,
8168                    verify_timeout,
8169                    &context,
8170                    &wait,
8171                    |state, budget| {
8172                        let shell = shell.clone();
8173                        let e2e_commands = e2e_commands.clone();
8174                        let worktree = winner.worktree.clone();
8175                        let context = context.clone();
8176                        let winner = winner.clone();
8177                        async move {
8178                            if !e2e_commands.is_empty() {
8179                                // The suite certifies one SHA. Format before it
8180                                // runs, or the commit `pre_gate` makes at the
8181                                // gate owes the whole suite again.
8182                                Self::run_pre_gate(state, &winner).await;
8183                            }
8184                            run_e2e_with_retry(
8185                                state,
8186                                &shell,
8187                                &e2e_commands,
8188                                &worktree,
8189                                budget,
8190                                &context,
8191                                Some(round),
8192                            )
8193                            .await
8194                        }
8195                    },
8196                )
8197                .await?;
8198                (e2e, verify_retried, false, None)
8199            };
8200
8201            let expected = records.len();
8202            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8203            let incomplete = answered < expected;
8204            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8205            let policy = self.state.config.graph.incomplete_review;
8206            let clean = round_is_clean(
8207                blocking,
8208                e2e_ok,
8209                answered,
8210                expected,
8211                round_quota_missing,
8212                policy,
8213            );
8214
8215            let mut round_record = ReviewRound {
8216                round,
8217                head: head.clone(),
8218                verified_head: None,
8219                verified_at: None,
8220                reviews: records,
8221                e2e,
8222                verify_retried,
8223                e2e_deferred,
8224                e2e_defer_reason,
8225                fix: None,
8226                blocking,
8227                answered,
8228                expected,
8229                clean,
8230                progressed: false,
8231                vote_split,
8232                reconsideration,
8233                verdict: None,
8234            };
8235            // The final vote per seat is its revote where reconsideration
8236            // ran and answered, its initial vote otherwise — the same
8237            // fallback `tally` uses for a judge whose private vote failed.
8238            round_record.verdict = ReviewVote::worst(
8239                round_record
8240                    .final_votes()
8241                    .into_iter()
8242                    .map(|(_, _, vote)| vote),
8243            );
8244            // Which commit and when magi actually attempted to check —
8245            // known the moment a command was dispatched against `head`,
8246            // whether or not it finished: a resource-blocked attempt still
8247            // targeted a specific commit at a specific time, and leaving
8248            // that unrecorded is exactly what made `verification_summary`
8249            // report a fresh attempt as "commit unknown ... recorded before
8250            // this was tracked", indistinguishable from a genuinely old,
8251            // untracked record. Only a deferred or unconfigured round never
8252            // ran at all and has nothing to record — see
8253            // `ReviewRound::verified_head`'s own doc.
8254            if !matches!(
8255                round_record.e2e_status(),
8256                E2eStatus::Deferred | E2eStatus::NotConfigured
8257            ) {
8258                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8259                // mechanical fixes before the commands ran.
8260                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8261                round_record.verified_at = Some(Timestamp::now());
8262            }
8263
8264            if incomplete {
8265                let missing: Vec<String> = round_record
8266                    .reviews
8267                    .iter()
8268                    .filter(|r| r.failed.is_some())
8269                    .map(|r| format!("review-{}", r.reviewer))
8270                    .collect();
8271                self.state.event(
8272                    "review",
8273                    format!(
8274                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8275                        missing.join(", ")
8276                    ),
8277                );
8278            }
8279
8280            if clean {
8281                self.state.event(
8282                    "review",
8283                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8284                        format!(
8285                            "round {round}: clean (warn policy, incomplete panel) — no \
8286                             blocking findings from the seats that answered, verification green"
8287                        )
8288                    } else if incomplete {
8289                        format!(
8290                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8291                             quorum) — no blocking findings from the seats that answered, \
8292                             verification green",
8293                            expected - answered
8294                        )
8295                    } else {
8296                        format!("round {round}: clean — no blocking findings, verification green")
8297                    },
8298                );
8299                self.state.reviews.push(round_record);
8300                self.state.status = RunStatus::Gating;
8301                self.state.save()?;
8302                return Ok(());
8303            }
8304
8305            // Nothing was raised and verification passed, but not every seat
8306            // answered and `round_is_clean` still refused to call it clean —
8307            // either a seat is missing for a reason other than its own quota
8308            // (a crash, a timeout, unparsable output — worth another try), or
8309            // every seat that could have answered lost its quota and nobody
8310            // is left to decide on: re-review rather than send the fixer
8311            // after a round with nothing to fix.
8312            if incomplete && blocking == 0 && e2e_ok {
8313                self.state.reviews.push(round_record);
8314                self.state.save()?;
8315                if round == max_rounds {
8316                    self.state.status = RunStatus::Blocked;
8317                    self.state.event(
8318                        "review",
8319                        format!(
8320                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8321                             refusing to call it clean",
8322                            expected - answered
8323                        ),
8324                    );
8325                    return Ok(());
8326                }
8327                continue;
8328            }
8329
8330            // Nothing for the fixer to act on (`blocking == 0`) and the only
8331            // reason this round is not clean is that magi itself never got
8332            // a command to run — the shared build cache, not the patch (see
8333            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8334            // the fixer would invite a change to appease contention that has
8335            // nothing to do with the diff, and would leave this attempt
8336            // sitting in the next round's prompt as if it were about an
8337            // earlier, superseded commit rather than what it actually is:
8338            // the same head, still waiting to be checked. Wait for it the
8339            // same way the final round's own contention is already handled,
8340            // whatever round this happens to be.
8341            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8342                self.state.reviews.push(round_record);
8343                return self
8344                    .stop_unresolved_review(
8345                        "the round's own verification could not run",
8346                        &shell,
8347                        &winner.worktree,
8348                    )
8349                    .await;
8350            }
8351
8352            if round == max_rounds {
8353                self.state.reviews.push(round_record);
8354                return self
8355                    .stop_reviewing(
8356                        &format!(
8357                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8358                        ),
8359                        &shell,
8360                        &winner.worktree,
8361                    )
8362                    .await;
8363            }
8364
8365            if !self.fix_review_round(&winner, round_record).await? {
8366                return Ok(());
8367            }
8368        }
8369        Ok(())
8370    }
8371
8372    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8373    /// False means admission or continuation policy stopped the review loop.
8374    async fn fix_review_round(
8375        &mut self,
8376        winner: &Candidate,
8377        mut round_record: ReviewRound,
8378    ) -> Result<bool> {
8379        let round = round_record.round;
8380        let shell = self.state.config.shell();
8381        let step = self.run_fix_round(winner, &mut round_record).await?;
8382        if matches!(step, FixStep::Resource) {
8383            self.stop_for_resource()?;
8384            return Ok(false);
8385        }
8386        if self.state.reviews.len() < round {
8387            self.state.reviews.push(round_record);
8388        } else {
8389            self.state.reviews[round - 1] = round_record;
8390        }
8391        self.state.save()?;
8392
8393        // The fixer's own report never came back this round, even after
8394        // `continue_fix_report`'s own budget was spent on it — not an
8395        // ordinary "no report" (dropped stream, quota, plain failure),
8396        // which already reads that way and is left to the existing round
8397        // budget. Stopping here, rather than opening another round, is
8398        // what keeps a next reviewer/fixer wave from ever being
8399        // dispatched onto `winner.worktree` while whatever the seat's
8400        // last call may still have running there is unaccounted for: no
8401        // process liveness check exists (and none is being added — see
8402        // AGENTS.md/this task's own scope), so the only way to honour
8403        // "nothing starts before a valid report returns" is to not start
8404        // anything further on this worktree from this run at all.
8405        if matches!(step, FixStep::Recorded { report_lost: true }) {
8406            self.stop_reviewing(
8407                "the fixer's adoption report never came back, even after resuming its \
8408                         own seat; refusing to start another round against the same worktree \
8409                         while that is unresolved",
8410                &shell,
8411                &winner.worktree,
8412            )
8413            .await?;
8414            return Ok(false);
8415        }
8416
8417        let streak = self
8418            .state
8419            .reviews
8420            .iter()
8421            .rev()
8422            .take_while(|r| !r.progressed)
8423            .count();
8424        if streak >= STAGNANT_LIMIT {
8425            self.stop_reviewing(
8426                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8427                &shell,
8428                &winner.worktree,
8429            )
8430            .await?;
8431            return Ok(false);
8432        }
8433        Ok(true)
8434    }
8435
8436    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8437    async fn run_fix_round(
8438        &mut self,
8439        winner: &Candidate,
8440        round_record: &mut ReviewRound,
8441    ) -> Result<FixStep> {
8442        let round = round_record.round;
8443        let max_rounds = self.state.config.graph.review_rounds;
8444        let run_id = self.state.id.clone();
8445        let prompts = self.state.config.prompts.clone();
8446        let language = self.state.config.graph.language.clone();
8447        let sessions = self.state.config.graph.sessions;
8448        let artifacts = self.merge_repair_artifacts();
8449        let base = self.landing_base();
8450        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8451        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8452        let this_round_verification = round_record.verification_summary(&head);
8453        let all_findings: Vec<_> = round_record
8454            .reviews
8455            .iter()
8456            .flat_map(|r| r.findings.iter().cloned())
8457            .collect();
8458        // Fix. The winner's own implementer seat continues its conversation:
8459        // the competition is over, so context is pure benefit now.
8460        let blocking_findings: Vec<_> = all_findings
8461            .iter()
8462            .filter(|f| f.severity.blocks())
8463            .cloned()
8464            .collect();
8465        let fix_prompt = prompt::fix_in(
8466            &self.state.instruction,
8467            &blocking_findings,
8468            this_round_verification.as_ref(),
8469            round,
8470            max_rounds,
8471            &language,
8472            &self.state.config.graph.github_language,
8473        );
8474        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8475        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8476        let (job, seat, out) = self
8477            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8478                prompt: fix_prompt.clone(),
8479                spec,
8480                seat,
8481                cwd: winner.worktree.clone(),
8482                timeout,
8483                allow_write: true,
8484                sessions,
8485                artifacts: artifacts.clone(),
8486                stem: format!("fix-{round}"),
8487                handover: None,
8488            })
8489            .await;
8490        // Not asked: the round is not recorded (so a resume repeats it),
8491        // no fixer was handed over to, and the seat is left as it was.
8492        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8493            return Ok(FixStep::Resource);
8494        }
8495        let agent_id = seat.agent.clone();
8496
8497        let mut fix = FixRecord {
8498            agent: agent_id,
8499            addressed: Vec::new(),
8500            rejected: Vec::new(),
8501            notes: String::new(),
8502            committed: false,
8503            failed: None,
8504            duration_ms: 0,
8505            continuation: None,
8506        };
8507        let mut continuation = ContinuationRecord::not_needed();
8508        let mut final_seat = seat.clone();
8509        match out {
8510            AgentOutcome::Ok(o) => {
8511                fix.duration_ms = o.duration_ms;
8512                let parsed = verdict::extract_json::<FixReport>(&o.text);
8513                // A parsed report standing next to a command this same
8514                // reply's own CLI never confirmed the exit status of is
8515                // not a resolved answer — the identical `CommandEvidence`
8516                // `state.jobs` renders, read here instead of only on
8517                // display, per the completion judgment and the shown
8518                // record needing to agree.
8519                let incomplete_reason = match &parsed {
8520                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8521                        "the reply parsed, but it reported a command whose own CLI never \
8522                             confirmed an exit status"
8523                            .to_owned(),
8524                    ),
8525                    Ok(_) => None,
8526                    Err(e) => Some(e.to_string()),
8527                };
8528                match incomplete_reason {
8529                    None => {
8530                        let report = parsed.expect("checked Ok above");
8531                        fix.addressed = report.addressed;
8532                        fix.rejected = report.rejected;
8533                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8534                    }
8535                    Some(reason) => {
8536                        let (resumed_seat, resolved, failure, cont) = self
8537                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8538                            .await;
8539                        fix.duration_ms += cont.cumulative_wait_ms;
8540                        continuation = cont;
8541                        final_seat = resumed_seat;
8542                        match resolved {
8543                            Some(report) => {
8544                                fix.addressed = report.addressed;
8545                                fix.rejected = report.rejected;
8546                                fix.notes =
8547                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8548                            }
8549                            None => fix.failed = failure,
8550                        }
8551                    }
8552                }
8553            }
8554            // The CLI's raw error JSON is not a fix report to parse.
8555            AgentOutcome::Dropped(o) => {
8556                fix.duration_ms = o.duration_ms;
8557                let why = o
8558                    .dropped
8559                    .as_ref()
8560                    .map(|d| d.why.as_str())
8561                    .unwrap_or("the CLI ended the stream without delivering its answer");
8562                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8563            }
8564            AgentOutcome::Quota(o) => {
8565                self.state.quota.push(QuotaLoss::from_report(
8566                    final_seat.key.clone(),
8567                    "fix",
8568                    o.quota.as_ref(),
8569                ));
8570                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8571            }
8572            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8573        }
8574        if self.state.resource_block.is_some() {
8575            self.state.seats.insert(final_seat.key.clone(), final_seat);
8576            return Ok(FixStep::Resource);
8577        }
8578        fix.continuation = Some(continuation);
8579        self.state.seats.insert(final_seat.key.clone(), final_seat);
8580        let coordination = self.coordinate(&winner.worktree).await?;
8581        if let Ok(r) = git::rescue_commit(
8582            &winner.worktree,
8583            &format!("magi: review round {round} fixes (uncommitted work)"),
8584        )
8585        .await
8586        {
8587            self.state.note_withheld("fix", &r.withheld);
8588        }
8589        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8590        fix.committed = after != before;
8591        // Judged by what `git` says moved against base, never by the
8592        // fixer's own `addressed`/`rejected` count — see
8593        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8594        // `patch` snapshot above: swallowing this error would default
8595        // `diff_after` to empty, which almost always differs from a
8596        // non-empty `patch` and reads as "progressed" — exactly backwards
8597        // for a `git` failure the stagnation check cannot see through.
8598        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8599        drop(coordination);
8600        let progressed = diff_after != patch;
8601        let commit_note = if fix.committed {
8602            "committed"
8603        } else {
8604            "NO new commit"
8605        };
8606        let tree_note = if progressed {
8607            "changed vs base"
8608        } else {
8609            "unchanged vs base"
8610        };
8611        self.state.event(
8612            "fix",
8613            match &fix.failed {
8614                // Distinct on purpose from "0 addressed, 0 rejected": the
8615                // fixer's own diff still landed (blocking counts do keep
8616                // falling round over round), only its adoption report did
8617                // not come back, so this must never read like every
8618                // finding was reviewed and declined.
8619                Some(reason) => {
8620                    format!(
8621                        "round {round}: fixer's adoption report was lost ({reason}); \
8622                             {commit_note}, tree {tree_note}"
8623                    )
8624                }
8625                None => format!(
8626                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8627                         {tree_note}{}",
8628                    fix.addressed.len(),
8629                    fix.rejected.len(),
8630                    if continuation.outcome == ContinuationOutcome::Resumed {
8631                        format!(
8632                            " (adoption report recovered after {} continuation(s))",
8633                            continuation.attempts
8634                        )
8635                    } else {
8636                        String::new()
8637                    },
8638                ),
8639            },
8640        );
8641        round_record.fix = Some(fix);
8642        round_record.progressed = progressed;
8643        Ok(FixStep::Recorded {
8644            report_lost: matches!(
8645                continuation.outcome,
8646                ContinuationOutcome::Exhausted
8647                    | ContinuationOutcome::QuotaLost
8648                    | ContinuationOutcome::NoSession
8649            ),
8650        })
8651    }
8652
8653    /// Decide, from the last recorded round's own verification, whether
8654    /// stopping the review loop is a hand-off or a genuine block.
8655    ///
8656    /// Called once the loop has given up trying — the round budget is spent,
8657    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8658    /// findings still open, never while a round is still clean or the
8659    /// incomplete-panel case handled inline above. Gate and e2e are facts
8660    /// about the tree; a lingering review finding is an opinion, and this
8661    /// workload's own `magi stats` puts reviewer precision low enough
8662    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8663    /// must not by itself stand between a green, verified change and the
8664    /// human who decides what to do with it. A red e2e is not an opinion, so
8665    /// that case still blocks, with the failing command and a tail of its
8666    /// output recorded here rather than left in `run.json` for someone to go
8667    /// find.
8668    ///
8669    /// A round that deferred its own e2e (see [`Config::graph`]'s
8670    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8671    /// only because nothing ran, and treating an empty list as a passing one
8672    /// here is exactly the "deferred painted green" bug this function exists
8673    /// to not have. When the last round's own verification never resolved —
8674    /// deferred on purpose, or a real attempt the shared build cache blocked
8675    /// — this makes (or retries) the real run, on the actual worktree this
8676    /// loop is about to stop touching, before deciding anything. A
8677    /// resource-blocked attempt is likewise never read as either green or
8678    /// red: it is evidence about the machine, not the patch (see
8679    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8680    /// blocked cache leaves this call without deciding rather than guessing
8681    /// — the caller retries on a later reentry.
8682    /// Record, once, that the review loop handed off over a blocking finding
8683    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8684    /// `land` asks the owner even with `land_approval` off. Called from every
8685    /// path that concludes `Gating`; a reentry keeps the first record.
8686    fn record_contested_handoff(&mut self) {
8687        if self.state.contested_handoff.is_some() {
8688            return;
8689        }
8690        let Some(contested) = self
8691            .state
8692            .reviews
8693            .last()
8694            .and_then(ReviewRound::contested_handoff)
8695        else {
8696            return;
8697        };
8698        self.state.event(
8699            "review",
8700            format!(
8701                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8702                 wait for the owner's approval",
8703                contested.findings.len(),
8704                contested.rejecters.len()
8705            ),
8706        );
8707        self.state.contested_handoff = Some(contested);
8708    }
8709
8710    async fn stop_unresolved_review(
8711        &mut self,
8712        why: &str,
8713        shell: &[String],
8714        worktree: &Path,
8715    ) -> Result<()> {
8716        self.stop_reviewing_inner(why, shell, worktree, true).await
8717    }
8718
8719    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8720        self.stop_reviewing_inner(why, shell, worktree, false).await
8721    }
8722
8723    async fn stop_reviewing_inner(
8724        &mut self,
8725        why: &str,
8726        shell: &[String],
8727        worktree: &Path,
8728        repairable: bool,
8729    ) -> Result<()> {
8730        let round_idx = self.state.reviews.len() - 1;
8731        // A deferred round and a resource-blocked one are the same shape
8732        // here: neither has a real result yet, and both get one more
8733        // attempt. Read off `e2e_status` — the single source for this —
8734        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8735        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8736        // still retries instead of being read as a settled result the
8737        // instant it stops being empty.
8738        let needs_catchup_run = matches!(
8739            self.state.reviews[round_idx].e2e_status(),
8740            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8741        );
8742        if needs_catchup_run {
8743            let round = self.state.reviews[round_idx].round;
8744            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8745            let commands = self.state.config.verify.e2e.clone();
8746            let before_head = git::rev_parse(worktree, "HEAD").await?;
8747            let winner = self.state.winner().cloned();
8748            let cache_dir = self.state.config.cache_dir();
8749            let context = format!(
8750                "round {round}: verification unresolved, catching up before the final decision"
8751            );
8752            let wait = self.repository_wait();
8753            let (outcomes, verify_retried) = with_cache_lease(
8754                &mut self.state,
8755                cache_dir.as_deref(),
8756                "e2e",
8757                "e2e",
8758                worktree,
8759                &before_head,
8760                timeout,
8761                &context,
8762                &wait,
8763                |state, budget| {
8764                    let shell = shell.to_vec();
8765                    let commands = commands.clone();
8766                    let context = context.clone();
8767                    async move {
8768                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8769                            // Same reason as in the round itself: format before
8770                            // the suite, not after it.
8771                            Self::run_pre_gate(state, &winner).await;
8772                        }
8773                        run_e2e_with_retry(
8774                            state,
8775                            &shell,
8776                            &commands,
8777                            worktree,
8778                            budget,
8779                            &context,
8780                            Some(round),
8781                        )
8782                        .await
8783                    }
8784                },
8785            )
8786            .await?;
8787            // After `pre_gate`: the commit the commands actually ran against.
8788            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8789            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8790                self.state.record_base_progress(&attempted_head);
8791            }
8792            let last = &mut self.state.reviews[round_idx];
8793            last.e2e = outcomes;
8794            last.verify_retried = verify_retried;
8795            // Always the commit and time this attempt actually targeted,
8796            // whether or not it happens to equal the reviewed `head` and
8797            // whether or not a command finished — see
8798            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8799            // attempt is recorded too, so a later reader sees "attempted
8800            // again at T2" rather than silence.
8801            last.verified_head = Some(attempted_head);
8802            last.verified_at = Some(Timestamp::now());
8803            if verify_inconclusive(&last.e2e) {
8804                // Still not a real result: `e2e_deferred` is left exactly
8805                // as it was, so `needs_catchup_run` above reads
8806                // `ResourceBlocked` (via `e2e_status`, which checks
8807                // `resource_blocked` before `e2e_deferred`) and retries
8808                // again on the next reentry, rather than recording
8809                // contention as a red e2e and blocking the run on it.
8810                self.state.save()?;
8811                return Ok(());
8812            }
8813            last.e2e_deferred = false;
8814            // A complete panel may have been saved as unclean solely because
8815            // verification could not run. Refresh that verdict with the new
8816            // outcomes before a granted repair consumes the round's result.
8817            // Incomplete panels retain their original policy/quota decision.
8818            if last.answered == last.expected {
8819                last.clean = round_is_clean(
8820                    last.blocking,
8821                    last.e2e.iter().all(CommandOutcome::ok),
8822                    last.answered,
8823                    last.expected,
8824                    0,
8825                    self.state.config.graph.incomplete_review,
8826                );
8827            }
8828        }
8829        let last = &self.state.reviews[round_idx];
8830        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8831
8832        match last.e2e_status() {
8833            E2eStatus::Failed => {
8834                let red: Vec<String> = last
8835                    .e2e
8836                    .iter()
8837                    .filter(|o| !o.ok())
8838                    .map(|o| {
8839                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8840                            .map(|c| format!(" ({c})"))
8841                            .unwrap_or_default();
8842                        format!(
8843                            "`{}` -> {:?}{comparison}\n{}",
8844                            o.command,
8845                            o.code,
8846                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8847                        )
8848                    })
8849                    .collect();
8850                let can_repair = last.blocking == 0 && last.fix.is_none();
8851                self.state.reviews[round_idx].clean = false;
8852                self.state
8853                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8854                self.state.status = RunStatus::Blocked;
8855                if repairable
8856                    && can_repair
8857                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8858                {
8859                    self.state.status = RunStatus::Reviewing;
8860                }
8861            }
8862            // `needs_catchup_run` above already retried once this call; if
8863            // it is still blocked, this is magi's own admission it could
8864            // not get a command to run, never a verdict on the patch — the
8865            // run is left exactly where a later reentry can retry again.
8866            E2eStatus::ResourceBlocked => {
8867                self.state.event(
8868                    "review",
8869                    format!(
8870                        "{why}; e2e could not run (resource unavailable); not \
8871                         deciding yet"
8872                    ),
8873                );
8874            }
8875            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8876                self.state.event(
8877                    "review",
8878                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8879                );
8880                self.record_contested_handoff();
8881                self.state.status = RunStatus::Gating;
8882            }
8883        }
8884        self.state.save()?;
8885        Ok(())
8886    }
8887
8888    // ----------------------------------------------------------------- gate
8889
8890    async fn gate(&mut self) -> Result<()> {
8891        if self.hold_base_sync().await? {
8892            return Ok(());
8893        }
8894        // Judged by the review record itself, not by `status`: a solo
8895        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8896        // reentry (see `judge`), and trusting it here is exactly how a run
8897        // that exhausted its review budget got gated and merged a second
8898        // time around. `review_conclusion` recomputes the review loop's own
8899        // verdict from the round records themselves — `Gating` for a clean
8900        // round or a hand-off (see `stop_reviewing`), anything else means the
8901        // loop is still going or genuinely blocked.
8902        // A base the winner could not be replayed onto is a decision, not a
8903        // round: there is no landing tree to gate. Read as its own record for
8904        // the same reason the review verdict is.
8905        if self.state.status == RunStatus::Failed
8906            || self
8907                .state
8908                .base_sync
8909                .as_ref()
8910                .is_some_and(|s| s.conflict.is_some())
8911            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8912                != Some(RunStatus::Gating)
8913        {
8914            return Ok(());
8915        }
8916        let Some(winner) = self.state.winner().cloned() else {
8917            return Ok(());
8918        };
8919        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8920        self.state.reconcile_verification_head(&head);
8921        self.state.save()?;
8922        let wait = self.repository_wait();
8923        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8924            return Ok(());
8925        }
8926        if self.state.gate_ran {
8927            // `review_loop` derives its conclusion from the clean review
8928            // record on every reentry and therefore puts a completed run back
8929            // in `Gating`. A recorded gate is a stronger, terminal fact:
8930            // retain its original command output (or lack of any, for a repo
8931            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8932            // doc) and restore `Blocked` on a real failure rather than
8933            // pretending the command is still running or running it a second
8934            // time. `gate_ran == false` remains the only shape — unattempted,
8935            // or a resource-blocked retry — that may still need to execute a
8936            // command.
8937            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8938                self.state.status = RunStatus::Blocked;
8939                self.state.save()?;
8940            }
8941            return Ok(());
8942        }
8943        self.state.status = RunStatus::Gating;
8944        let mut outcomes = self.run_gate(&winner).await?;
8945        let mut attempted_head = self.state.gate_head.clone();
8946        loop {
8947            // A resource-blocked outcome means the gate command never actually
8948            // ran - the shared build cache could not be acquired or confirmed
8949            // fresh in time - which is evidence about the machine, not about
8950            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8951            // Recording it as a red gate would mark a run `Blocked` on nothing
8952            // but contention magi has already logged; leaving `self.state.gate`
8953            // empty and `self.state.gate_ran` false instead keeps the shape
8954            // this function already treats as "still needs to run" (see the
8955            // early-return above), so the next call retries the command
8956            // rather than concluding anything.
8957            if verify_inconclusive(&outcomes) {
8958                self.state.save()?;
8959                return Ok(());
8960            }
8961            if outcomes.iter().all(CommandOutcome::ok) {
8962                break;
8963            }
8964            let fixes_before = self.state.gate_fixes.len();
8965            match self.gate_fix_round(&winner, &outcomes).await? {
8966                GateFix::Retry => {
8967                    outcomes = self.run_gate(&winner).await?;
8968                    attempted_head = self.state.gate_head.clone();
8969                }
8970                GateFix::Stop => {
8971                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8972                    if self.state.gate_fixes.len() > fixes_before
8973                        && attempted_head.as_deref() != Some(current.as_str())
8974                        && verify_current_head(&mut self.state, &winner, &wait).await?
8975                    {
8976                        // A new SHA owes a gate even when a spent fixer changed only
8977                        // commit metadata. This does not grant another repair round.
8978                        outcomes = self.run_gate(&winner).await?;
8979                        attempted_head = self.state.gate_head.clone();
8980                    } else {
8981                        break;
8982                    }
8983                }
8984                GateFix::Defer => {
8985                    self.state.save()?;
8986                    return Ok(());
8987                }
8988            }
8989        }
8990        let passed = outcomes.iter().all(CommandOutcome::ok);
8991        self.state.gate = outcomes;
8992        self.state.gate_ran = true;
8993        self.state.gate_head = attempted_head;
8994        if !self.state.gate.is_empty()
8995            && !verify_inconclusive(&self.state.gate)
8996            && let Some(head) = self.state.gate_head.clone()
8997        {
8998            self.state.record_base_progress(&head);
8999        }
9000        self.state.save()?;
9001        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9002            return Ok(());
9003        }
9004        if !passed {
9005            self.state.status = RunStatus::Blocked;
9006            let spent = self.state.gate_fixes.len();
9007            self.state.event(
9008                "gate",
9009                if spent == 0 {
9010                    "gate failed; not merging".to_owned()
9011                } else {
9012                    format!("gate failed after {spent} gate-fix round(s); not merging")
9013                },
9014            );
9015        }
9016        self.state.save()?;
9017        Ok(())
9018    }
9019
9020    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9021    /// changed into one commit. Runs before `verify.e2e` in the review loop
9022    /// and again before the gate commands, always on the winner and never on
9023    /// a candidate awaiting judging.
9024    ///
9025    /// Before e2e as well as before the gate because command evidence belongs
9026    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9027    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9028    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9029    /// own call then finds nothing left to change. The commands must be
9030    /// idempotent; one that is not makes a commit per call.
9031    ///
9032    /// Never fails the run: a non-zero exit or timeout is a warning and a
9033    /// recorded outcome, and the gate remains the single arbiter. Nothing
9034    /// configured means nothing happens - no event, no commit. `commit_all`
9035    /// commits any leftover change under the neutral identity and returns
9036    /// `false` when the tree is clean, so no empty commit is ever made.
9037    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9038        let commands = state.config.verify.pre_gate.clone();
9039        if commands.is_empty() {
9040            return;
9041        }
9042        let shell = state.config.shell();
9043        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9044        let (outcomes, _) = run_commands(
9045            state,
9046            "pre_gate",
9047            "pre_gate",
9048            0,
9049            &shell,
9050            &commands,
9051            &winner.worktree,
9052            timeout,
9053        )
9054        .await;
9055        for o in &outcomes {
9056            if !o.ok() {
9057                tracing::warn!(
9058                    "pre_gate `{}` failed ({:?}); the gate decides",
9059                    o.command,
9060                    o.code
9061                );
9062            }
9063            state.event(
9064                "pre_gate",
9065                format!(
9066                    "`{}` -> {}",
9067                    o.command,
9068                    if o.ok() {
9069                        "pass".to_owned()
9070                    } else {
9071                        format!(
9072                            "FAIL ({:?})\n{}",
9073                            o.code,
9074                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9075                        )
9076                    }
9077                ),
9078            );
9079        }
9080        state.pre_gate = outcomes;
9081        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9082            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9083                Ok(head) => {
9084                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9085                    state.pre_gate_commit = Some(head);
9086                }
9087                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9088            },
9089            Ok(false) => {}
9090            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9091        }
9092        if let Err(e) = state.save() {
9093            tracing::warn!("could not persist the pre_gate record: {e:#}");
9094        }
9095    }
9096
9097    /// Run `verify.gate` once against the winner's current tree, logging one
9098    /// event per command. Empty when nothing is configured.
9099    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9100        let wait = self.repository_wait();
9101        run_landing_gate(&mut self.state, winner, &wait).await
9102    }
9103
9104    /// One bounded fix round for a failing gate.
9105    ///
9106    /// The fixer is told the failure came from the gate itself, not from a
9107    /// reviewer, and is shown the failed commands, their exit codes and a tail
9108    /// of their output - whatever `[verify].gate` holds, nothing here knows
9109    /// what those commands run. Only a normal non-zero exit that printed
9110    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9111    /// command or a full disk says nothing about the code, and a fixer sent
9112    /// after it can only appease the machine. The round is judged by what git
9113    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9114    /// again before the gate does, so a fix cannot trade a green gate for a
9115    /// red e2e unnoticed.
9116    async fn gate_fix_round(
9117        &mut self,
9118        winner: &Candidate,
9119        outcomes: &[CommandOutcome],
9120    ) -> Result<GateFix> {
9121        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9122            g.phase == crate::repair_budget::Phase::Fixing
9123                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9124        }) {
9125            self.state.gate_fixes.len().saturating_add(1)
9126        } else {
9127            self.state.config.graph.gate_fix_rounds
9128        };
9129        let spent = self.state.gate_fixes.len();
9130        if spent >= cap {
9131            if cap > 0 {
9132                self.state.event(
9133                    "gate",
9134                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9135                );
9136            }
9137            return Ok(GateFix::Stop);
9138        }
9139        if !gate_fixable(outcomes) {
9140            self.state.event(
9141                "gate",
9142                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9143                 command or similar); not spending a fix round on it",
9144            );
9145            return Ok(GateFix::Stop);
9146        }
9147        let min_free = self.state.config.disk.min_free_bytes;
9148        if min_free > 0 {
9149            match crate::disk::free_bytes(&winner.worktree) {
9150                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9151                Ok(free) => {
9152                    self.state.event(
9153                        "gate",
9154                        format!(
9155                            "only {free} bytes free ({min_free} required by `[disk] \
9156                             min_free_bytes`); not spending a fix round on a failure the disk \
9157                             may explain"
9158                        ),
9159                    );
9160                    return Ok(GateFix::Stop);
9161                }
9162                Err(e) => {
9163                    self.state.event(
9164                        "gate",
9165                        format!("free disk space could not be measured ({e:#}); no fix round"),
9166                    );
9167                    return Ok(GateFix::Stop);
9168                }
9169            }
9170        }
9171
9172        let attempt = spent + 1;
9173        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9174        let base = self.landing_base();
9175        let fix_prompt = prompt::gate_fix_in(
9176            &self.state.instruction,
9177            &failed,
9178            attempt,
9179            cap,
9180            &self.state.config.graph.language,
9181            &self.state.config.graph.github_language,
9182        );
9183        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9184        let sessions = self.state.config.graph.sessions;
9185        let artifacts = self.merge_repair_artifacts();
9186        self.state.event(
9187            "gate",
9188            format!("gate failed; gate-fix round {attempt} of {cap}"),
9189        );
9190        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9191        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9192        // Persist before invoking the fixer: it may commit and then be
9193        // interrupted before its result (or the following e2e) is saved.
9194        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9195            before.clone(),
9196            false,
9197            Vec::new(),
9198        ));
9199        self.state.save()?;
9200        let (_, seat, out) = self
9201            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9202                prompt: fix_prompt.clone(),
9203                spec,
9204                seat,
9205                cwd: winner.worktree.clone(),
9206                timeout,
9207                allow_write: true,
9208                sessions,
9209                artifacts: artifacts.clone(),
9210                stem: format!("gate-fix-{attempt}"),
9211                handover: None,
9212            })
9213            .await;
9214        // The fixer was never asked: no round is spent (nothing is recorded)
9215        // and a later reentry asks the same agent again.
9216        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9217            return Ok(GateFix::Defer);
9218        }
9219        let mut record = GateFixRecord {
9220            agent: seat.agent.clone(),
9221            failed,
9222            notes: String::new(),
9223            committed: false,
9224            error: None,
9225        };
9226        match out {
9227            AgentOutcome::Ok(o) => {
9228                // A missing report is not a failed fix: the round is judged
9229                // by the tree below, and the report only carries prose.
9230                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9231                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9232                }
9233            }
9234            AgentOutcome::Dropped(_) => {
9235                record.error = Some("the CLI dropped the stream".to_owned());
9236            }
9237            AgentOutcome::Quota(o) => {
9238                self.state.quota.push(QuotaLoss::from_report(
9239                    seat.key.clone(),
9240                    "gate-fix",
9241                    o.quota.as_ref(),
9242                ));
9243                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9244            }
9245            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9246        }
9247        self.state.seats.insert(seat.key.clone(), seat);
9248        let coordination = self.coordinate(&winner.worktree).await?;
9249        if let Ok(r) = git::rescue_commit(
9250            &winner.worktree,
9251            &format!("magi: gate fix {attempt} (uncommitted work)"),
9252        )
9253        .await
9254        {
9255            self.state.note_withheld("gate-fix", &r.withheld);
9256        }
9257        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9258        record.committed = after != before;
9259        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9260        let note = record.error.clone();
9261        self.state.gate_fixes.push(record);
9262        self.state.save()?;
9263        if !changed {
9264            self.state.event(
9265                "gate",
9266                match note {
9267                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9268                    None => format!("gate-fix round {attempt}: the tree did not change"),
9269                },
9270            );
9271            return Ok(GateFix::Stop);
9272        }
9273        self.state.event(
9274            "gate",
9275            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9276        );
9277
9278        drop(coordination);
9279        let wait = self.repository_wait();
9280        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9281    }
9282
9283    // ---------------------------------------------------------------- merge
9284
9285    /// One read-only rewrite by the summary's author; a text the gate still
9286    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9287    /// applies on their word or on silence. `None` means the run is parked on
9288    /// that question and nothing may be pushed or opened yet.
9289    async fn guarded_pr_message(
9290        &mut self,
9291        winner: &Candidate,
9292        facts: Option<&BranchFacts>,
9293        posting: bool,
9294    ) -> Result<Option<PrMessage>> {
9295        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9296        let head = match final_head.as_deref() {
9297            Some(h) => crate::pr_outcome::FinalHead::At(h),
9298            None => crate::pr_outcome::FinalHead::Unknown,
9299        };
9300        // Only a pull request that is about to be posted pays for a summary.
9301        let summarized = if posting {
9302            Some(self.summarize_change(winner, final_head.as_deref()).await)
9303        } else {
9304            None
9305        };
9306        // A busy shared resource is not a permanent cause: publishing an
9307        // "unavailable" description would stick (a later head move never
9308        // edits the body). Stop before anything is pushed or opened; the
9309        // run is `Blocked` and a resume asks the summary again.
9310        if self.state.resource_block.is_some() {
9311            self.state.event(
9312                "pr-summary",
9313                "a shared resource was busy; nothing was published, resume to summarize again",
9314            );
9315            return Ok(None);
9316        }
9317        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9318            anyhow::bail!(
9319                "the final commit moved during public description generation; retry before publishing"
9320            );
9321        }
9322        let note = match (&summarized, &self.state.change_summary) {
9323            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9324            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9325            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9326            (None, _) => ChangeNote::NotAsked,
9327        };
9328        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9329        if !posting {
9330            let identity = crate::scrub::Identity::current();
9331            return Ok(Some(PrMessage {
9332                title: crate::scrub::scrub(&pr.title, &identity),
9333                body: crate::scrub::scrub(&pr.body, &identity),
9334            }));
9335        }
9336        // This very text was already rejected and asked about: no second
9337        // judge call, rewrite or question, just carry the record on.
9338        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9339        if let Some(known) = self
9340            .state
9341            .github_text
9342            .clone()
9343            .filter(|g| g.fingerprint == raw_fp)
9344        {
9345            return self.settle_withheld(winner, &pr, known).await;
9346        }
9347        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9348        let mut violations =
9349            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9350        let identity = crate::scrub::Identity::current();
9351        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9352            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9353            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9354        {
9355            violations.push(crate::github_text::Violation::SensitiveData);
9356        }
9357        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9358        // only a language violation starts one; sensitive data alone goes
9359        // straight to the owner, with the redacted text as the fallback.
9360        let has_language = violations
9361            .iter()
9362            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9363        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9364            self.state.event(
9365                "github-text",
9366                if has_language {
9367                    format!("description rejected: {violations:?}; requesting one rewrite")
9368                } else {
9369                    format!("description rejected: {violations:?}; asking the owner")
9370                },
9371            );
9372            let mut rewritten = false;
9373            let mut rejected_rewrite = None;
9374            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9375            {
9376                let output = text;
9377                if let Some(title) = summary_title(&output) {
9378                    // Judge the redacted candidate that will actually be posted.
9379                    // Sensitive data alone must not discard a useful rewrite.
9380                    let raw_body = summary_without_title(&output);
9381                    let clean_title = crate::scrub::scrub(&title, &identity);
9382                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9383                    let redacted = clean_title != title || body != raw_body;
9384                    let title = clean_title;
9385                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9386                    if !complete {
9387                        self.state.event(
9388                            "github-text",
9389                            "description rewrite omitted required findings",
9390                        );
9391                    }
9392                    if !body.trim().is_empty() {
9393                        body.push_str("\n\n");
9394                        body.push_str(&public_pr_evidence(&self.state, head));
9395                    }
9396                    let marker = format!("magi:run/{}", self.state.id);
9397                    if !body.trim().is_empty() && !body.contains(&marker) {
9398                        body.push_str(&format!("\n\n{marker}"));
9399                    }
9400                    let rewrite = PrMessage {
9401                        title: title.clone(),
9402                        body: body.clone(),
9403                    };
9404                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9405                    let mut failed = crate::github_text::check_for(
9406                        &self.state.config.graph,
9407                        &title,
9408                        &body,
9409                        redecision,
9410                    );
9411                    if (!crate::github_text::shareable(&title)
9412                        || !crate::github_text::shareable(&body))
9413                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9414                    {
9415                        failed.push(crate::github_text::Violation::SensitiveData);
9416                    }
9417                    if complete
9418                        && !title.trim().is_empty()
9419                        && !body.trim().is_empty()
9420                        && !failed.is_empty()
9421                    {
9422                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9423                            title: title.clone(),
9424                            body: body.clone(),
9425                            failed: failed
9426                                .iter()
9427                                .map(|v| crate::github_text::category(*v).to_owned())
9428                                .collect(),
9429                        });
9430                    }
9431                    if complete
9432                        && !title.trim().is_empty()
9433                        && !raw_body.trim().is_empty()
9434                        && failed.is_empty()
9435                    {
9436                        decision = redecision;
9437                        pr = PrMessage { title, body };
9438                        rewritten = true;
9439                        self.state
9440                            .event("github-text", "description rewrite passed");
9441                        if redacted {
9442                            self.state.event(
9443                                "github-text",
9444                                "sensitive data removed from description rewrite",
9445                            );
9446                        }
9447                    }
9448                }
9449            }
9450            if !rewritten {
9451                self.state.event(
9452                    "github-text",
9453                    "description rewrite unavailable or rejected; asking the owner",
9454                );
9455                if let Some(w) =
9456                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9457                {
9458                    // A different text than the one asked about before: that
9459                    // question no longer describes anything.
9460                    self.retire_github_text_question("the withheld text changed");
9461                    let record = crate::run::GithubTextAsk {
9462                        rewrite: rejected_rewrite,
9463                        fingerprint: raw_fp,
9464                        title: w.title,
9465                        body: w.body,
9466                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9467                        question: None,
9468                        asks: 0,
9469                        resolved: false,
9470                        chosen_title: None,
9471                        choice: None,
9472                        publication: None,
9473                    };
9474                    return self.settle_withheld(winner, &pr, record).await;
9475                }
9476            }
9477        }
9478        let (title, body) =
9479            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9480        Ok(Some(PrMessage { title, body }))
9481    }
9482
9483    /// Describe the whole change from its final diff in either run mode.
9484    ///
9485    /// The summary is tied to the final commit and to the merge base of the
9486    /// resolved remote base; a record for any other pair is dropped and the
9487    /// agent asked again, so a description never outlives the diff it was
9488    /// written from. The seat is read-only and the prompt tells it to read the
9489    /// diff and the code around it. `[roles] synthesizer` selects the agents
9490    /// (unset: the default pick), each asked at most once, advancing on an
9491    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9492    /// carries the reason it is unavailable; nothing is invented then.
9493    async fn summarize_change(
9494        &mut self,
9495        winner: &Candidate,
9496        head: Option<&str>,
9497    ) -> std::result::Result<(), String> {
9498        let Some(head) = head else {
9499            return Err("the final commit could not be read".to_owned());
9500        };
9501        let remote = self.state.config.merge.remote.clone();
9502        let tracking = format!("{remote}/{}", self.state.base_branch);
9503        if !git::rev_exists(&winner.worktree, &tracking).await {
9504            return Err(format!("the remote base `{tracking}` could not be read"));
9505        }
9506        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9507            Ok(b) if !b.is_empty() => b,
9508            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9509        };
9510        let evidence = crate::pr_outcome::summary_evidence(
9511            &self.state,
9512            crate::pr_outcome::FinalHead::At(head),
9513        );
9514        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9515        if self
9516            .state
9517            .change_summary
9518            .as_ref()
9519            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9520        {
9521            return Ok(());
9522        }
9523        if self.state.change_summary.take().is_some() {
9524            self.state.event(
9525                "pr-summary",
9526                "the final diff or evidence changed; the earlier change summary was discarded",
9527            );
9528        }
9529        // Save the source snapshot even if no generation agent is available.
9530        if let Err(e) = write_artifact(
9531            &self.state,
9532            &format!("public-description-{fingerprint}.md"),
9533            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9534        ) {
9535            tracing::warn!("could not save public description evidence: {e:#}");
9536        }
9537        let chain = match agent::pick_chain(
9538            &self.state.config.agents,
9539            self.state.config.roles.synthesizer.as_ref(),
9540            &agent::installed,
9541            "synthesizer",
9542        ) {
9543            Ok(chain) => chain,
9544            Err(e) => {
9545                tracing::warn!("no agent for the change summary: {e:#}");
9546                self.state.event("pr-summary", "no summary agent available");
9547                return Err("no agent was available to summarize it".to_owned());
9548            }
9549        };
9550        let subjects = git::subjects(&winner.worktree, &base, head)
9551            .await
9552            .unwrap_or_default();
9553        let stat = git::diff_stat(&winner.worktree, &base, head)
9554            .await
9555            .unwrap_or_default();
9556        let stat: String = stat.chars().take(6_000).collect();
9557        let mut prompt = crate::prompt::change_summary_in(
9558            &base,
9559            head,
9560            &subjects,
9561            stat.trim(),
9562            &self.state.config.graph.github_language,
9563        );
9564        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."));
9565        let sessions = self.state.config.graph.sessions;
9566        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9567        let prompts = self.state.config.prompts.clone();
9568        let cache = self.state.config.cache_dir();
9569        let run = self.state.id.clone();
9570        for (i, spec) in chain.into_iter().enumerate() {
9571            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9572            let github_spec = match agent::for_github_text(
9573                &spec,
9574                &self.state.config.graph.github_language,
9575                &winner.worktree,
9576            ) {
9577                Ok(spec) => spec,
9578                Err(e) => {
9579                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9580                    continue;
9581                }
9582            };
9583            let job = SeatJob {
9584                spec: github_spec,
9585                seat,
9586                cwd: winner.worktree.clone(),
9587                prompt: prompt.clone(),
9588                timeout,
9589                allow_write: false,
9590                sessions,
9591                artifacts: agent::artifacts_dir(&self.state.dir()),
9592                stem: if i == 0 {
9593                    "change-summary".to_owned()
9594                } else {
9595                    format!("change-summary-{}", spec.id)
9596                },
9597                handover: None,
9598            };
9599            let ctx = WaveCtx {
9600                run: &run,
9601                node: "pr-summary",
9602                prompts: &prompts,
9603                cache: cache.as_deref(),
9604                round: None,
9605                carry_seats: false,
9606                pauses: Some((&self.pause, &self.interrupt)),
9607            };
9608            let (seat, outcome) =
9609                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9610            self.state.seats.insert(seat.key.clone(), seat);
9611            let text = match outcome {
9612                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9613                AgentOutcome::ResourceBlocked(why) => {
9614                    // No agent was asked: the run stops resumably before
9615                    // anything is published (see `guarded_pr_message`).
9616                    if self.state.resource_block.is_none() {
9617                        self.state.resource_block = Some(crate::run::ResourceBlock {
9618                            cause: crate::run::ResourceBlockCause::Other,
9619                            node: "pr-summary".to_owned(),
9620                            kind: "shared resource".to_owned(),
9621                            detail: why,
9622                            at: Timestamp::now(),
9623                        });
9624                    }
9625                    return Err("a shared resource was busy".to_owned());
9626                }
9627                _ => continue,
9628            };
9629            let blind = &self.state.config.blind;
9630            let Some(title) = summary_title(&text) else {
9631                continue;
9632            };
9633            let body: String = summary_without_title(&text)
9634                .lines()
9635                .filter(|l| !l.contains("magi:run/"))
9636                .collect::<Vec<_>>()
9637                .join("\n");
9638            let body = blind::sanitize_prose(body.trim(), blind);
9639            let title = blind::sanitize_prose(&title, blind);
9640            if body.trim().is_empty() || title.trim().is_empty() {
9641                continue;
9642            }
9643            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9644                continue;
9645            }
9646            // The branch must still be the one the agent was shown.
9647            if git::rev_parse(&winner.worktree, "HEAD")
9648                .await
9649                .ok()
9650                .as_deref()
9651                != Some(head)
9652            {
9653                return Err("the branch moved while the summary was written".to_owned());
9654            }
9655            if git::merge_base(&winner.worktree, &tracking, head)
9656                .await
9657                .ok()
9658                .as_deref()
9659                != Some(base.as_str())
9660                || crate::pr_outcome::summary_evidence(
9661                    &self.state,
9662                    crate::pr_outcome::FinalHead::At(head),
9663                ) != evidence
9664            {
9665                return Err("the summary evidence changed while it was written".to_owned());
9666            }
9667            self.state.change_summary = Some(crate::run::ChangeSummary {
9668                head: head.to_owned(),
9669                base,
9670                evidence: fingerprint,
9671                title,
9672                body,
9673            });
9674            self.state.event(
9675                "pr-summary",
9676                format!("change summary written by {} for the final diff", spec.id),
9677            );
9678            if let Err(e) = self.state.save() {
9679                tracing::warn!("could not save the change summary: {e:#}");
9680            }
9681            return Ok(());
9682        }
9683        self.state
9684            .event("pr-summary", "no agent produced a change summary");
9685        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9686    }
9687
9688    /// One read-only rewrite request for a withheld description. The
9689    /// implementer's own conversation is tried first when it exists and can be
9690    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9691    /// writes it in a separate conversation, skipping the implementer's agent.
9692    /// The prompt carries the whole text, so no agent needs any memory. Each
9693    /// agent is asked at most once and the chain advances on an error, quota,
9694    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9695    /// that has run out of quota must not end the rewrite. Nothing is recorded
9696    /// as a handover.
9697    async fn rewrite_pr_text(
9698        &mut self,
9699        winner: &Candidate,
9700        pr: &PrMessage,
9701        violations: &[crate::github_text::Violation],
9702    ) -> Option<String> {
9703        let prompt = format!(
9704            "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{}",
9705            pr.title, pr.body
9706        );
9707        let sessions = self.state.config.graph.sessions;
9708        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9709        // (spec, the resumed implementer's seat). A fallback seat is created
9710        // only when its turn comes, so an unused fallback leaves no record.
9711        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9712        let key = format!("impl-{}", winner.label);
9713        if let Some(spec) = self
9714            .state
9715            .config
9716            .agents
9717            .iter()
9718            .find(|a| a.id == winner.agent)
9719            .cloned()
9720            && let Some(existing) = self.state.seats.get(&key)
9721            && existing.agent == spec.id
9722            && agent::has_session(spec.kind, existing, sessions)
9723        {
9724            attempts.push((spec, Some(existing.clone())));
9725        }
9726        match agent::pick_chain(
9727            &self.state.config.agents,
9728            self.state.config.roles.language_judge.as_ref(),
9729            &agent::installed,
9730            "language_judge",
9731        ) {
9732            Ok(chain) => {
9733                for spec in chain {
9734                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9735                        continue;
9736                    }
9737                    attempts.push((spec, None));
9738                }
9739            }
9740            Err(e) if attempts.is_empty() => {
9741                tracing::warn!("no agent for the description rewrite: {e:#}");
9742                self.state
9743                    .event("github-text", "no rewrite agent available");
9744                return None;
9745            }
9746            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9747        }
9748        let prompts = self.state.config.prompts.clone();
9749        let cache = self.state.config.cache_dir();
9750        let run = self.state.id.clone();
9751        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9752            let resumed = resumed_seat.is_some();
9753            let seat = resumed_seat.unwrap_or_else(|| {
9754                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9755            });
9756            let github_spec = match agent::for_github_text(
9757                &spec,
9758                &self.state.config.graph.github_language,
9759                &winner.worktree,
9760            ) {
9761                Ok(spec) => spec,
9762                Err(e) => {
9763                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9764                    continue;
9765                }
9766            };
9767            let job = SeatJob {
9768                spec: github_spec,
9769                seat,
9770                cwd: winner.worktree.clone(),
9771                prompt: prompt.clone(),
9772                timeout: retry_budget(timeout_full, resumed),
9773                allow_write: false,
9774                sessions,
9775                artifacts: agent::artifacts_dir(&self.state.dir()),
9776                stem: if i == 0 {
9777                    "github-text-rewrite".to_owned()
9778                } else {
9779                    format!("github-text-rewrite-{}", spec.id)
9780                },
9781                handover: None,
9782            };
9783            let ctx = WaveCtx {
9784                run: &run,
9785                node: "github-text",
9786                prompts: &prompts,
9787                cache: cache.as_deref(),
9788                round: None,
9789                carry_seats: false,
9790                pauses: Some((&self.pause, &self.interrupt)),
9791            };
9792            let (seat, outcome) =
9793                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9794            self.state.seats.insert(seat.key.clone(), seat);
9795            match outcome {
9796                AgentOutcome::Ok(o)
9797                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9798                {
9799                    return Some(o.text);
9800                }
9801                AgentOutcome::ResourceBlocked(_) => return None,
9802                _ => {}
9803            }
9804        }
9805        None
9806    }
9807
9808    /// Abandon the standing posting-gate question, if any.
9809    fn retire_github_text_question(&mut self, why: &str) {
9810        let Some(id) = self
9811            .state
9812            .github_text
9813            .as_ref()
9814            .and_then(|g| g.question.clone())
9815        else {
9816            return;
9817        };
9818        let _ = ask::Questions::open().update(&id, |q| {
9819            q.abandon(why);
9820            Ok(())
9821        });
9822    }
9823
9824    /// Carry a withheld text to its end: file the question, park while it is
9825    /// open, and on an answer, silence or timeout pick the text to post. The
9826    /// decision is saved before it is used, so it applies once.
9827    async fn settle_withheld(
9828        &mut self,
9829        winner: &Candidate,
9830        pr: &PrMessage,
9831        mut g: crate::run::GithubTextAsk,
9832    ) -> Result<Option<PrMessage>> {
9833        use crate::github_text as gt;
9834        let store = ask::Questions::open();
9835        let timeout = self.state.config.graph.answer_timeout;
9836        if !g.resolved {
9837            let mut standing = g
9838                .question
9839                .as_ref()
9840                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9841            if let Some(q) = standing.as_ref()
9842                && q.status.open()
9843                && !store.held_reply(&q.id)
9844                && gt::expired(q, timeout)
9845            {
9846                let why = format!("no answer within {}s of asking", timeout.max(1));
9847                standing = store
9848                    .update(&q.id, |q| {
9849                        q.abandon(&why);
9850                        Ok(())
9851                    })
9852                    .ok()
9853                    .map(|(q, ())| q);
9854            }
9855            let mut ask_again: Option<Option<Vec<String>>> = None;
9856            match standing {
9857                // Recorded but never written (a stop between the two saves),
9858                // or removed: ask again without spending the retry.
9859                None if g.asks <= 1 => {
9860                    g.asks = 0;
9861                    ask_again = Some(None);
9862                }
9863                None => {
9864                    g.resolved = true;
9865                    g.chosen_title = None;
9866                    g.choice = Some(GithubTextChoice::Fallback);
9867                }
9868                Some(q) if q.status.open() => {
9869                    self.park_on_github_text(&g)?;
9870                    return Ok(None);
9871                }
9872                Some(q) => match gt::read_reply(&q) {
9873                    gt::Reply::Fallback => {
9874                        g.resolved = true;
9875                        g.chosen_title = None;
9876                        g.choice = Some(GithubTextChoice::Fallback);
9877                    }
9878                    gt::Reply::Original => {
9879                        g.resolved = true;
9880                        g.chosen_title = None;
9881                        g.choice = Some(GithubTextChoice::Original);
9882                    }
9883                    gt::Reply::Rewrite => {
9884                        g.resolved = true;
9885                        g.chosen_title = None;
9886                        g.choice = Some(if g.rewrite.is_some() {
9887                            GithubTextChoice::Rewrite
9888                        } else {
9889                            GithubTextChoice::Fallback
9890                        });
9891                    }
9892                    gt::Reply::Title(text) => {
9893                        let first = text
9894                            .lines()
9895                            .map(str::trim)
9896                            .find(|l| !l.is_empty())
9897                            .unwrap_or("");
9898                        let decision = if first.is_empty() {
9899                            None
9900                        } else {
9901                            let candidate = PrMessage {
9902                                title: first.to_owned(),
9903                                body: String::new(),
9904                            };
9905                            self.judge_pr_language(&winner.worktree, &candidate).await
9906                        };
9907                        match gt::vet_title(
9908                            &text,
9909                            decision,
9910                            self.state.config.graph.github_english(),
9911                        ) {
9912                            Ok(title) => {
9913                                g.resolved = true;
9914                                g.chosen_title = Some(title);
9915                                g.choice = Some(GithubTextChoice::MyTitle);
9916                            }
9917                            Err(cats) if g.asks < 2 => {
9918                                ask_again = Some(Some(
9919                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9920                                ))
9921                            }
9922                            Err(_) => {
9923                                g.resolved = true;
9924                                g.chosen_title = None;
9925                                g.choice = Some(GithubTextChoice::Fallback);
9926                            }
9927                        }
9928                    }
9929                },
9930            }
9931            if let Some(rejected) = ask_again {
9932                // A retry (after a rejected replacement title) is still about
9933                // the original text: the same ORIGINAL / FALLBACK comparison.
9934                let w = gt::Withheld {
9935                    title: g.title,
9936                    body: g.body,
9937                    categories: g.categories.clone(),
9938                };
9939                // Named by the original text's fingerprint alone, so a resume
9940                // rewrites the same file and the detail stays identical.
9941                let artifact = match crate::run::write_artifact(
9942                    &self.state,
9943                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9944                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9945                ) {
9946                    Ok(p) => Some(p),
9947                    Err(e) => {
9948                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9949                        None
9950                    }
9951                };
9952                let (detail, comparison) = gt::question_content(
9953                    &w,
9954                    &pr.title,
9955                    &pr.body,
9956                    &self.state.id,
9957                    rejected.as_deref(),
9958                    artifact.as_deref(),
9959                    g.rewrite.as_ref(),
9960                );
9961                let mut q = ask::Question::new(
9962                    self.state.id.clone(),
9963                    gt::ASK_NODE.to_owned(),
9964                    gt::ASK_SEAT.to_owned(),
9965                    gt::question_summary(&self.state.config.graph.language, &w),
9966                    detail,
9967                    gt::question_choices(&w, g.rewrite.as_ref()),
9968                );
9969                q.posting_comparison = Some(comparison);
9970                q.answer_timeout = timeout;
9971                // Recorded before it is written: a stop in between leaves a
9972                // record naming a question the resume then files again.
9973                g.question = Some(q.id.clone());
9974                g.asks += 1;
9975                self.state.github_text = Some(g.clone());
9976                self.state.event(
9977                    "github-text",
9978                    format!("asking the owner about the withheld text ({})", q.short()),
9979                );
9980                self.state.save()?;
9981                store
9982                    .put_executable(&mut q)
9983                    .context("file the posting-gate question")?;
9984                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9985                    tracing::warn!(
9986                        "could not notify about posting-gate question {}: {e:#}",
9987                        q.short()
9988                    );
9989                }
9990                self.park_on_github_text(&g)?;
9991                return Ok(None);
9992            }
9993        }
9994        let resolved = g.chosen_title.clone();
9995        let original = g.choice == Some(GithubTextChoice::Original);
9996        // Field names only: the event log never records the text.
9997        self.state.event(
9998            "github-text",
9999            if original {
10000                format!(
10001                    "posting the original text for: {}",
10002                    match (g.title, g.body) {
10003                        (true, true) => "title, description",
10004                        (true, false) => "title",
10005                        _ => "description",
10006                    }
10007                )
10008            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10009                "posting the saved rewrite title and description".to_owned()
10010            } else if resolved.is_some() {
10011                "posting the owner's replacement title".to_owned()
10012            } else {
10013                "posting the neutral text for the withheld fields".to_owned()
10014            },
10015        );
10016        self.state.github_text = Some(g.clone());
10017        self.state.save()?;
10018        if g.choice == Some(GithubTextChoice::Rewrite)
10019            && let Some(r) = g.rewrite.as_ref()
10020        {
10021            return Ok(Some(PrMessage {
10022                title: r.title.clone(),
10023                body: r.body.clone(),
10024            }));
10025        }
10026        let w = gt::Withheld {
10027            title: g.title,
10028            body: g.body,
10029            categories: g.categories.clone(),
10030        };
10031        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10032        if let Some(t) = resolved {
10033            title = t;
10034        }
10035        // Every withheld field is now neutral or vetted English.
10036        let english = gt::LanguageDecision {
10037            title_english: true,
10038            body_english: true,
10039            body_complete: true,
10040        };
10041        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10042        if original {
10043            // The owner's explicit choice overrides the gate for the fields it
10044            // was made for; the others keep what the gate produced.
10045            if g.title {
10046                title = pr.title.clone();
10047            }
10048            if g.body {
10049                body = pr.body.clone();
10050            }
10051        }
10052        Ok(Some(PrMessage { title, body }))
10053    }
10054
10055    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10056        self.state.github_text = Some(g.clone());
10057        self.state.end_pass_parked(ParkCause::Question);
10058        self.state.parked = true;
10059        self.state.event(
10060            "github-text",
10061            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10062        );
10063        self.state.save()
10064    }
10065
10066    /// Ask `[roles] language_judge` about this text and record which source
10067    /// decided; the text itself is never recorded.
10068    async fn judge_pr_language(
10069        &mut self,
10070        cwd: &Path,
10071        pr: &PrMessage,
10072    ) -> Option<crate::github_text::LanguageDecision> {
10073        self.state.config.roles.language_judge.as_ref()?;
10074        if !self.state.config.graph.language_gate() {
10075            return None;
10076        }
10077        let decision =
10078            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10079        self.state.event(
10080            "github-text",
10081            if decision.is_some() {
10082                "language decided by the language judge"
10083            } else {
10084                "language judge unavailable; using built-in heuristics"
10085            },
10086        );
10087        decision
10088    }
10089
10090    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10091        Box::pin(self.merge_inner())
10092    }
10093
10094    async fn merge_inner(&mut self) -> Result<()> {
10095        if self.resource_halt()? || self.hold_base_sync().await? {
10096            return Ok(());
10097        }
10098        // Same reasoning as `gate`: ask the review and gate records directly
10099        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10100        // skip can rewrite on reentry to something that no longer says
10101        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10102        // so a hand-off (open findings, green verification) reaches merge
10103        // exactly like a genuinely clean round does.
10104        //
10105        // A run resumed mid-`land` never reaches here at all: `execute`
10106        // recognises `RunStatus::Landing` before it even calls `prep`, and
10107        // routes straight to `run_land` instead. That has to happen a level
10108        // up from this function, not with a check in here, because
10109        // `review_loop`'s own status recomputation (see its doc) runs
10110        // *before* `merge` on every reentry and would otherwise overwrite
10111        // the `Landing` marker with `Gating` before this node ever saw it.
10112        if self
10113            .state
10114            .base_sync
10115            .as_ref()
10116            .is_some_and(|s| s.conflict.is_some())
10117            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10118                != Some(RunStatus::Gating)
10119            // `gate_ran == false` is not "passed" - `gate` leaves it false
10120            // both before it has ever run and when its last attempt was
10121            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10122            // permission to merge on nothing but the review record. Only a
10123            // gate that actually ran may proceed; an intentional local
10124            // review can also finish with verification explicitly not configured.
10125            // `RunState::gate_status` computes that distinction.
10126            || !self.state.gate_allows_progress()
10127        {
10128            return Ok(());
10129        }
10130        // This node's own record, not `status`: `status == Ready` is not
10131        // unique to the harmless `MergeMode::None` path this line was
10132        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10133        // run's PR was closed without merging — and on that run `mode` is
10134        // still `Pr`, so a reentry that fell through here would push and
10135        // open a second pull request. `self.state.merge` is set exactly once
10136        // this node (or `land`) has already produced a verdict, under every
10137        // mode, which is what "already done" actually means here.
10138        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10139            return Ok(());
10140        }
10141        let Some(winner) = self.state.winner().cloned() else {
10142            return Ok(());
10143        };
10144        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10145        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10146            self.state.status = RunStatus::Blocked;
10147            self.state.event(
10148                "gate",
10149                "winner changed after gate; fresh verification required",
10150            );
10151            self.state.save()?;
10152            return Ok(());
10153        }
10154        let wait = self.repository_wait();
10155        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10156            return Ok(());
10157        }
10158        let repo = self.state.repo.clone();
10159        let base = self.state.base_branch.clone();
10160        let mode = self.state.config.merge.mode;
10161        let style = self.state.config.merge.style;
10162        let facts = if is_review_run(&self.state) {
10163            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10164            let start = review_base(
10165                &repo,
10166                &self.state.config.merge.remote,
10167                &base,
10168                &self.state.base_commit,
10169                &winner.branch,
10170            )
10171            .await;
10172            branch_facts(&repo, &start, &winner.branch).await
10173        } else {
10174            None
10175        };
10176        // `None` when the base could not be freshly read: then an adopted
10177        // pull request's title is left alone.
10178        let leaked = if is_review_run(&self.state) {
10179            leaked_subjects(&self.state, &winner.branch).await
10180        } else {
10181            Some(Vec::new())
10182        };
10183        // `None`: parked on the owner's word about a withheld title or body.
10184        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10185        // the resume arrives here again.
10186        let Some(pr) = self
10187            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10188            .await?
10189        else {
10190            return Ok(());
10191        };
10192        let message = pr.commit_message();
10193
10194        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10195        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10196            return Ok(());
10197        }
10198        let outcome = match mode {
10199            MergeMode::None => MergeOutcome {
10200                mode,
10201                ok: true,
10202                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10203                empty: false,
10204            },
10205            MergeMode::Pr | MergeMode::Local
10206                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10207            {
10208                MergeOutcome {
10209                    mode,
10210                    ok: false,
10211                    detail: empty_candidate_detail(&self.state, &base),
10212                    empty: true,
10213                }
10214            }
10215            MergeMode::Local => {
10216                let on = git::current_branch(&repo).await?;
10217                if on.as_deref() != Some(base.as_str()) {
10218                    MergeOutcome {
10219                        mode,
10220                        ok: false,
10221                        detail: format!(
10222                            "{} has {} checked out, not the base branch {base}",
10223                            repo.display(),
10224                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10225                        ),
10226                        empty: false,
10227                    }
10228                } else if !git::is_clean(&repo).await? {
10229                    MergeOutcome {
10230                        mode,
10231                        ok: false,
10232                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10233                        empty: false,
10234                    }
10235                } else {
10236                    let out = match style {
10237                        MergeStyle::Merge => {
10238                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10239                        }
10240                        MergeStyle::Squash => {
10241                            git::merge_squash(&repo, &winner.branch, &message).await?
10242                        }
10243                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10244                    };
10245                    MergeOutcome {
10246                        mode,
10247                        ok: out.ok(),
10248                        detail: if out.ok() { out.stdout } else { out.stderr },
10249                        empty: false,
10250                    }
10251                }
10252            }
10253            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10254                self.state.pr_publication_pending = true;
10255                self.state.save()?;
10256                let out =
10257                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10258                self.state.pr_publication_pending = out.is_err();
10259                MergeOutcome {
10260                    mode,
10261                    ok: out.is_ok(),
10262                    detail: match out {
10263                        Ok(url) => url,
10264                        Err(e) => format!("{e:#}"),
10265                    },
10266                    empty: false,
10267                }
10268            }
10269            MergeMode::Pr => {
10270                let remote = self.state.config.merge.remote.clone();
10271                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10272                let pushed = if self.state.foreign_checkout.is_some() {
10273                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10274                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10275                } else {
10276                    git::push(&winner.worktree, &remote, &winner.branch).await?
10277                };
10278                if !pushed.ok() {
10279                    MergeOutcome {
10280                        mode,
10281                        ok: false,
10282                        detail: pushed.stderr,
10283                        empty: false,
10284                    }
10285                } else {
10286                    if self.state.foreign_checkout.is_some() {
10287                        self.state.pr_pushed_head = Some(delivery_head.clone());
10288                    }
10289                    // A retry or resume of a run whose branch already has an
10290                    // open pull request adopts it rather than failing on a
10291                    // duplicate. Only this winner branch into this base:
10292                    // `branch_for` derives the name from the run id, so a
10293                    // different run's pull request never matches.
10294                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10295                    let out = match pr_merge_plan(found) {
10296                        PrPlan::Create => {
10297                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10298                                .await
10299                        }
10300                        PrPlan::Adopt { url, title } => {
10301                            self.state
10302                                .event("merge", format!("Pr: adopted open pull request {url}"));
10303                            if self.state.explicit_github_text_selection() {
10304                                // An explicit publication selection applies the prepared
10305                                // payload; acceptance alone is not publication proof.
10306                                land::set_pr_text_verbatim(
10307                                    &winner.worktree,
10308                                    &url,
10309                                    &pr.title,
10310                                    &pr.body,
10311                                )
10312                                .await
10313                                .map(|()| url)
10314                            } else {
10315                                if title != pr.title
10316                                    && (!is_review_run(&self.state)
10317                                        || leaked
10318                                            .as_deref()
10319                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10320                                    && let Err(e) =
10321                                        if self.state.github_text.as_ref().is_some_and(|g| {
10322                                            g.resolved
10323                                                && g.title
10324                                                && g.choice == Some(GithubTextChoice::Original)
10325                                        }) {
10326                                            // The owner chose to post this title unmodified.
10327                                            land::set_pr_title_verbatim(
10328                                                &winner.worktree,
10329                                                &url,
10330                                                &pr.title,
10331                                            )
10332                                            .await
10333                                        } else {
10334                                            land::set_pr_title(
10335                                                &mut self.state,
10336                                                &winner.worktree,
10337                                                &url,
10338                                                &pr.title,
10339                                            )
10340                                            .await
10341                                        }
10342                                {
10343                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10344                                    self.state
10345                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10346                                }
10347                                Ok(url)
10348                            }
10349                        }
10350                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10351                    };
10352                    match out {
10353                        Ok(url) => MergeOutcome {
10354                            mode,
10355                            ok: true,
10356                            detail: url,
10357                            empty: false,
10358                        },
10359                        Err(e) => MergeOutcome {
10360                            mode,
10361                            ok: false,
10362                            detail: e.to_string(),
10363                            empty: false,
10364                        },
10365                    }
10366                }
10367            }
10368        };
10369
10370        self.state.status = match (mode, outcome.ok) {
10371            (MergeMode::None, _) => RunStatus::Ready,
10372            (_, true) if outcome.empty => RunStatus::Ready,
10373            (MergeMode::Pr, true) => RunStatus::Ready,
10374            (_, true) => RunStatus::Merged,
10375            (_, false) => RunStatus::Blocked,
10376        };
10377        self.state.event(
10378            "merge",
10379            format!(
10380                "{:?}: {}",
10381                mode,
10382                outcome.detail.lines().next().unwrap_or("")
10383            ),
10384        );
10385        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10386            self.state.record_github_text_publication(&outcome.detail);
10387        }
10388        self.state.merge = Some(outcome);
10389        self.state.save()?;
10390
10391        // The PR is open and the run would historically stop here, leaving the
10392        // operator to watch checks, feed review comments back to a fixer, and
10393        // merge. That was done by hand six times in one session before this
10394        // existed. Opt-in, because merging is the one irreversible thing magi
10395        // can do to a repository.
10396        if self.state.config.graph.land
10397            && mode == MergeMode::Pr
10398            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10399        {
10400            self.run_land().await?;
10401        }
10402        // `run_land` may have left `status` at `Landing` - still waiting on
10403        // CI or the owner's approval, not actually settled - so this has to
10404        // read whatever `status` ended up as here, not the `Merged` this
10405        // function set a few lines up.
10406        self.settle_questions();
10407        Ok(())
10408    }
10409
10410    /// Enter `land`.
10411    ///
10412    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10413    /// a resumed run's re-entry. `land::land` itself is what serialises the
10414    /// two git-mutating moments inside the loop — the rebase push and
10415    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10416    /// to hold a lock across the whole call, and doing so would serialise
10417    /// this run's CI wait against a *different* run's land-approval resume
10418    /// in the same repository, which is exactly the "must not wait on
10419    /// another task" property the daemon's slot-freeing exists to give.
10420    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10421        Box::pin(self.run_land_inner())
10422    }
10423
10424    async fn run_land_inner(&mut self) -> Result<()> {
10425        crate::pr_head::ensure_owner(&self.state)?;
10426        let url = self
10427            .state
10428            .pr
10429            .as_ref()
10430            .map(|pr| pr.url.clone())
10431            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10432            .unwrap_or_default();
10433        let url = url.lines().next().unwrap_or("").trim().to_owned();
10434        if !url.starts_with("http") {
10435            return Ok(());
10436        }
10437        // A land failure is not a lost run: the work is on a branch and the
10438        // pull request is open, which is exactly where a human takes over.
10439        loop {
10440            match land::land(&mut self.state, &url).await {
10441                Ok(_)
10442                    if self
10443                        .state
10444                        .merge_repairs
10445                        .last()
10446                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10447                {
10448                    if self.repair_merge_review().await? {
10449                        continue;
10450                    }
10451                }
10452                Ok(_) if self.state.resource_block.is_some() => {
10453                    return self.stop_for_resource();
10454                }
10455                Ok(pr) if self.state.parked => {
10456                    // `land` already saved the parked marker; nothing here
10457                    // overrides `status` back to a terminal value while an
10458                    // approval is still outstanding.
10459                    let _ = pr;
10460                }
10461                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10462                    self.state.status = RunStatus::Superseded;
10463                    self.state.save()?;
10464                }
10465                Ok(pr) => {
10466                    self.state.status = match pr.state {
10467                        land::PrLifecycle::Merged => RunStatus::Merged,
10468                        _ => RunStatus::Blocked,
10469                    };
10470                    // Downstream of a confirmed merge only - see
10471                    // `bump::should_release_bump`'s own doc for why this one
10472                    // check covers all three of `land`'s success paths.
10473                    // Best-effort: the run already landed, so a failure here
10474                    // (the decision call, `gh`, `cargo`) is recorded and never
10475                    // turns a landed run into a failed one.
10476                    if bump::should_release_bump(self.state.status)
10477                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10478                    {
10479                        // The event is the run's own record. Not-eligible cases
10480                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10481                        // `Err` is a bump that was tried and failed:
10482                        // `after_merge` itself raises the operator notice for
10483                        // that, whether or not a release PR exists yet.
10484                        self.state
10485                            .event("bump", format!("release bump skipped: {e:#}"));
10486                    }
10487                    // Independent of the bump, and best-effort in the same way:
10488                    // findings the merge left open become follow-up tasks.
10489                    if self.state.status == RunStatus::Merged {
10490                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10491                    }
10492                    self.state.save()?;
10493                }
10494                Err(e) => {
10495                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10496                        return Err(e);
10497                    }
10498                    self.state.status = RunStatus::Blocked;
10499                    self.state.event("land", format!("gave up: {e}"));
10500                    self.state.save()?;
10501                }
10502            }
10503            break;
10504        }
10505        Ok(())
10506    }
10507
10508    /// One repair cycle stays under the existing driver/task claim. An
10509    /// interrupted fixer is rolled back and held rather than run twice.
10510    async fn repair_merge_review(&mut self) -> Result<bool> {
10511        use crate::run::MergeRepairPhase as Phase;
10512        crate::pr_head::ensure_owner(&self.state)?;
10513        let i = self.state.merge_repairs.len() - 1;
10514        let request = self.state.merge_repairs[i].clone();
10515        if request.phase == Phase::Fixing {
10516            let restored = match self.state.winner().cloned() {
10517                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10518                None => Err(anyhow::anyhow!("repair has no winning branch")),
10519            };
10520            let why = match restored {
10521                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10522                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10523                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10524            };
10525            self.hold_merge_repair(i, why)?;
10526            return Ok(false);
10527        }
10528        // A completed repair gate is a publication checkpoint. On reentry,
10529        // reject external changes before the ordinary gate path can replace
10530        // that evidence by verifying a new head. Requested repairs still
10531        // start their own review generation below.
10532        if request.phase == Phase::Reviewing && self.state.gate_ran {
10533            let winner = self
10534                .state
10535                .winner()
10536                .context("repair has no winning branch")?;
10537            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10538            if self.state.gate_head.as_deref() != Some(head.as_str())
10539                || !git::is_clean(&winner.worktree).await?
10540            {
10541                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())?;
10542                return Ok(false);
10543            }
10544        }
10545        let failure = if i >= self.state.config.graph.land_rounds
10546            || self.state.config.graph.review_rounds == 0
10547        {
10548            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10549        } else {
10550            None
10551        };
10552        if let Some(why) = failure {
10553            self.hold_merge_repair(i, why)?;
10554            return Ok(false);
10555        }
10556        if request.phase == Phase::Requested {
10557            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10558                Ok(pr) => pr,
10559                Err(e) => {
10560                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10561                    return Ok(false);
10562                }
10563            };
10564            self.state.merge_repairs[i].phase = Phase::Fixing;
10565            self.state.land_approval = None;
10566            self.state.land_armed_head = None;
10567            self.state.save()?;
10568            // Serialize the exact records, including finding ids/details,
10569            // reconsideration reasons, final votes and verification output.
10570            let evidence = serde_json::to_string_pretty(&request)?;
10571            let reason = format!(
10572                "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}"
10573            );
10574            let budget = self.state.config.graph.land_rounds;
10575            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10576            match result {
10577                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10578                Ok(land::Fixed::Deferred) => {
10579                    // An unavailable fixer did not spend this repair request.
10580                    // Restore partial fallback work before retrying it, as for
10581                    // an interrupted repair, without closing the request.
10582                    let worktree = self
10583                        .state
10584                        .winner()
10585                        .context("repair has no winning branch")?
10586                        .worktree
10587                        .clone();
10588                    self.graft_restore(&worktree, &request.head).await?;
10589                    self.state.merge_repairs[i].phase = Phase::Requested;
10590                    self.stop_for_resource()?;
10591                    return Ok(false);
10592                }
10593                Ok(land::Fixed::Failed(why)) => {
10594                    self.hold_merge_repair(
10595                        i,
10596                        format!(
10597                            "repair failed: {why}; inspect the branch and run an explicit review"
10598                        ),
10599                    )?;
10600                    return Ok(false);
10601                }
10602                Err(e) => {
10603                    self.hold_merge_repair(
10604                        i,
10605                        format!(
10606                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10607                        ),
10608                    )?;
10609                    return Ok(false);
10610                }
10611            }
10612            // Even no change gets a real new reviewer wave. The previous
10613            // evidence remains in the request; a former clean/concluded round
10614            // cannot short-circuit the new review or gate.
10615            self.begin_merge_repair_review(i)?;
10616        }
10617        self.review_loop().await?;
10618        self.gate().await?;
10619        if self.resource_halt()? || self.state.parked {
10620            return Ok(false);
10621        }
10622        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10623            != Some(RunStatus::Gating)
10624            || !self.state.gate_allows_progress()
10625        {
10626            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10627            return Ok(false);
10628        }
10629        // Review and gate may have added commits after the initial repair.
10630        // Publish exactly their final head to the existing PR, with a lease.
10631        let winner = self
10632            .state
10633            .winner()
10634            .cloned()
10635            .context("repair has no winning branch")?;
10636        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10637        if self.state.gate_head.as_deref() != Some(after.as_str())
10638            || !git::is_clean(&winner.worktree).await?
10639        {
10640            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())?;
10641            return Ok(false);
10642        }
10643        let expected = self
10644            .state
10645            .pr_pushed_head
10646            .as_deref()
10647            .unwrap_or(&request.head)
10648            .to_owned();
10649        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10650        // Push the checked commit itself: a local ref moving after the check
10651        // must not change which commit the forge receives.
10652        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10653            return Ok(false);
10654        }
10655        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10656        let refspec = format!("{after}:refs/heads/{public}");
10657        let push = git::git_raw(
10658            &winner.worktree,
10659            &["push", &lease, &self.state.config.merge.remote, &refspec],
10660        )
10661        .await;
10662        match push {
10663            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10664            Ok(out) => {
10665                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10666                return Ok(false);
10667            }
10668            Err(e) => {
10669                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10670                return Ok(false);
10671            }
10672        }
10673        self.state.merge_repairs[i].phase = Phase::Complete;
10674        self.state.status = RunStatus::Landing;
10675        self.state.event(
10676            "repair",
10677            "new review and gate completed; fresh owner merge decision required",
10678        );
10679        self.state.save()?;
10680        Ok(true)
10681    }
10682
10683    fn merge_repair_artifacts(&self) -> PathBuf {
10684        let artifacts = agent::artifacts_dir(&self.state.dir());
10685        match self
10686            .state
10687            .merge_repairs
10688            .last()
10689            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10690        {
10691            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10692            None => artifacts,
10693        }
10694    }
10695
10696    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10697        if let Some(e2e) = self.state.head_e2e.take() {
10698            self.state
10699                .verification_history
10700                .push(crate::run::VerificationEvidence {
10701                    superseded_by: None,
10702                    archived_at: Some(Timestamp::now()),
10703                    fixes_spent: Some(self.state.gate_fixes.len()),
10704                    gate_head: None,
10705                    gate_ran: false,
10706                    gate: Vec::new(),
10707                    e2e: Some(e2e),
10708                });
10709        }
10710        self.state.reviews.clear();
10711        self.state.gate.clear();
10712        self.state.gate_ran = false;
10713        self.state.gate_head = None;
10714        self.state.gate_fixes.clear();
10715        self.state.gate_repair_e2e = None;
10716        self.state.pre_gate.clear();
10717        self.state.pre_gate_commit = None;
10718        self.state.contested_handoff = None;
10719        self.state.land_reruns = None;
10720        self.state.land_approval = None;
10721        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10722        self.state.status = RunStatus::Reviewing;
10723        self.state.save()
10724    }
10725
10726    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10727        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10728        self.state.merge_repairs[index].failure = Some(why.clone());
10729        self.state.status = RunStatus::Blocked;
10730        self.state.event("repair", why);
10731        self.state.save()
10732    }
10733
10734    // -------------------------------------------------------------- helpers
10735
10736    /// Fetch or create a seat, keeping its conversation across nodes.
10737    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10738        if let Some(existing) = self.state.seats.get(key)
10739            && existing.agent == agent
10740        {
10741            return existing.clone();
10742        }
10743        // A seat that changes agent mints its session id from the agent too,
10744        // like a handover: the old agent's uuid is already taken by the CLI.
10745        let fresh = if self.state.seats.contains_key(key) {
10746            handover_seat(key, agent, self.state.next_seat_seed())
10747        } else {
10748            SeatState::new(key, agent, self.state.seed)
10749        };
10750        self.state.seats.insert(key.to_owned(), fresh.clone());
10751        fresh
10752    }
10753
10754    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10755    /// seat to another roster agent, in which case that agent. Nodes that
10756    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10757    /// reconsideration) must keep talking to whoever answered it, not slip
10758    /// back to the agent that failed it.
10759    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10760        match self.state.seats.get(key) {
10761            Some(s) if s.agent != spec.id => {
10762                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10763            }
10764            _ => spec,
10765        }
10766    }
10767
10768    /// A candidate rendered for judging, with the leak policy applied.
10769    fn view(&self, c: &Candidate) -> CandidateView {
10770        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10771            .unwrap_or_default();
10772        let (patch, _) = blind::sanitize_patch(
10773            &format!("candidate {} patch", c.label),
10774            &raw,
10775            &self.state.config.blind,
10776        );
10777        CandidateView {
10778            label: c.label,
10779            branch: c.branch.clone(),
10780            summary: c.summary.clone(),
10781            stat: c.stat.clone(),
10782            patch,
10783        }
10784    }
10785
10786    /// The full candidate set as prompt text, for seats with no live session.
10787    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10788        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10789        prompt::judge(
10790            "(see above)",
10791            &views,
10792            self.roles.judges.len(),
10793            base_short,
10794            "en",
10795        )
10796    }
10797
10798    /// The final-vote prompt with everything a seat that has no session of its
10799    /// own needs: the candidates, the seat's own ranking and reasons, and the
10800    /// anonymised deliberation it took part in (only when there was one, so a
10801    /// handed-over seat never sees more than the seat it replaces did). The
10802    /// `Final vote` heading stays first.
10803    fn vote_prompt_full(
10804        &self,
10805        j: usize,
10806        labels: &[char],
10807        language: &str,
10808        candidates: &[Candidate],
10809        base_short: &str,
10810    ) -> String {
10811        let mut text = format!(
10812            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10813            prompt::final_vote(labels, language),
10814            self.state.instruction,
10815            self.candidate_block(candidates, base_short)
10816        );
10817        if let Some(own) = self
10818            .state
10819            .judgements
10820            .get(j)
10821            .filter(|r| !r.ranking.is_empty())
10822        {
10823            let reasons = own
10824                .reasons
10825                .iter()
10826                .map(|(k, v)| format!("- {k}: {v}"))
10827                .collect::<Vec<_>>()
10828                .join("\n");
10829            text.push_str(&format!(
10830                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10831                own.ranking.iter().collect::<String>(),
10832                if reasons.is_empty() {
10833                    ""
10834                } else {
10835                    ", because:\n"
10836                }
10837            ));
10838        }
10839        if !self.state.deliberation.is_empty() {
10840            text.push_str("\n# What was argued before this vote\n");
10841            for t in self.transcript(&[], j) {
10842                text.push_str(&format!(
10843                    "\n## {}{}\n\n{}\n",
10844                    t.who,
10845                    if t.is_self { " (you)" } else { "" },
10846                    t.body.trim()
10847                ));
10848            }
10849        }
10850        text
10851    }
10852
10853    /// Anonymised transcript for judge `self_idx`.
10854    ///
10855    /// The initial rankings are always the opening statements. Seeding them
10856    /// only when no turn had been taken yet meant every judge after the first
10857    /// argued against a single voice instead of against the actual split — the
10858    /// disagreement is the information, so it is always on the table.
10859    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10860        let mut turns = Vec::new();
10861        for j in &self.state.judgements {
10862            if j.ranking.is_empty() {
10863                continue;
10864            }
10865            let reasons = j
10866                .reasons
10867                .iter()
10868                .map(|(k, v)| format!("- {k}: {v}"))
10869                .collect::<Vec<_>>()
10870                .join("\n");
10871            turns.push(Turn {
10872                who: format!("Judge {} (opening ranking)", j.judge),
10873                is_self: j.judge == self_idx + 1,
10874                body: format!(
10875                    "Ranked {}{}{reasons}",
10876                    j.ranking.iter().collect::<String>(),
10877                    if reasons.is_empty() {
10878                        ""
10879                    } else {
10880                        ", because:\n"
10881                    }
10882                ),
10883            });
10884        }
10885        for t in self
10886            .state
10887            .deliberation
10888            .iter()
10889            .flat_map(|r| r.turns.iter())
10890            .chain(current)
10891        {
10892            turns.push(Turn {
10893                who: format!("Judge {}", t.judge),
10894                is_self: t.judge == self_idx + 1,
10895                body: t.body.clone(),
10896            });
10897        }
10898        turns
10899    }
10900}
10901
10902/// Does this seat still hold the context a follow-up prompt would rely on?
10903fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10904    agent::has_session(spec.kind, seat, sessions)
10905}
10906
10907/// The next entry in `roster` after `start`, never wrapping back to the
10908/// front, whose id is not in `tried` yet.
10909///
10910/// Starts one past `start` rather than at the front of `roster`: `start` is
10911/// the seat's own original position, and a seat whose candidate slot already
10912/// sits on the roster's second entry must fall through to the third next, not
10913/// restart at the first — which is very likely a different candidate's own
10914/// agent already. Never wraps back past `start`, for the same reason: an
10915/// entry earlier in the roster than the seat's own position is almost
10916/// certainly some *other* candidate slot's own agent, and once the tail of
10917/// the roster is exhausted there are no more untried agents for *this* seat
10918/// to fall through to — the caller's fallback chain ends there, exactly as
10919/// "no further untried agents remain in the list for that seat" asks for.
10920///
10921/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10922/// the same id twice (an operator's `roles.implementers` typo, or a
10923/// `[[agents]]` list reused across roles) must not let
10924/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10925/// over `roster` either finds an untried id or runs out, so this always
10926/// terminates regardless of duplicates.
10927fn next_untried_in_roster<'a>(
10928    roster: &'a [AgentSpec],
10929    start: usize,
10930    tried: &BTreeSet<String>,
10931) -> Option<&'a AgentSpec> {
10932    roster
10933        .get(start + 1..)?
10934        .iter()
10935        .find(|s| !tried.contains(&s.id))
10936}
10937
10938/// The successor for a seat, shared by all four seat kinds (implement, judge,
10939/// review, advise). `others` holds the ids that *currently* occupy the other
10940/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10941/// sees them), so roster entries beyond the seat count act as spares: a failed
10942/// seat goes to an agent no other seat holds whenever the roster permits.
10943///
10944/// `carried` is `Some` only for the review loop's carried failure history.
10945/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10946/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10947/// whole roster: untried and not another seat's occupant; (3) the plain walk
10948/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10949/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10950/// a better outcome than an empty seat, and it keeps the answer to "is there
10951/// a successor at all" exactly what it was before occupants were considered,
10952/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10953/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10954/// carried failure is a cheaper bet than doubling an agent on the panel, and
10955/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10956/// the same round are handled one at a time, so a seat later in the batch
10957/// sees an earlier one's new occupant but not yet its own freed agent.
10958fn pick_successor<'a>(
10959    roster: &'a [AgentSpec],
10960    start: usize,
10961    tried: &BTreeSet<String>,
10962    carried: Option<&BTreeSet<String>>,
10963    others: &BTreeSet<String>,
10964) -> Option<&'a AgentSpec> {
10965    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10966    roster
10967        .get(start + 1..)
10968        .and_then(|tail| {
10969            tail.iter()
10970                .filter(free)
10971                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10972        })
10973        .or_else(|| {
10974            carried
10975                .is_some()
10976                .then(|| roster.iter().find(free))
10977                .flatten()
10978        })
10979        .or_else(|| match carried {
10980            Some(c) => next_for_seat(roster, start, tried, c),
10981            None => next_untried_in_roster(roster, start, tried),
10982        })
10983}
10984
10985/// The next agent for a seat that carries its failure history across rounds
10986/// (the review loop). `round_tried` is this round's own bound and starts
10987/// empty every round; `carried_failed` only decides priority.
10988///
10989/// First: an id walking forward from `start`, never wrapping, that is neither
10990/// tried this round nor failed in an earlier one. Only when that is exhausted
10991/// does it rescue: the first roster id (in roster order, so this one *does*
10992/// look before `start`) not yet tried this round, which is by then a carried
10993/// failure. Each id is rescued at most once per round, so it cannot loop.
10994fn next_for_seat<'a>(
10995    roster: &'a [AgentSpec],
10996    start: usize,
10997    round_tried: &BTreeSet<String>,
10998    carried_failed: &BTreeSet<String>,
10999) -> Option<&'a AgentSpec> {
11000    roster
11001        .get(start + 1..)?
11002        .iter()
11003        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11004        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11005}
11006
11007/// Where a reviewer seat starts a round: the agent that last answered it when
11008/// it is still on the roster and not marked failed, else the spec's own agent
11009/// unless it failed, else the next roster agent that has not failed, else the
11010/// spec's own agent again (the whole roster failed). Ids no longer on the
11011/// roster are ignored. An empty roster has no handover, so the spec stands.
11012fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11013    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11014        return spec;
11015    };
11016    let ok = |id: &str| !h.failed.contains(id);
11017    if let Some(last) = h.last_ok.as_deref()
11018        && ok(last)
11019        && let Some(s) = roster.iter().find(|s| s.id == last)
11020    {
11021        return s.clone();
11022    }
11023    if ok(&spec.id) {
11024        return spec;
11025    }
11026    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11027    roster
11028        .get(from + 1..)
11029        .into_iter()
11030        .flatten()
11031        .chain(roster.iter())
11032        .find(|s| ok(&s.id))
11033        .cloned()
11034        .unwrap_or(spec)
11035}
11036
11037/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11038/// seed so a CLI that mints its session id up front (`--session-id`) never
11039/// reuses the uuid the previous agent already opened under the same seat key.
11040pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11041    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11042}
11043
11044/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11045/// so the classifier below and the code that builds the message cannot drift.
11046const TIMED_OUT: &str = "timed out";
11047
11048impl FailClass {
11049    /// `None` for an answer; otherwise how the turn failed.
11050    fn of(out: &AgentOutcome) -> Option<Self> {
11051        match out {
11052            AgentOutcome::Ok(_) => None,
11053            AgentOutcome::Quota(_) => Some(Self::Quota),
11054            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11055            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11056            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11057            // Not a failure of the agent. Callers check for it first; `None`
11058            // here means "no class to hand over on".
11059            AgentOutcome::ResourceBlocked(_) => None,
11060        }
11061    }
11062
11063    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11064    fn stem_word(&self) -> &'static str {
11065        match self {
11066            Self::Quota => "quota",
11067            _ => "handover",
11068        }
11069    }
11070}
11071
11072/// The message's first line with its variable parts removed — digit runs and
11073/// path-like tokens — so "exit code 2" and "exit code 7" read
11074/// as one kind of failure.
11075fn failure_signature(msg: &str) -> String {
11076    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11077    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11078    // the historical machine key while the process diagnosis uses readable prose.
11079    if let Some(code) = line
11080        .strip_prefix("process exited with no usable output (exit code ")
11081        .and_then(|s| s.strip_suffix(')'))
11082        .and_then(|s| s.parse::<i32>().ok())
11083    {
11084        line = format!("exited with some({code}) and no usable output");
11085    } else if matches!(
11086        line.as_str(),
11087        "process exited with no usable output (no exit code reported)"
11088            | "process exited with no usable output (exit code unavailable)"
11089    ) {
11090        line = "exited with none and no usable output".to_owned();
11091    }
11092    let mut out = Vec::new();
11093    for word in line.split_whitespace() {
11094        if word.contains('/') || word.contains('\\') {
11095            out.push("<path>".to_owned());
11096            continue;
11097        }
11098        let mut w = String::new();
11099        let mut in_digits = false;
11100        for c in word.chars() {
11101            if c.is_ascii_digit() {
11102                if !in_digits {
11103                    w.push('#');
11104                }
11105                in_digits = true;
11106            } else {
11107                in_digits = false;
11108                w.push(c);
11109            }
11110        }
11111        out.push(w);
11112    }
11113    out.join(" ").chars().take(120).collect()
11114}
11115
11116/// Whether a seat that just failed with `cur` may go to the next roster agent.
11117/// A quota or a timeout always may. Any other failure may not when the agent
11118/// before it failed the same way: an error the prompt causes would otherwise
11119/// walk the whole roster. `prev` is the class of the immediately preceding
11120/// agent's failure, so a quota or timeout in between breaks the run of
11121/// identical failures by itself.
11122fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11123    match cur {
11124        FailClass::Quota | FailClass::Timeout => true,
11125        FailClass::Other(_) => prev != Some(cur),
11126    }
11127}
11128
11129/// A short human reason for a failed outcome, for the handover record.
11130fn fail_reason(out: &AgentOutcome) -> String {
11131    match out {
11132        AgentOutcome::Ok(_) => String::new(),
11133        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11134        AgentOutcome::Dropped(o) => format!(
11135            "the CLI dropped the stream ({})",
11136            o.dropped
11137                .as_ref()
11138                .map(|d| d.why.as_str())
11139                .unwrap_or("it ended without delivering its answer")
11140        ),
11141        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11142            e.lines().next().unwrap_or("").chars().take(160).collect()
11143        }
11144    }
11145}
11146
11147/// Note one handover in the run: the structured record and, in the timeline,
11148/// the sentence a person reads. A quota keeps the wording it always had.
11149pub(crate) fn record_handover(
11150    state: &mut RunState,
11151    node: &str,
11152    seat: &str,
11153    from: &str,
11154    to: &str,
11155    class: &FailClass,
11156    reason: &str,
11157) {
11158    let message = if *class == FailClass::Quota {
11159        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11160    } else {
11161        format!("{seat}: handed over {from} -> {to} ({reason})")
11162    };
11163    state.event(node, message);
11164    state.handovers.push(Handover {
11165        at: Timestamp::now(),
11166        node: node.to_owned(),
11167        seat: seat.to_owned(),
11168        from: from.to_owned(),
11169        to: to.to_owned(),
11170        reason: reason.to_owned(),
11171    });
11172}
11173
11174/// Did this reply report running a command whose own CLI never confirmed an
11175/// exit status?
11176///
11177/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11178/// command *finished* (see that type's own doc), so this can only be `true`
11179/// for a command whose completion event carried no readable exit code — not
11180/// for one that simply is not mentioned at all. That is the one signal this
11181/// crate can read, from the same record `state.jobs` renders, about a reply
11182/// standing next to work its own CLI cannot vouch for finishing; it is
11183/// deliberately not a check on the exit code's *value* (a fixer legitimately
11184/// runs a command that fails mid-iteration before it succeeds) and not a
11185/// guess at a command still running in the background (which emits no event
11186/// at all, and so leaves no evidence here to find).
11187fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11188    commands.iter().any(|c| c.exit_code.is_none())
11189}
11190
11191/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11192/// adoption guard.
11193#[derive(Debug, Clone, PartialEq, Eq)]
11194enum NoopClaimVerdict {
11195    /// Reply did not open with `NO CHANGE NEEDED:`.
11196    Absent,
11197    /// Structured evidence passed schema, CLI command, and repository checks.
11198    Accepted,
11199    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11200    /// concrete reason.
11201    Rejected(String),
11202}
11203
11204fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11205    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11206    cmd.description.trim() == check.method.trim()
11207}
11208
11209/// Checks cited by `requirements` plus the final check, deduplicated in order.
11210fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11211    let mut out = report.cited_checks();
11212    if let Some(last) = report.checks.last()
11213        && !out
11214            .iter()
11215            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11216    {
11217        out.push(last);
11218    }
11219    out
11220}
11221
11222/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11223/// when the backend reported commands. Empty `commands` is allowed because not
11224/// every backend emits structured command events.
11225fn check_command_evidence(
11226    report: &verdict::VerifiedNoopReport,
11227    commands: &[agent::CommandEvidence],
11228) -> std::result::Result<(), String> {
11229    if commands.is_empty() {
11230        return Ok(());
11231    }
11232    for check in checks_to_cross_verify(report) {
11233        let matching: Vec<&agent::CommandEvidence> = commands
11234            .iter()
11235            .filter(|cmd| command_matches_check(cmd, check))
11236            .collect();
11237        match check.kind {
11238            verdict::NoopEvidenceKind::Command
11239            | verdict::NoopEvidenceKind::Test
11240            | verdict::NoopEvidenceKind::Path => {
11241                let Some(last_cmd) = matching.last() else {
11242                    return Err(format!(
11243                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11244                         but no matching command was recorded by the CLI",
11245                        check.id.trim(),
11246                        check.kind,
11247                        check.target.trim()
11248                    ));
11249                };
11250                if last_cmd.exit_code != Some(0) {
11251                    return Err(format!(
11252                        "contradictory command evidence: check `{}` claims `{}` passed, \
11253                         but its last recorded CLI command (`{}`) exited with {}",
11254                        check.id.trim(),
11255                        check.target.trim(),
11256                        last_cmd.description.trim(),
11257                        crate::notices::exit_status(last_cmd.exit_code)
11258                    ));
11259                }
11260                if check.kind == verdict::NoopEvidenceKind::Test
11261                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11262                {
11263                    return Err(format!(
11264                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11265                         but its last recorded CLI output reports failure or no passing tests",
11266                        check.id.trim(),
11267                        check.target.trim()
11268                    ));
11269                }
11270            }
11271            verdict::NoopEvidenceKind::Commit => {
11272                if let Some(last_cmd) = matching.last()
11273                    && last_cmd.exit_code != Some(0)
11274                {
11275                    return Err(format!(
11276                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11277                         but its last recorded CLI command (`{}`) exited with {}",
11278                        check.id.trim(),
11279                        check.target.trim(),
11280                        last_cmd.description.trim(),
11281                        crate::notices::exit_status(last_cmd.exit_code)
11282                    ));
11283                }
11284            }
11285        }
11286    }
11287    Ok(())
11288}
11289
11290/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11291/// exit, confirmed commands, strict structured JSON validation, and
11292/// `CommandEvidence` consistency.
11293fn evaluate_noop_claim(
11294    usable: bool,
11295    commands: &[agent::CommandEvidence],
11296    text: &str,
11297) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11298    if !text
11299        .trim_start()
11300        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11301    {
11302        return Ok(None);
11303    }
11304    if !usable {
11305        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11306    }
11307    if has_unconfirmed_command(commands) {
11308        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11309    }
11310    let Some(parsed) = verdict::parse_verified_noop(text) else {
11311        return Ok(None);
11312    };
11313    let report = parsed?;
11314    check_command_evidence(&report, commands)?;
11315    Ok(Some(report))
11316}
11317
11318/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11319/// structured no-op report against the candidate's real Git history and
11320/// worktree. Existence alone never satisfies a requirement (the report still
11321/// had to carry concrete passing checks), while a missing commit/path or a
11322/// commit not on `base_commit` disqualifies the claim.
11323async fn verify_noop_repo_evidence(
11324    report: &verdict::VerifiedNoopReport,
11325    worktree: &Path,
11326    base_commit: &str,
11327) -> std::result::Result<(), String> {
11328    let wt_canon = std::fs::canonicalize(worktree).ok();
11329    for check in checks_to_cross_verify(report) {
11330        match check.kind {
11331            verdict::NoopEvidenceKind::Commit => {
11332                let target = check.target.trim();
11333                let Some(sha) = git::commit_of(worktree, target).await else {
11334                    return Err(format!(
11335                        "check `{}` cites commit `{target}`, which does not exist in git history",
11336                        check.id.trim()
11337                    ));
11338                };
11339                if !git::is_ancestor(worktree, &sha, base_commit).await {
11340                    return Err(format!(
11341                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11342                        check.id.trim(),
11343                        short(base_commit)
11344                    ));
11345                }
11346            }
11347            verdict::NoopEvidenceKind::Path => {
11348                let target = check.target.trim();
11349                let rel = verdict::strip_path_locator(target);
11350                let full = worktree.join(rel);
11351                if !full.exists() {
11352                    return Err(format!(
11353                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11354                        check.id.trim()
11355                    ));
11356                }
11357                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11358                    && !path_canon.starts_with(wt_canon)
11359                {
11360                    return Err(format!(
11361                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11362                        check.id.trim()
11363                    ));
11364                }
11365            }
11366            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11367        }
11368    }
11369    Ok(())
11370}
11371
11372/// Full adoption guard for an implementer reply, including real Git history and
11373/// worktree path verification.
11374async fn verified_noop_claim_in_worktree(
11375    usable: bool,
11376    commands: &[agent::CommandEvidence],
11377    text: &str,
11378    worktree: &Path,
11379    base_commit: &str,
11380) -> NoopClaimVerdict {
11381    let report = match evaluate_noop_claim(usable, commands, text) {
11382        Ok(Some(r)) => r,
11383        Ok(None) => return NoopClaimVerdict::Absent,
11384        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11385    };
11386    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11387        return NoopClaimVerdict::Rejected(reason);
11388    }
11389    NoopClaimVerdict::Accepted
11390}
11391
11392/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11393/// trusted as a verified no-op — the adoption guard's pure text-and-command
11394/// half (repository history/path verification runs in
11395/// [`verified_noop_claim_in_worktree`]).
11396///
11397/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11398/// timed out): a marker only earns the benefit of the doubt from a turn the
11399/// CLI itself vouches for finishing properly, the same house style
11400/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11401/// *fix* report to for `commands`. A candidate that timed out, exited
11402/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11403/// or failed structured validation returns `None`.
11404#[cfg(test)]
11405fn verified_noop_claim(
11406    usable: bool,
11407    commands: &[agent::CommandEvidence],
11408    text: &str,
11409) -> Option<String> {
11410    evaluate_noop_claim(usable, commands, text)
11411        .ok()
11412        .flatten()
11413        .map(|report| report.summary_text())
11414}
11415
11416fn short(commit: &str) -> String {
11417    commit.chars().take(7).collect()
11418}
11419
11420fn make_executable(path: &Path) -> Result<()> {
11421    #[cfg(unix)]
11422    {
11423        use std::os::unix::fs::PermissionsExt as _;
11424        let mut perms = std::fs::metadata(path)?.permissions();
11425        perms.set_mode(0o755);
11426        std::fs::set_permissions(path, perms)?;
11427    }
11428    #[cfg(not(unix))]
11429    {
11430        let _ = path;
11431    }
11432    Ok(())
11433}
11434
11435/// What every seat in one batch shares: where the answers are attributed, the
11436/// prompt overlay they inherit, and the build cache they are told to use.
11437///
11438/// A struct rather than four more parameters: `wave` also needs the run's
11439/// state (to record who is answering right now) and the attempt number, and
11440/// eight positional arguments is both unreadable and a clippy error.
11441struct WaveCtx<'a> {
11442    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11443    /// paid for it.
11444    run: &'a str,
11445    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11446    node: &'a str,
11447    prompts: &'a Prompts,
11448    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11449    cache: Option<&'a Path>,
11450    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11451    /// `JobRecord::round`. `None` for every other node.
11452    round: Option<usize>,
11453    /// Carry each seat's failed-agent history across waves (the review loop
11454    /// only): start-of-round priority and handover choice read
11455    /// [`RunState::seat_history`], and every answer or failure writes it.
11456    carry_seats: bool,
11457    /// The run's park / interrupt requests, so a wait for a shared resource
11458    /// can be abandoned the moment the operator asks to park.
11459    pauses: Option<(&'a Pause, &'a Pause)>,
11460}
11461
11462/// Shared scheduling policy for operations and spawned seat invocations.
11463fn repository_wait(
11464    state: &RunState,
11465    pauses: Option<(&Pause, &Pause)>,
11466) -> crate::repo_lock::WaitPolicy {
11467    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11468    let inherited = crate::repo_lock::WaitPolicy::current();
11469    crate::repo_lock::WaitPolicy::new(
11470        Duration::from_secs(state.config.graph.timeout_resource_wait),
11471        move || {
11472            inherited.cancelled()
11473                || pauses
11474                    .as_ref()
11475                    .is_some_and(|(a, b)| a.parked() || b.parked())
11476        },
11477    )
11478}
11479
11480fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11481    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11482        state.event("resource", timeout.0.description());
11483        state.resource_block = Some(timeout.0.clone());
11484        return;
11485    }
11486    if error.is::<crate::repo_lock::ResourceBlocked>() {
11487        state.resource_block = Some(crate::run::ResourceBlock {
11488            cause: crate::run::ResourceBlockCause::Other,
11489            node: "repository".into(),
11490            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11491                "disk admission"
11492            } else if error.to_string().contains("disk pressure") {
11493                "disk pressure"
11494            } else if error.to_string().contains("disk admission") {
11495                "disk admission"
11496            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11497                "incremental cache admission"
11498            } else {
11499                "repository coordination"
11500            }
11501            .into(),
11502            detail: format!("{error:#}"),
11503            at: Timestamp::now(),
11504        });
11505        state.event("resource", error.to_string());
11506    }
11507}
11508
11509async fn coordinate_operation(
11510    state: &mut RunState,
11511    cwd: &Path,
11512    wait: &crate::repo_lock::WaitPolicy,
11513) -> Result<Option<crate::repo_lock::SeatLease>> {
11514    let result =
11515        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11516            .await;
11517    if let Err(e) = &result {
11518        record_repository_block(state, e);
11519    }
11520    result
11521}
11522
11523/// Run one job, honouring the parallelism budget.
11524async fn run_one(
11525    job: SeatJob,
11526    sem: Arc<Semaphore>,
11527    ctx: &WaveCtx<'_>,
11528    state: &mut RunState,
11529    attempt: usize,
11530) -> (SeatState, AgentOutcome) {
11531    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11532        .await
11533        .pop()
11534        .expect("one job in, one result out");
11535    (seat, out)
11536}
11537
11538/// Run every job concurrently, capped by the semaphore, preserving order.
11539///
11540/// Every seat in the batch is recorded into [`RunState::active`] before the
11541/// wave starts and cleared as each answer lands, so the run's own record says
11542/// who is still being waited on rather than only who finished.
11543async fn wave(
11544    jobs: Vec<SeatJob>,
11545    sem: Arc<Semaphore>,
11546    ctx: &WaveCtx<'_>,
11547    state: &mut RunState,
11548    attempt: usize,
11549) -> Vec<(usize, SeatState, AgentOutcome)> {
11550    let WaveCtx {
11551        run,
11552        node,
11553        prompts,
11554        cache,
11555        round,
11556        carry_seats: _,
11557        pauses,
11558    } = *ctx;
11559    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11560    for job in &jobs {
11561        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11562    }
11563    if let Err(e) = state.save() {
11564        // A failed persist of "who is answering right now" must not abort the
11565        // wave: the seats are already being asked, and the alternative is
11566        // losing the answers to save a status line nobody may even be
11567        // watching.
11568        tracing::warn!("could not persist in-progress seats: {e:#}");
11569    }
11570    // Shared-mode waves keep their existing single lease. Isolated writers
11571    // acquire their own checkout's target at seat admission.
11572    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11573    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11574    // never borrowed from a job's agent budget (and never charged to it either,
11575    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11576    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11577    let cache_guard = if let Some(cache_dir) = cache {
11578        if jobs_had_a_writer {
11579            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11580            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11581            match acquire_cache_lease(
11582                state,
11583                cache_dir,
11584                &owner,
11585                resource_limit,
11586                node,
11587                node,
11588                &cancel,
11589            )
11590            .await
11591            {
11592                Ok(Some(g)) => Some(g),
11593                // Parking: leave without spawning anything. The run parks at
11594                // the next boundary and the seats are asked afresh on resume.
11595                Ok(None) => {
11596                    if let Some(block) = &mut state.resource_block {
11597                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11598                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11599                        };
11600                    }
11601                    return block_wave(
11602                        jobs,
11603                        state,
11604                        node,
11605                        attempt,
11606                        "parked while waiting for the shared build cache",
11607                    );
11608                }
11609                // An unreadable lease is not contention: keep the old
11610                // fallback (no shared cache for this wave's seats).
11611                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11612                Err(e) => {
11613                    // Writing seats may not build into a cache this run does
11614                    // not hold, and an agent that cannot be given one is not
11615                    // asked at all: the run stops resumably instead.
11616                    let why = format!("{e:#}");
11617                    state.event(
11618                        "resource",
11619                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11620                    );
11621                    return block_wave(jobs, state, node, attempt, &why);
11622                }
11623            }
11624        } else {
11625            None
11626        }
11627    } else {
11628        None
11629    };
11630    // Every job keeps its whole budget: the wait above was not the agent's.
11631    // Restart the seats' clocks so "started" means "being spawned now".
11632    state.seats_spawning(node, attempt);
11633    if let Err(e) = state.save() {
11634        tracing::warn!("could not persist the start of a wave: {e:#}");
11635    }
11636    // Queueing behind this wave's own seats for a parallelism slot is normal
11637    // (each of them is bounded by its own agent timeout); only a wait beyond
11638    // all of them plus the resource limit means the slots never came back.
11639    let slot_limit = resource_limit
11640        + jobs
11641            .iter()
11642            .map(|j| j.timeout)
11643            .max()
11644            .unwrap_or_default()
11645            .saturating_mul(jobs.len() as u32);
11646    let mut set = tokio::task::JoinSet::new();
11647    // Seats announce themselves here the moment they hold a parallelism
11648    // permit, i.e. just before their CLI is spawned.
11649    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11650    let overlay = prompts.overlay(node);
11651    let repository_wait = repository_wait(state, pauses);
11652    for (i, mut job) in jobs.into_iter().enumerate() {
11653        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11654        if cache.is_some() {
11655            job.prompt.push('\n');
11656            job.prompt
11657                .push_str(&prompt::build_cache_note(node, job.allow_write));
11658        }
11659        let sem = Arc::clone(&sem);
11660        let run = run.to_owned();
11661        let node = node.to_owned();
11662        // Only implementers were told about the task's attachments, so only
11663        // their seats get the directory widened for reading.
11664        let attachments = if node == "implement" {
11665            state.attachments.clone()
11666        } else {
11667            Vec::new()
11668        };
11669        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11670        // `prompt::build_cache_note`'s doc for why setting it anyway is
11671        // exactly how a sandboxed reviewer's write refusal got reported as a
11672        // defect in the patch, not a property of its own seat. And a
11673        // write-allowed one is handed it only when the lease above was
11674        // actually acquired: a wave that could not get it (`cache_guard` is
11675        // `None`, see its own comment) must not send seats to build into a
11676        // directory this run does not hold - that is the exact concurrent,
11677        // unmanaged-write race this module exists to prevent, not something
11678        // "proceeding anyway" is allowed to reintroduce.
11679        let cache = cache
11680            .filter(|_| job.allow_write && cache_guard.is_some())
11681            .map(Path::to_path_buf);
11682        let spawned_tx = spawned_tx.clone();
11683        let repository_wait = repository_wait.clone();
11684        let coordination = state.config.coordination.clone();
11685        let fetched_base = state.fetched_base.clone();
11686        set.spawn(async move {
11687            // A wait for a parallelism slot is scheduling, not the agent: it
11688            // is bounded by its own limit and ends as a resource block, never
11689            // as a timeout of the agent that was not started.
11690            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11691                Ok(p) => p,
11692                Err(_) => {
11693                    return (
11694                        i,
11695                        job.seat,
11696                        AgentOutcome::ResourceBlocked(format!(
11697                            "no parallel slot became free within {}s",
11698                            slot_limit.as_secs()
11699                        )),
11700                        None,
11701                        false,
11702                    );
11703                }
11704            };
11705            spawned_tx.send(job.seat.key.clone()).ok();
11706            let mut seat = job.seat;
11707            let out = repository_wait
11708                .scope(agent::invoke(
11709                    &job.spec,
11710                    &mut seat,
11711                    &Invocation {
11712                        coordination: coordination.as_ref(),
11713                        fetched_base: fetched_base.as_ref(),
11714                        cwd: &job.cwd,
11715                        prompt: &job.prompt,
11716                        timeout: job.timeout,
11717                        allow_write: job.allow_write,
11718                        sessions: job.sessions,
11719                        artifacts: &job.artifacts,
11720                        stem: &job.stem,
11721                        run: &run,
11722                        node: &node,
11723                        cache_dir: cache.as_deref(),
11724                        attachments: &attachments,
11725                        writable: &[],
11726                    },
11727                ))
11728                .await;
11729            let cache_block = out
11730                .as_ref()
11731                .err()
11732                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11733                .map(|timeout| timeout.0.clone());
11734            let interrupted = out
11735                .as_ref()
11736                .err()
11737                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11738            let out = match out {
11739                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11740                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11741                // Billed work the CLI failed to hand over is not an ordinary
11742                // failure, but its text is the CLI's raw error JSON, not an
11743                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11744                // read it as one by forgetting to check. `usable()` is always
11745                // false here (dropped implies an empty response), so this has
11746                // to be checked before the catch-all `Failed` below or the
11747                // one shape this exists for is lost with the rest.
11748                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11749                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11750                Ok(o) => AgentOutcome::Failed(format!(
11751                    "process exited with no usable output ({})",
11752                    crate::notices::exit_status(o.exit_code)
11753                )),
11754                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11755                    AgentOutcome::ResourceBlocked(e.to_string())
11756                }
11757                Err(e) => AgentOutcome::Failed(e.to_string()),
11758            };
11759            (i, seat, out, cache_block, interrupted)
11760        });
11761    }
11762    drop(spawned_tx);
11763    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11764    loop {
11765        let joined = tokio::select! {
11766            Some(key) = spawned_rx.recv() => {
11767                // The clock of this seat starts now, not when it queued.
11768                state.seat_spawned(&key);
11769                if let Err(e) = state.save() {
11770                    tracing::warn!("could not persist a seat's start: {e:#}");
11771                }
11772                continue;
11773            }
11774            joined = set.join_next() => joined,
11775        };
11776        let Some(joined) = joined else {
11777            break;
11778        };
11779        let (i, seat, out, cache_block, interrupted) = match joined {
11780            Ok(v) => v,
11781            // No seat to clear: a panicked task never reported which one it
11782            // was. The defensive sweep below this loop is what stops that
11783            // seat's `active` entry from surviving forever.
11784            Err(e) => {
11785                tracing::error!("agent task panicked: {e}");
11786                continue;
11787            }
11788        };
11789        state.seat_finished(&seat.key);
11790        if interrupted
11791            && node == "implement"
11792            && let Some(label) = state
11793                .candidates
11794                .iter()
11795                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11796                .map(|candidate| candidate.label)
11797        {
11798            state.candidate_preservation.insert(
11799                label,
11800                "interrupted implementation awaiting persistence".into(),
11801            );
11802            state.interrupted_implementations.insert(label);
11803        }
11804        if let Some(block) = cache_block
11805            && state.resource_block.is_none()
11806        {
11807            state.event("resource", block.description());
11808            state.resource_block = Some(block);
11809        }
11810        if let AgentOutcome::ResourceBlocked(why) = &out
11811            && state.resource_block.is_none()
11812        {
11813            state.resource_block = Some(crate::run::ResourceBlock {
11814                cause: crate::run::ResourceBlockCause::Other,
11815                node: node.to_owned(),
11816                kind: if why.contains("disk pressure") {
11817                    "disk pressure"
11818                } else if why.contains("disk admission") {
11819                    "disk admission"
11820                } else if why.contains(crate::incremental::BLOCKED) {
11821                    "incremental cache admission"
11822                } else if why.contains(crate::build_target::KIND) {
11823                    crate::build_target::KIND
11824                } else if why.contains("repository coordination") {
11825                    "repository coordination"
11826                } else {
11827                    "parallel slot"
11828                }
11829                .to_owned(),
11830                detail: why.clone(),
11831                at: Timestamp::now(),
11832            });
11833            let activity = if interrupted {
11834                "agent execution interrupted"
11835            } else {
11836                "no agent was started"
11837            };
11838            state.event("resource", format!("{node}: {activity} - {why}"));
11839        }
11840        record_jobs(state, node, round, &seat.key, &out);
11841        if let Err(e) = state.save() {
11842            tracing::warn!("could not persist a seat's completion: {e:#}");
11843        }
11844        if collected.len() <= i {
11845            collected.resize_with(i + 1, || None);
11846        }
11847        collected[i] = Some((i, seat, out));
11848    }
11849    // Belt-and-braces for the panic branch above: every seat this exact batch
11850    // started shares this `(node, attempt)` pair, and every seat that finished
11851    // normally already cleared itself, so anything left tagged with it here
11852    // can only be a panicked task's leftover. Cleared unconditionally rather
11853    // than left to read as still answering forever.
11854    if state
11855        .active
11856        .values()
11857        .any(|a| a.node == node && a.attempt == attempt)
11858    {
11859        state
11860            .active
11861            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11862        if let Err(e) = state.save() {
11863            tracing::warn!("could not persist the end of a wave: {e:#}");
11864        }
11865    }
11866    // Whether or not the lease above was actually held, several worktrees
11867    // may just have built into the cache with nothing here able to name one
11868    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11869    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11870    // clean it might not have strictly needed; trusting a stale match would
11871    // cost it a wrong answer.
11872    if let Some(cache_dir) = cache
11873        && jobs_had_a_writer
11874    {
11875        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11876    }
11877    if let Some(guard) = cache_guard {
11878        guard.release();
11879    }
11880    collected.into_iter().flatten().collect()
11881}
11882
11883/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11884/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11885/// this is data collection, not the fix-specific completion contract in
11886/// [`Runner::continue_fix_report`], and applies regardless of which node
11887/// asked.
11888///
11889/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11890/// evidence from; `Failed` does not, and correctly contributes nothing — a
11891/// timeout or crash is not itself evidence about a command the seat may have
11892/// started.
11893fn record_jobs(
11894    state: &mut RunState,
11895    node: &str,
11896    round: Option<usize>,
11897    seat: &str,
11898    out: &AgentOutcome,
11899) {
11900    let commands: &[agent::CommandEvidence] = match out {
11901        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11902        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11903    };
11904    let checked_at = Timestamp::now();
11905    for c in commands {
11906        state.jobs.push(JobRecord {
11907            node: node.to_owned(),
11908            round,
11909            seat: seat.to_owned(),
11910            id: c.id.clone(),
11911            description: c.description.clone(),
11912            checked_at,
11913            status: match c.exit_code {
11914                Some(0) => JobStatus::Completed,
11915                Some(_) => JobStatus::Failed,
11916                None => JobStatus::Unknown,
11917            },
11918            exit_code: c.exit_code,
11919            result_summary: c.result_summary.clone(),
11920            source: c.source.clone(),
11921        });
11922    }
11923}
11924
11925/// Is a review round clean, given how many reviewer seats answered against
11926/// how many the round expected?
11927///
11928/// A seat that never answered (timeout, crash, unparsable output) is not a
11929/// seat that read the patch and found nothing — treating it as such is
11930/// exactly the bug this function exists to close. Under the default `block`
11931/// policy a missing seat can never be clean; `warn` still requires the seats
11932/// that *did* answer to have found nothing blocking and verification to be
11933/// green.
11934///
11935/// `quota_missing` narrows that `block` default for exactly one cause of
11936/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11937/// a session limit lifts by the very next round buys nothing — the seat is
11938/// asked again with the same quota — so once every missing seat is accounted
11939/// for by a quota loss (and at least one seat *did* answer, so a decision has
11940/// something to rest on) the round is decided on the panel that could answer,
11941/// same as `warn` would. A panel that lost every seat to quota is not
11942/// decided here: `answered == 0` falls through to the existing `block`
11943/// fallback so a fully collapsed panel still waits rather than landing on no
11944/// review at all.
11945fn round_is_clean(
11946    blocking: usize,
11947    e2e_ok: bool,
11948    answered: usize,
11949    expected: usize,
11950    quota_missing: usize,
11951    policy: IncompleteReviewPolicy,
11952) -> bool {
11953    if blocking != 0 || !e2e_ok {
11954        return false;
11955    }
11956    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11957        return true;
11958    }
11959    answered > 0 && expected - answered <= quota_missing
11960}
11961
11962/// The review loop's own conclusion, derived entirely from its persisted
11963/// round records and the round budget that produced them — never from
11964/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11965/// recomputes the identical answer regardless of what an earlier node in the
11966/// same walk, or a previous walk, did to `status`.
11967///
11968/// `None` while more rounds remain to try, including when review never ran
11969/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11970/// gone clean, or the budget is spent, or the tree has stopped moving (see
11971/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11972///
11973/// - An incomplete panel that raised nothing is missing input, not a
11974///   verified tree — never a hand-off candidate, whatever verification said
11975///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11976/// - Otherwise, green e2e on the last round hands off (see
11977///   [`Runner::stop_reviewing`]); red e2e blocks.
11978///
11979/// A last round whose own verification is still `ResourceBlocked` — magi
11980/// itself never got a command to run, not evidence the patch is broken —
11981/// is neither: this returns `None` for it too, the same as "more rounds
11982/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11983/// handling of that shape) instead of this cheap recomputation guessing a
11984/// verdict a real attempt never produced.
11985pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11986    if max_rounds == 0
11987        || reviews.last().is_some_and(|r| {
11988            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11989        })
11990    {
11991        return Some(RunStatus::Gating);
11992    }
11993    let last = reviews.last()?;
11994    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11995    if reviews.len() < max_rounds && !stagnant {
11996        return None;
11997    }
11998    if last.incomplete() && last.blocking == 0 {
11999        return Some(RunStatus::Blocked);
12000    }
12001    if last.e2e_status() == E2eStatus::ResourceBlocked
12002        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12003    {
12004        return None;
12005    }
12006    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12007        RunStatus::Gating
12008    } else {
12009        RunStatus::Blocked
12010    })
12011}
12012
12013/// How long a re-ask may take, given the budget the first attempt had.
12014///
12015/// A `nudged` retry is a request to restate an answer the seat has already
12016/// worked out: it carries no new work, so it does not deserve the original
12017/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12018/// 133 seconds while a third sat for over ten minutes on a resumed session
12019/// holding 410 KB of prior output - and because the retry had inherited the
12020/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12021/// judging round whose other seats were long finished.
12022///
12023/// A quarter of the budget, with a floor so that a deliberately short timeout
12024/// does not collapse to nothing. A retry that re-sends the whole prompt
12025/// (because the seat kept no context) is the original job again, and keeps the
12026/// original budget.
12027pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12028    if nudged {
12029        (full / 4).max(Duration::from_secs(120)).min(full)
12030    } else {
12031        full
12032    }
12033}
12034
12035/// Run a wave and parse each reply, re-asking the seats whose reply was
12036/// unusable.
12037///
12038/// The re-ask is a nudge rather than the whole prompt again when the seat still
12039/// holds its conversation, which is the difference between a cheap retry and
12040/// paying for the entire candidate set twice.
12041///
12042/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12043/// successor in `roster` is handed to it instead of being re-asked: the
12044/// handover is the retry. A seat with no successor left (a single-agent
12045/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12046/// the asks to one seat in one node number at most
12047/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12048/// is asked once (a dropped stream is nudged first), and only the last agent
12049/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12050/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12051/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12052/// other failure stops the chain when the previous agent failed the same way
12053/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12054/// [`has_context`] is false and the job's own full prompt and full budget are
12055/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12056/// intermediate ones are not losses) and is returned as a failure like any
12057/// other absent seat — the caller decides whether the panel still has a
12058/// quorum. An empty `roster` disables handover: failures are nudged as they
12059/// always were, and a quota is simply lost. A reply that fails to parse or
12060/// validate is the prompt's doing and is only ever nudged, never handed over.
12061///
12062/// The returned [`SeatState`] names the agent that answered (or tried last).
12063#[allow(clippy::too_many_arguments)]
12064async fn ask_json_wave<T>(
12065    jobs: Vec<SeatJob>,
12066    sem: Arc<Semaphore>,
12067    retries: usize,
12068    roster: &[AgentSpec],
12069    ctx: &WaveCtx<'_>,
12070    losses: &mut Vec<QuotaLoss>,
12071    state: &mut RunState,
12072    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12073) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12074where
12075    T: serde::de::DeserializeOwned + Send + 'static,
12076{
12077    ask_wave_with(
12078        jobs,
12079        sem,
12080        retries,
12081        roster,
12082        ctx,
12083        losses,
12084        state,
12085        &|text: &str| {
12086            let v = verdict::extract_json::<T>(text)?;
12087            validate(&v)?;
12088            Ok(v)
12089        },
12090    )
12091    .await
12092}
12093
12094/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12095/// a node whose answer is prose (deliberation) shares the same handover,
12096/// failure classification, quota bookkeeping and bounds instead of a copy.
12097///
12098/// A seat handed to another roster agent is sent the job's `handover` prompt
12099/// (when it has one) rather than `prompt`: the new agent has no session, so a
12100/// resume-style prompt would be incomplete. That holds for the handover ask
12101/// and for every nudge to that agent whose `has_context` is false.
12102#[allow(clippy::too_many_arguments)]
12103async fn ask_wave_with<T>(
12104    jobs: Vec<SeatJob>,
12105    sem: Arc<Semaphore>,
12106    retries: usize,
12107    roster: &[AgentSpec],
12108    ctx: &WaveCtx<'_>,
12109    losses: &mut Vec<QuotaLoss>,
12110    state: &mut RunState,
12111    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12112) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12113where
12114    T: Send + 'static,
12115{
12116    let n = jobs.len();
12117    let originals: Vec<SeatJob> = jobs;
12118    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12119    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12120    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12121    // answer, N once it has gone through N nudges. Read back once this
12122    // returns, so a caller building a history record (`ReviewRecord`) can
12123    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12124    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12125    // field's own doc.
12126    let mut nudges: Vec<usize> = vec![0; n];
12127    // The agent now occupying each seat, the ids it has already been through,
12128    // where in the roster the walk began, the class of the last failure, and
12129    // the stem word of a handover not yet asked (full prompt, full budget).
12130    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12131    let mut tried: Vec<BTreeSet<String>> = specs
12132        .iter()
12133        .map(|s| BTreeSet::from([s.id.clone()]))
12134        .collect();
12135    let starts: Vec<usize> = specs
12136        .iter()
12137        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12138        .collect();
12139    let carry = ctx.carry_seats && !roster.is_empty();
12140    // Carried across rounds: ids that failed the seat earlier, and how the
12141    // last failure went (so a repeat of it is not handed over again).
12142    let carried: Vec<BTreeSet<String>> = originals
12143        .iter()
12144        .map(|j| {
12145            state
12146                .seat_history
12147                .get(&j.seat.key)
12148                .filter(|_| carry)
12149                .map(|h| h.failed.clone())
12150                .unwrap_or_default()
12151        })
12152        .collect();
12153    let mut prev: Vec<Option<FailClass>> = originals
12154        .iter()
12155        .map(|j| {
12156            state
12157                .seat_history
12158                .get(&j.seat.key)
12159                .filter(|_| carry)
12160                .and_then(|h| h.last_fail.clone())
12161        })
12162        .collect();
12163    let next_agent =
12164        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12165            let others: BTreeSet<String> = specs
12166                .iter()
12167                .enumerate()
12168                .filter(|(j, _)| *j != i)
12169                .map(|(_, s)| s.id.clone())
12170                .collect();
12171            pick_successor(
12172                roster,
12173                starts[i],
12174                tried,
12175                carry.then(|| &carried[i]),
12176                &others,
12177            )
12178            .cloned()
12179        };
12180    let mut fresh: Vec<Option<String>> = vec![None; n];
12181    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12182    let mut pending: Vec<usize> = (0..n).collect();
12183
12184    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12185    // asks: an agent with a successor is asked once and handed over, and only
12186    // a seat with no successor spends `retries` nudges on the same agent. This
12187    // only guarantees the loop's own termination whatever those say.
12188    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12189    for round in 0..max_rounds {
12190        if pending.is_empty() {
12191            break;
12192        }
12193        let mut batch = Vec::with_capacity(pending.len());
12194        let mut renudged: Vec<&str> = Vec::new();
12195        for &i in &pending {
12196            let src = &originals[i];
12197            // A seat now held by another agent than the job named has no
12198            // session of its own: it gets the full-context prompt whenever
12199            // it is asked in full (the handover ask, a nudge it cannot
12200            // resume).
12201            let full: &str = match &src.handover {
12202                Some(h) if specs[i].id != src.spec.id => h,
12203                _ => &src.prompt,
12204            };
12205            // The prompt and the budget are one decision: a nudge restates
12206            // finished work, a re-sent prompt redoes it.
12207            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12208                (
12209                    full.to_owned(),
12210                    src.timeout,
12211                    format!("{}-{word}-{}", src.stem, specs[i].id),
12212                )
12213            } else if nudges[i] == 0 {
12214                (full.to_owned(), src.timeout, src.stem.clone())
12215            } else {
12216                renudged.push(src.seat.key.as_str());
12217                let why = done[i]
12218                    .as_ref()
12219                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12220                    .unwrap_or_else(|| "no parsable answer".to_owned());
12221                let nudge = prompt::nudge(&why);
12222                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12223                let prompt = if nudged {
12224                    nudge
12225                } else {
12226                    format!("{full}\n\n---\n\n{nudge}")
12227                };
12228                (
12229                    prompt,
12230                    retry_budget(src.timeout, nudged),
12231                    format!("{}-retry{}", src.stem, nudges[i]),
12232                )
12233            };
12234            batch.push(SeatJob {
12235                spec: specs[i].clone(),
12236                seat: seats[i].clone(),
12237                cwd: src.cwd.clone(),
12238                prompt,
12239                timeout,
12240                allow_write: src.allow_write,
12241                sessions: src.sessions,
12242                artifacts: src.artifacts.clone(),
12243                stem,
12244                handover: None,
12245            });
12246        }
12247
12248        if !renudged.is_empty() {
12249            state.event(
12250                ctx.node,
12251                format!("retry {round}: re-asking {}", renudged.join(", ")),
12252            );
12253        }
12254        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12255        let mut still = Vec::new();
12256        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12257            seats[i] = seat;
12258            // No agent was asked: nothing to hand over, nudge, remember or
12259            // charge. The caller sees `resource_block` and stops the node.
12260            if let AgentOutcome::ResourceBlocked(why) = &out {
12261                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12262                continue;
12263            }
12264            let class = FailClass::of(&out);
12265            // A dropped stream is nudged first (the conversation is still
12266            // there to pick up); only a seat whose nudges are spent hands over.
12267            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12268                && nudges[i] < retries
12269                && !roster.is_empty();
12270            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12271                let next = should_hand_over(prev[i].as_ref(), &cur)
12272                    .then(|| next_agent(i, &tried[i], &specs))
12273                    .flatten();
12274                if carry {
12275                    let h = state
12276                        .seat_history
12277                        .entry(originals[i].seat.key.clone())
12278                        .or_default();
12279                    h.failed.insert(specs[i].id.clone());
12280                    h.last_fail = Some(cur.clone());
12281                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12282                        h.last_ok = None;
12283                    }
12284                    // Saved before the next agent is asked, so a restart in
12285                    // between does not forget who failed.
12286                    if let Err(e) = state.save() {
12287                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12288                    }
12289                }
12290                if let Some(next) = next {
12291                    record_handover(
12292                        state,
12293                        ctx.node,
12294                        &originals[i].seat.key,
12295                        &specs[i].id,
12296                        &next.id,
12297                        &cur,
12298                        &fail_reason(&out),
12299                    );
12300                    tried[i].insert(next.id.clone());
12301                    prev[i] = Some(cur.clone());
12302                    seats[i] =
12303                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12304                    specs[i] = next;
12305                    fresh[i] = Some(cur.stem_word().to_owned());
12306                    nudges[i] = 0;
12307                    done[i] = Some(Err(anyhow::anyhow!(
12308                        "handed over after: {}",
12309                        fail_reason(&out)
12310                    )));
12311                    still.push(i);
12312                    continue;
12313                }
12314            }
12315            if carry
12316                && !nudge_first
12317                && let Some(cur) = class.clone()
12318            {
12319                // The chain ended here (no successor, or a repeated failure).
12320                let h = state
12321                    .seat_history
12322                    .entry(originals[i].seat.key.clone())
12323                    .or_default();
12324                h.failed.insert(specs[i].id.clone());
12325                h.last_fail = Some(cur);
12326            }
12327            let parsed = match out {
12328                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12329                AgentOutcome::Quota(o) => {
12330                    last_quota[i] = o.quota.clone();
12331                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12332                }
12333                // Not a parseable answer: the nudge loop re-asks it, which is
12334                // exactly what a dropped stream needs. Just don't hand its raw
12335                // error JSON to `extract_json`.
12336                AgentOutcome::Dropped(o) => {
12337                    let why = o
12338                        .dropped
12339                        .as_ref()
12340                        .map(|d| d.why.as_str())
12341                        .unwrap_or("the CLI ended the stream without delivering its answer");
12342                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12343                }
12344                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12345                    Err(anyhow::anyhow!(e))
12346                }
12347            };
12348            let quota = class == Some(FailClass::Quota);
12349            let failed = parsed.is_err();
12350            if !failed && matches!(ctx.node, "judge" | "vote") {
12351                // A validated answer restores this seat's quorum presence,
12352                // including on the normal path after an all-seat block.
12353                state
12354                    .quota
12355                    .retain(|loss| loss.seat != originals[i].seat.key);
12356            }
12357            done[i] = Some(parsed);
12358            if carry && !failed {
12359                let h = state
12360                    .seat_history
12361                    .entry(originals[i].seat.key.clone())
12362                    .or_default();
12363                h.failed.remove(&specs[i].id);
12364                h.last_ok = Some(specs[i].id.clone());
12365                h.last_fail = None;
12366            }
12367            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12368            // fail the same way; and never re-ask a seat that already parsed.
12369            // A failed agent that still has a successor is not re-asked
12370            // either: the handover was its remedy and has just been refused
12371            // (the chain stops on a repeated failure class). A seat with no
12372            // successor left (a single-agent roster, the roster's tail, or an
12373            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12374            let agent_failure = class.is_some()
12375                && !nudge_first
12376                && !roster.is_empty()
12377                && next_agent(i, &tried[i], &specs).is_some();
12378            if failed && !quota && !agent_failure && nudges[i] < retries {
12379                nudges[i] += 1;
12380                still.push(i);
12381            }
12382        }
12383        pending = still;
12384    }
12385
12386    // One loss per seat whose chain ended on a quota: the intermediate ones
12387    // were absorbed by a handover and are not losses.
12388    for (i, q) in last_quota.into_iter().enumerate() {
12389        if let Some(quota) = q {
12390            losses.push(QuotaLoss::from_report(
12391                originals[i].seat.key.clone(),
12392                ctx.node,
12393                Some(&quota),
12394            ));
12395        }
12396    }
12397
12398    // A stalled quorum already has its own recovery checkpoint. Refresh
12399    // its missing seats before deciding whether it can resume.
12400    if state.status != RunStatus::Stalled
12401        && ctx.node != "deliberate"
12402        && n > 0
12403        && losses.len() == n
12404        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12405    {
12406        block_machine_outage(state, ctx.node, losses);
12407        state.quota.append(losses);
12408    }
12409
12410    seats
12411        .into_iter()
12412        .zip(done)
12413        .zip(nudges)
12414        .map(|((seat, res), attempts)| {
12415            (
12416                seat,
12417                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12418                attempts,
12419            )
12420        })
12421        .collect()
12422}
12423
12424/// A node with no available agent has no task verdict. Preserve the node
12425/// checkpoint and record why a subsequent explicit resume is needed.
12426pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12427    let mut auth: Vec<_> = losses
12428        .iter()
12429        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12430        .map(|loss| loss.agent.clone())
12431        .collect();
12432    auth.sort();
12433    auth.dedup();
12434    let (kind, detail) = if auth.is_empty() {
12435        (
12436            "agent usage limit",
12437            "All seats reached their agent usage limits; resume after usage is available"
12438                .to_owned(),
12439        )
12440    } else {
12441        (
12442            "agent authentication",
12443            format!(
12444                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12445                auth.join(", ")
12446            ),
12447        )
12448    };
12449    state.resource_block = Some(crate::run::ResourceBlock {
12450        node: node.to_owned(),
12451        kind: kind.to_owned(),
12452        cause: crate::run::ResourceBlockCause::Other,
12453        detail: detail.clone(),
12454        at: Timestamp::now(),
12455    });
12456    state.event(node, detail);
12457}
12458
12459/// Did the wave end without asking any agent (see [`block_wave`])?
12460fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12461    results
12462        .iter()
12463        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12464}
12465
12466/// Settle a wave that never spawned anything: every job answers
12467/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12468/// else about the seat (session, history, quota) is touched.
12469fn block_wave(
12470    jobs: Vec<SeatJob>,
12471    state: &mut RunState,
12472    node: &str,
12473    attempt: usize,
12474    why: &str,
12475) -> Vec<(usize, SeatState, AgentOutcome)> {
12476    state.resource_wait = None;
12477    state
12478        .active
12479        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12480    if let Err(e) = state.save() {
12481        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12482    }
12483    jobs.into_iter()
12484        .enumerate()
12485        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12486        .collect()
12487}
12488
12489/// Acquire the shared build cache's lease, waiting out contention within
12490/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12491/// unbounded wait is never acceptable).
12492///
12493/// A first, non-blocking check happens before ever waiting; if it finds the
12494/// lease busy, that fact is logged as a `verify` event *and* flushed with
12495/// [`RunState::save`] immediately — not only once the wait finally succeeds
12496/// or gives up — so a `magi show` run by a different process while this one
12497/// is still waiting reads a `run.json` that says so, rather than whatever it
12498/// looked like before the wait started. The same applies to the terminal
12499/// failure: logged and saved before this returns `Err`, so a caller that
12500/// could not get the lease at all still leaves a legible record of why.
12501async fn acquire_cache_lease(
12502    state: &mut RunState,
12503    cache_dir: &Path,
12504    owner: &crate::cache::Owner,
12505    budget: Duration,
12506    node: &str,
12507    context: &str,
12508    cancel: &(dyn Fn() -> bool + Sync),
12509) -> Result<Option<crate::cache::Guard>> {
12510    let home = crate::run::home();
12511    let kind = if crate::build_target::isolated(&state.config) {
12512        crate::build_target::KIND
12513    } else {
12514        "shared build cache"
12515    };
12516    let started = Instant::now();
12517    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12518        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12519        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12520        Err(e) => {
12521            state.event(
12522                "verify",
12523                format!(
12524                    "{context}: could not check the {kind} at {}: {e:#}",
12525                    cache_dir.display()
12526                ),
12527            );
12528            if let Err(e2) = state.save() {
12529                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12530            }
12531            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12532        }
12533    };
12534    state.event(
12535        "verify",
12536        format!(
12537            "{context}: waiting for the {kind} at {} ({})",
12538            cache_dir.display(),
12539            busy.describe()
12540        ),
12541    );
12542    // Seats of this node are waiting, not running: say so, so the countdown a
12543    // reader sees only ever measures an agent that has been spawned.
12544    state.resource_wait = Some(crate::run::ResourceWait {
12545        node: context.to_owned(),
12546        kind: kind.to_owned(),
12547        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12548        since: Timestamp::now(),
12549        limit_secs: budget.as_secs(),
12550    });
12551    if let Err(e) = state.save() {
12552        tracing::warn!("could not persist a cache wait: {e:#}");
12553    }
12554    let remaining = budget.saturating_sub(started.elapsed());
12555    let waited = crate::cache::wait_for_unless(
12556        &home,
12557        cache_dir,
12558        owner,
12559        remaining,
12560        Duration::from_secs(5),
12561        cancel,
12562    )
12563    .await;
12564    state.resource_wait = None;
12565    let cause = match &waited {
12566        Ok(Some(_)) => None,
12567        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12568        Err(error)
12569            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12570        {
12571            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12572                target: cache_dir.to_owned(),
12573                waited_secs: started.elapsed().as_secs(),
12574                limit_secs: budget.as_secs(),
12575            })
12576        }
12577        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12578            Some(crate::run::ResourceBlockCause::Timeout {
12579                waited_secs: started.elapsed().as_secs(),
12580                limit_secs: budget.as_secs(),
12581            })
12582        }
12583        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12584    };
12585    if let Some(cause) = cause {
12586        let detail = match &waited {
12587            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12588            Err(error) => format!("{error:#}"),
12589        };
12590        state.resource_block = Some(crate::run::ResourceBlock {
12591            cause,
12592            node: node.to_owned(),
12593            kind: kind.into(),
12594            detail: format!("{}: {detail}", cache_dir.display()),
12595            at: Timestamp::now(),
12596        });
12597        state.event(
12598            "resource",
12599            state.resource_block.as_ref().unwrap().description(),
12600        );
12601    }
12602    if let Err(error) = state.save() {
12603        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12604    }
12605    waited
12606}
12607
12608/// The lease state could not be read at all (unreadable lease file, a
12609/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12610/// known to be contended, so a wave degrades to running without a shared cache
12611/// instead of stopping on a hold that [`crate::triage`] could never release.
12612#[derive(Debug)]
12613struct CacheCheckError(String);
12614
12615impl std::fmt::Display for CacheCheckError {
12616    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12617        f.write_str(&self.0)
12618    }
12619}
12620
12621impl std::error::Error for CacheCheckError {}
12622
12623/// Keep a specific acquisition outcome when the caller adds command evidence.
12624fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12625    let kind = if crate::build_target::isolated(&state.config) {
12626        crate::build_target::KIND
12627    } else {
12628        "shared build cache"
12629    };
12630    state
12631        .resource_block
12632        .get_or_insert_with(|| crate::run::ResourceBlock {
12633            cause: crate::run::ResourceBlockCause::Other,
12634            node: node.to_owned(),
12635            kind: kind.into(),
12636            detail: format!("{error:#}"),
12637            at: Timestamp::now(),
12638        });
12639    if let Err(error) = state.save() {
12640        tracing::warn!("could not persist cache resource block: {error:#}");
12641    }
12642}
12643
12644tokio::task_local! {
12645    static VERIFY_TARGET: PathBuf;
12646}
12647
12648/// Run `body` — a verify command batch — while holding the shared build
12649/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12650/// never interleave with another borrower's build against the same
12651/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12652/// timeout, or a human's own `magi review`. See the `cache` module doc for
12653/// why this matters more than Cargo's own per-target locking covers — two
12654/// *different* worktrees building the same package name/version into one
12655/// cache directory is a staleness bug, not a lock contention one.
12656///
12657/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12658/// agent waves do. Repository scheduling also has its own bounded,
12659/// cancellable resource-wait policy. Contention must not consume the
12660/// verification budget: `body` receives the full `budget` after both leases
12661/// are acquired and the cache is fresh. Without a shared cache, only
12662/// repository coordination is acquired before handing over the full budget.
12663///
12664/// A lease that cannot be acquired within the resource wait is reported as a single
12665/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12666/// verification — the same shape a spawn failure already takes in
12667/// [`run_commands`], so a caller need not special-case it.
12668#[allow(clippy::too_many_arguments)]
12669async fn with_cache_lease<'s, F, Fut>(
12670    state: &'s mut RunState,
12671    cache_dir: Option<&Path>,
12672    node: &str,
12673    seat: &str,
12674    worktree: &Path,
12675    head: &str,
12676    budget: Duration,
12677    context: &str,
12678    wait: &crate::repo_lock::WaitPolicy,
12679    body: F,
12680) -> Result<(Vec<CommandOutcome>, bool)>
12681where
12682    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12683    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12684{
12685    // Match editing waves: cache first, repository second. In particular,
12686    // pre_gate must never hold the repository while waiting for a wave's cache.
12687    let started = Instant::now();
12688    let home = crate::run::home();
12689    let isolated = crate::build_target::isolated(&state.config);
12690    let planned_target = if isolated {
12691        let plan = (|| -> Result<PathBuf> {
12692            crate::build_target::supports(&state.config)?;
12693            crate::build_target::resolve(&home, worktree)
12694        })();
12695        match plan {
12696            Ok(path) => Some(path),
12697            Err(error) => {
12698                record_cache_error(state, node, &error);
12699                return Ok((
12700                    vec![CommandOutcome {
12701                        command: "(planning isolated build cache)".into(),
12702                        code: None,
12703                        output_tail: format!("{error:#}"),
12704                        duration_ms: 0,
12705                        resource_blocked: true,
12706                        ..Default::default()
12707                    }],
12708                    false,
12709                ));
12710            }
12711        }
12712    } else {
12713        None
12714    };
12715    let cache_dir = planned_target.as_deref().or(cache_dir);
12716    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12717    let guard = if let Some(cache_dir) = cache_dir {
12718        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12719        match acquire_cache_lease(
12720            state,
12721            cache_dir,
12722            &owner,
12723            resource_limit,
12724            node,
12725            context,
12726            &|| wait.cancelled(),
12727        )
12728        .await
12729        .and_then(|g| {
12730            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12731        }) {
12732            Ok(g) => Some(g),
12733            Err(e) => {
12734                record_cache_error(state, node, &e);
12735                return Ok((
12736                    vec![CommandOutcome {
12737                        command: if isolated {
12738                            "(waiting for the isolated build cache)"
12739                        } else {
12740                            "(waiting for the shared build cache)"
12741                        }
12742                        .into(),
12743                        code: None,
12744                        output_tail: e.to_string(),
12745                        duration_ms: started.elapsed().as_millis() as u64,
12746                        resource_blocked: true,
12747                        ..Default::default()
12748                    }],
12749                    false,
12750                ));
12751            }
12752        }
12753    } else {
12754        None
12755    };
12756    let _coordination = coordinate_operation(state, worktree, wait).await?;
12757    if let Some(path) = &planned_target {
12758        state.event(node, format!("isolated build target: {}", path.display()));
12759    }
12760    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12761        let identity = crate::cache::Identity::new(worktree, head);
12762        let fresh = crate::cache::ensure_fresh(
12763            &home,
12764            cache_dir,
12765            &identity,
12766            &state.config.verify.cargo_manifests(),
12767        );
12768        if let Err(e) = fresh {
12769            record_cache_error(state, node, &e);
12770            state.event(
12771                "verify",
12772                format!(
12773                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12774                    worktree.display(),
12775                    short(head)
12776                ),
12777            );
12778            if let Some(guard) = guard {
12779                guard.release();
12780            }
12781            return Ok((
12782                vec![CommandOutcome {
12783                    command: "(confirming the build cache is fresh)".into(),
12784                    code: None,
12785                    output_tail: e.to_string(),
12786                    duration_ms: started.elapsed().as_millis() as u64,
12787                    resource_blocked: true,
12788                    ..Default::default()
12789                }],
12790                false,
12791            ));
12792        }
12793    }
12794    let future = body(state, budget);
12795    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12796        VERIFY_TARGET.scope(target, future).await
12797    } else {
12798        future.await
12799    };
12800    if !timed_out_pids.is_empty() {
12801        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12802    }
12803    // Drop repository coordination before releasing the cache, reversing the
12804    // acquisition order. A cancelled/error future also drops both guards.
12805    drop(_coordination);
12806    if let Some(guard) = guard {
12807        guard.release();
12808    }
12809    Ok((outcomes, retried))
12810}
12811
12812/// Poll `pids` — commands [`run_commands`] reports as still running when its
12813/// own timeout elapsed — until every one is confirmed gone, or
12814/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12815///
12816/// Real confirmation where confirmation is possible, not a substitute for
12817/// full process-tree observation: a grandchild the timed-out process spawned
12818/// and that survives independently of it is invisible to a pid check the
12819/// same way it always was, and continuing to observe and collect *that*
12820/// stays a different piece of work with its own owner. This only narrows a
12821/// fixed blind wait into an actual check of the pids this process does know
12822/// about.
12823async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12824    wait_for_pids_with(
12825        pids,
12826        crate::proc::pid_alive,
12827        LEASE_RELEASE_POLL,
12828        LEASE_RELEASE_MAX_WAIT,
12829    )
12830    .await;
12831}
12832
12833/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12834/// interval and ceiling supplied by the caller, so the polling *logic* -
12835/// returns as soon as every pid reports dead, gives up at the ceiling
12836/// otherwise - is testable on millisecond durations without asking the real
12837/// OS about a pid at all.
12838async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12839    pids: &[u32],
12840    alive: F,
12841    poll: Duration,
12842    max_wait: Duration,
12843) {
12844    let deadline = Instant::now() + max_wait;
12845    loop {
12846        if pids.iter().all(|&pid| !alive(pid)) {
12847            return;
12848        }
12849        if Instant::now() >= deadline {
12850            return;
12851        }
12852        tokio::time::sleep(poll).await;
12853    }
12854}
12855
12856/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12857/// admission that it could not even get a verify command to run, as opposed
12858/// to evidence the command actually produced? A caller that would otherwise
12859/// read a resource-blocked outcome as a red command must check this first:
12860/// see [`Runner::gate`], which retries rather than records `Blocked` when
12861/// this is true.
12862fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12863    outcomes.iter().any(|o| o.resource_blocked)
12864}
12865
12866/// What [`Runner::gate_fix_round`] decided.
12867pub(crate) enum GateFix {
12868    /// The tree changed and `verify.e2e` is still green: run the gate again.
12869    Retry,
12870    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12871    /// last failure stands and the run ends blocked.
12872    Stop,
12873    /// `verify.e2e` could not run after the fix (magi's own contention):
12874    /// decide nothing now, a later reentry retries.
12875    Defer,
12876}
12877
12878/// Is every red command in `outcomes` an ordinary failure the code could
12879/// explain: it ran, exited non-zero, and said something?
12880///
12881/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12882/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12883/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12884/// what the command is stays the gate's business.
12885pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12886    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12887    red.peek().is_some()
12888        && red.all(|o| {
12889            !o.resource_blocked
12890                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12891                && !o.output_tail.trim().is_empty()
12892        })
12893}
12894
12895/// Describe one verify command's outcome for the event log, distinguishing a
12896/// build/link failure — the toolchain never produced a binary to run — from
12897/// an actual test failure, since only the latter is a verdict on the patch.
12898fn e2e_outcome_label(o: &CommandOutcome) -> String {
12899    if o.ok() {
12900        return "pass".to_owned();
12901    }
12902    let reason = if o.build_failed() {
12903        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12904    } else {
12905        format!("FAIL ({:?})", o.code)
12906    };
12907    format!(
12908        "{reason}\n{}",
12909        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12910    )
12911}
12912
12913/// Does `outcomes` hold a failure worth one more run on the same commit?
12914///
12915/// Only an ordinary test result qualifies: every red command ran, exited
12916/// non-zero and said which way (not a build/link failure, a timeout or kill,
12917/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12918/// evidence about the machine or the toolchain, never about a flaky test.
12919fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12920    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12921    red.peek().is_some()
12922        && !verify_inconclusive(outcomes)
12923        && red.all(|o| {
12924            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12925        })
12926}
12927
12928/// Run `verify.e2e`, retrying once if the first attempt could not build or
12929/// link — a build/link failure is frequently a race against a shared
12930/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12931/// `verify` event per command, tagged with `context` (normally `"round N"`)
12932/// so the call sites that need this — the ordinary per-round leg in
12933/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12934/// will ever call a round green, `verify_current_head` and the gate-repair
12935/// check — read identically in the event log.
12936///
12937/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12938/// only after the failed commands have run once more on the same commit, in
12939/// the same worktree and — because the caller holds it around this whole
12940/// function — under the same cache lease, with a full `timeout` of their own
12941/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12942/// flake: the head is verified, the first failure is recorded and filed
12943/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12944/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12945/// preserving bounded evidence and artifact references for both attempts;
12946/// it claims a matching reproduction only when both attempts yield identical
12947/// confirmed terminal test failures. One verification is therefore run at most
12948/// three times: the build/link retry, then this one rerun. `round` is the
12949/// review round the verification belongs to, if any.
12950async fn run_e2e_with_retry(
12951    state: &mut RunState,
12952    shell: &[String],
12953    commands: &[String],
12954    worktree: &Path,
12955    timeout: Duration,
12956    context: &str,
12957    round: Option<usize>,
12958) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12959    let (mut e2e, mut timed_out_pids) = run_commands(
12960        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12961    )
12962    .await;
12963    for o in &e2e {
12964        state.event(
12965            "verify",
12966            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12967        );
12968    }
12969    // A build/link failure is not a verdict on the patch — it is frequently a
12970    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12971    // one retry before letting a red like that decide the round.
12972    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12973    if verify_retried {
12974        state.event(
12975            "verify",
12976            format!(
12977                "{context}: verify could not build/link, not a test result — retrying once \
12978                 before concluding"
12979            ),
12980        );
12981        let retried = run_commands(
12982            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12983        )
12984        .await;
12985        e2e = retried.0;
12986        // Both attempts' timeouts matter, not just the last one: the first
12987        // attempt's descendants may still be alive alongside the retry's.
12988        timed_out_pids.extend(retried.1);
12989        for o in &e2e {
12990            state.event(
12991                "verify",
12992                format!(
12993                    "{context}: retry `{}` -> {}",
12994                    o.command,
12995                    e2e_outcome_label(o)
12996                ),
12997            );
12998        }
12999    }
13000    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13001        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13002        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13003        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13004        state.event(
13005            "verify",
13006            format!(
13007                "{context}: {} failed with a test result — running it once more on the same \
13008                 commit {} before deciding",
13009                rerun_commands
13010                    .iter()
13011                    .map(|c| format!("`{c}`"))
13012                    .collect::<Vec<_>>()
13013                    .join(", "),
13014                short(&head)
13015            ),
13016        );
13017        let (second, pids) = run_commands(
13018            state,
13019            "verify",
13020            "e2e",
13021            1 + usize::from(verify_retried),
13022            shell,
13023            &rerun_commands,
13024            worktree,
13025            timeout,
13026        )
13027        .await;
13028        timed_out_pids.extend(pids);
13029        for o in &second {
13030            state.event(
13031                "verify",
13032                format!(
13033                    "{context}: rerun `{}` -> {}",
13034                    o.command,
13035                    e2e_outcome_label(o)
13036                ),
13037            );
13038        }
13039        for (slot, &i) in failed.iter().enumerate() {
13040            let Some(again) = second.get(slot) else {
13041                break;
13042            };
13043            let first = std::mem::replace(&mut e2e[i], again.clone());
13044            if again.ok() {
13045                let signature = crate::flake::signature(&first.output_tail, first.code);
13046                let flake = crate::run::VerifyFlake {
13047                    round,
13048                    context: context.to_owned(),
13049                    head: head.clone(),
13050                    command: first.command.clone(),
13051                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13052                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13053                    at: Timestamp::now(),
13054                    task: None,
13055                    filed: false,
13056                    filing_error: None,
13057                };
13058                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13059            } else if !again.resource_blocked {
13060                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13061                let message = crate::verify_evidence::rerun_event_message(
13062                    context,
13063                    &e2e[i].command,
13064                    &comparison,
13065                );
13066                e2e[i].rerun_comparison = Some(comparison);
13067                state.event("verify", message);
13068            }
13069        }
13070    }
13071    (e2e, verify_retried, timed_out_pids)
13072}
13073
13074/// Run configured shell commands in `cwd`, in order. The second element is
13075/// the pid of every command that hit `timeout` and was still running when
13076/// this stopped waiting on it (best-effort: `None` when the platform did not
13077/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13078/// that releases a shared resource afterward needs to know.
13079///
13080/// Records `task` into [`RunState::active`] at every command boundary
13081/// (`RunState::task_command`) and clears it once the whole list has run
13082/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13083/// for minutes with no seat and no output of its own to show for it (see
13084/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13085/// apart from "not yet run" without this), and this is the only place that
13086/// knows which command is running right now and how many are left. Three
13087/// saves per command — start, not per second — matching the same "only at a
13088/// boundary" rule [`wave`] already follows for seats.
13089#[allow(clippy::too_many_arguments)]
13090async fn run_commands(
13091    state: &mut RunState,
13092    node: &str,
13093    task: &str,
13094    attempt: usize,
13095    shell: &[String],
13096    commands: &[String],
13097    cwd: &Path,
13098    timeout: Duration,
13099) -> (Vec<CommandOutcome>, Vec<u32>) {
13100    let isolated = crate::build_target::isolated(&state.config);
13101    if isolated && let Some(block) = &state.resource_block {
13102        return (
13103            vec![CommandOutcome {
13104                command: "(isolated build admission)".into(),
13105                code: None,
13106                output_tail: block.description(),
13107                duration_ms: 0,
13108                resource_blocked: true,
13109                ..Default::default()
13110            }],
13111            Vec::new(),
13112        );
13113    }
13114    if commands.is_empty() {
13115        // Nothing to mark as running and nothing to clear — an empty list
13116        // means "not configured", and touching `active` (or the disk) over
13117        // that would be a write for every round of a repo with no
13118        // `verify.e2e` / `verify.gate` commands at all.
13119        return (Vec::new(), Vec::new());
13120    }
13121    let mut out = Vec::new();
13122    let mut timed_out_pids = Vec::new();
13123    let total = commands.len();
13124    for (idx, command) in commands.iter().enumerate() {
13125        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13126        if let Err(e) = state.save() {
13127            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13128        }
13129        let started = Instant::now();
13130        let mut cmd = tokio::process::Command::new(&shell[0]);
13131        cmd.quiet();
13132        // Verify the checkout as a standalone caller. Worker ownership and
13133        // pinned executable selection belong to this driver, not to tests or
13134        // tools it runs. Preserve home/seat context and Running's containment.
13135        for key in crate::worker::INVOCATION_ENV {
13136            cmd.env_remove(key);
13137        }
13138        cmd.env_remove(crate::build_id::EXPECT_ENV);
13139        cmd.args(&shell[1..])
13140            .current_dir(cwd)
13141            .stdin(std::process::Stdio::null())
13142            .stdout(std::process::Stdio::piped())
13143            .stderr(std::process::Stdio::piped())
13144            .kill_on_drop(true);
13145        let mut outputs = Vec::new();
13146        let mut cache = None;
13147        let home = crate::run::home();
13148        let head = if isolated {
13149            Some(git::rev_parse(cwd, "HEAD").await)
13150        } else {
13151            None
13152        };
13153        let protected = (|| -> Result<()> {
13154            crate::incremental::configure(&mut cmd, cwd)?;
13155            cache = if isolated {
13156                let target = VERIFY_TARGET
13157                    .try_with(Clone::clone)
13158                    .context("isolated verification has no target lease")?;
13159                cmd.arg(crate::build_target::command::normalize(command)?);
13160                crate::build_target::command::configure(&mut cmd, &target)?;
13161                Some(target)
13162            } else {
13163                crate::build_target::command::clear(&mut cmd)?;
13164                cmd.arg(command);
13165                state.config.cache_dir()
13166            };
13167            let mut paths = vec![cwd.to_owned()];
13168            if let Some(cache) = &cache {
13169                paths.push(cache.clone());
13170            }
13171            let admit = if isolated {
13172                crate::retention::OutputLease::admit_isolated
13173            } else {
13174                crate::retention::OutputLease::admit
13175            };
13176            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13177            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13178                outputs.push(guard);
13179            }
13180            if let Some(cache) = &cache {
13181                outputs.push(crate::retention::OutputLease::cache(
13182                    &crate::run::home(),
13183                    cache,
13184                    false,
13185                )?);
13186                if let Some(head) = head {
13187                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13188                    if task == "pre_gate" {
13189                        crate::cache::invalidate_identity(&home, cache);
13190                    }
13191                }
13192            }
13193            Ok(())
13194        })();
13195        if let Err(e) = protected {
13196            let detail = format!("execution admission unavailable: {e:#}");
13197            state.resource_block = Some(crate::run::ResourceBlock {
13198                cause: crate::run::ResourceBlockCause::Other,
13199                node: node.to_owned(),
13200                kind: if detail.contains("disk admission") {
13201                    "disk admission"
13202                } else {
13203                    "output ownership"
13204                }
13205                .to_owned(),
13206                detail: detail.clone(),
13207                at: Timestamp::now(),
13208            });
13209            out.push(CommandOutcome {
13210                command: command.clone(),
13211                code: None,
13212                output_tail: detail,
13213                duration_ms: 0,
13214                resource_blocked: true,
13215                ..Default::default()
13216            });
13217            break;
13218        }
13219        let spawned = if isolated {
13220            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13221        } else {
13222            crate::seat_process::Running::spawn(cmd, None, outputs)
13223        };
13224        let (code, out_text, err_text, body) = match spawned {
13225            Ok(mut running) => {
13226                let pid = running.child().id();
13227                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13228                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13229                let mut paths = vec![cwd.to_owned()];
13230                if let Some(cache) = cache {
13231                    paths.push(cache);
13232                }
13233                let mut pressure = None;
13234                let status = tokio::select! {
13235                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13236                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13237                        pressure = Some(reason); None
13238                    }
13239                };
13240                let (code, failure) = match status {
13241                    Some(Ok(Ok(status))) => (
13242                        status.code(),
13243                        status
13244                            .code()
13245                            .is_none()
13246                            .then(|| format!("command terminated: {status}")),
13247                    ),
13248                    Some(Ok(Err(error))) => {
13249                        (None, Some(format!("failed waiting for command: {error}")))
13250                    }
13251                    Some(Err(_)) => {
13252                        // Leased cleanup confirms process-tree death itself.
13253                        // Unleased commands still need the caller's PID check
13254                        // after kill-on-drop, before releasing cache ownership.
13255                        if !running.coordinated()
13256                            && let Some(pid) = pid
13257                        {
13258                            timed_out_pids.push(pid);
13259                        }
13260                        (
13261                            None,
13262                            Some(format!("timed out after {}s", timeout.as_secs())),
13263                        )
13264                    }
13265                    None => (None, None),
13266                };
13267                running.finish().await;
13268                if let Some(reason) = pressure {
13269                    state.resource_block = Some(crate::run::ResourceBlock {
13270                        cause: crate::run::ResourceBlockCause::Other,
13271                        node: node.to_owned(),
13272                        kind: "disk pressure".to_owned(),
13273                        detail: reason.clone(),
13274                        at: Timestamp::now(),
13275                    });
13276                    out.push(CommandOutcome {
13277                        command: command.clone(),
13278                        code: None,
13279                        output_tail: reason,
13280                        duration_ms: started.elapsed().as_millis() as u64,
13281                        resource_blocked: true,
13282                        ..Default::default()
13283                    });
13284                    break;
13285                }
13286                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13287                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13288                let mut body = out_text.clone();
13289                body.push_str(&err_text);
13290                if let Some(failure) = failure {
13291                    body.push('\n');
13292                    body.push_str(&failure);
13293                }
13294                (code, out_text, err_text, body)
13295            }
13296            Err(e) if isolated => {
13297                let e = anyhow::Error::new(e)
13298                    .context(format!("could not start managed build `{}`", shell[0]));
13299                record_cache_error(state, node, &e);
13300                out.push(CommandOutcome {
13301                    command: command.clone(),
13302                    code: None,
13303                    output_tail: format!("{e:#}"),
13304                    duration_ms: 0,
13305                    resource_blocked: true,
13306                    ..Default::default()
13307                });
13308                break;
13309            }
13310            Err(e) => (
13311                None,
13312                String::new(),
13313                String::new(),
13314                format!("failed to spawn `{}`: {e}", shell[0]),
13315            ),
13316        };
13317        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13318        let mut artifact = None;
13319        if !body.is_empty() {
13320            // The full text is kept whatever the summary dropped. A fresh
13321            // name per command so a resume or retry never overwrites an
13322            // earlier run's output. A failed write changes no verdict.
13323            match crate::run::write_verification_artifact(state, task, &body) {
13324                Ok(name) => {
13325                    let rel = format!("artifacts/{name}");
13326                    if summary != body {
13327                        summary = format!("[full output: {rel}]\n{summary}");
13328                    }
13329                    artifact = Some(rel);
13330                }
13331                Err(e) => {
13332                    let warning = format!("could not save the full {task} output: {e:#}");
13333                    tracing::warn!("{warning}");
13334                    state.event(node, warning);
13335                    if summary != body {
13336                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13337                    }
13338                }
13339            }
13340        }
13341        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13342        let mut outcome = CommandOutcome {
13343            command: command.clone(),
13344            code,
13345            output_tail: summary,
13346            duration_ms: started.elapsed().as_millis() as u64,
13347            resource_blocked,
13348            artifact,
13349            failure_evidence: None,
13350            rerun_comparison: None,
13351        };
13352        if !outcome.ok() && !outcome.resource_blocked {
13353            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13354                code,
13355                outcome.build_failed(),
13356                &out_text,
13357                &err_text,
13358            ));
13359        }
13360        out.push(outcome);
13361        if resource_blocked {
13362            state.resource_block = Some(crate::run::ResourceBlock {
13363                cause: crate::run::ResourceBlockCause::Other,
13364                node: node.to_owned(),
13365                kind: "incremental cache admission".into(),
13366                detail: body,
13367                at: Timestamp::now(),
13368            });
13369            break;
13370        }
13371    }
13372    state.task_finished(task);
13373    if let Err(e) = state.save() {
13374        tracing::warn!("could not persist the end of {task}: {e:#}");
13375    }
13376    (out, timed_out_pids)
13377}
13378
13379/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13380/// section (`report::run`) and in the `merge` event this node records — for
13381/// the operator to run by hand.
13382///
13383/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13384/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13385/// merge commits", or "require linear history") rejects the push a `--no-ff`
13386/// merge would produce, which is exactly the guidance this function replaces.
13387/// `message`'s first line becomes the squash commit's subject, matching the
13388/// note `report::run` prints alongside this command — see that function for
13389/// why an explicit subject is not optional there.
13390fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13391    let repo = repo.display();
13392    match style {
13393        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13394        MergeStyle::Squash => {
13395            // The subject sits inside double quotes, and a title an agent
13396            // wrote may carry the characters that break out of them.
13397            let subject = message
13398                .lines()
13399                .next()
13400                .unwrap_or(branch)
13401                .replace(['\\', '"', '$', '`'], "");
13402            format!(
13403                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13404            )
13405        }
13406        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13407    }
13408}
13409
13410/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13411/// under the hood, rejects a `title` over 256 characters and the whole
13412/// command fails — no PR at all, for a run whose body was otherwise fine
13413/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13414/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13415/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13416/// this bound. It is a margin, not a guarantee — a title packed
13417/// with multi-unit characters could still in principle land close to the
13418/// edge, but a real task title's occasional emoji or accented letter fits
13419/// comfortably inside it.
13420const PR_TITLE_MAX: usize = 240;
13421
13422/// A pull request title from the opening line of `text`, or `None` when that
13423/// line is not English (GitHub text is) or has no letters.
13424///
13425/// A line within `max` is kept as is. A longer one is cut at the end of its
13426/// first sentence when that falls inside `max`, else at a word boundary with a
13427/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13428/// make every merely-truncated title look non-English). The language check
13429/// runs on the kept text before any mark is added, so only what GitHub will
13430/// show is judged: an English opening followed by non-ASCII far past the cut
13431/// still passes.
13432fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13433    let line = queue::first_line(text)?;
13434    let chars: Vec<char> = line.chars().collect();
13435    let (kept, mark) = if chars.len() <= max {
13436        (line.to_owned(), "")
13437    } else if let Some(end) = sentence_end(&chars, max) {
13438        (chars[..end].iter().collect::<String>(), "")
13439    } else {
13440        let room = max.saturating_sub(3);
13441        // Cut at the last space inside the room; when the char just past the
13442        // room is a space the room already ends on a word.
13443        let cut = if chars[room].is_whitespace() {
13444            room
13445        } else {
13446            chars[..room]
13447                .iter()
13448                .rposition(|c| c.is_whitespace())
13449                .unwrap_or(room)
13450        };
13451        let head: String = chars[..cut].iter().collect();
13452        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13453        (head.to_owned(), "...")
13454    };
13455    if kept.is_empty() {
13456        return None;
13457    }
13458    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13459        return None;
13460    }
13461    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13462        return None;
13463    }
13464    Some(format!("{kept}{mark}"))
13465}
13466
13467/// The char length of the first sentence of `chars` when it ends within `max`
13468/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13469/// abbreviations so `e.g. foo` does not end a title early.
13470fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13471    const MIN: usize = 20;
13472    for i in MIN..max.min(chars.len()) {
13473        if !matches!(chars[i], '.' | '!' | '?') {
13474            continue;
13475        }
13476        let Some(&next) = chars.get(i + 1) else {
13477            continue;
13478        };
13479        if !next.is_whitespace() {
13480            continue;
13481        }
13482        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13483        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13484            continue;
13485        }
13486        let word: String = chars[..i]
13487            .iter()
13488            .rev()
13489            .take_while(|c| !c.is_whitespace())
13490            .collect::<Vec<_>>()
13491            .into_iter()
13492            .rev()
13493            .collect();
13494        let word = word.to_ascii_lowercase();
13495        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13496            continue;
13497        }
13498        let end = chars[..i]
13499            .iter()
13500            .rposition(|c| !c.is_whitespace())
13501            .map_or(i, |p| p + 1);
13502        return Some(end);
13503    }
13504    None
13505}
13506
13507/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13508/// change: a title and a body describing what was *implemented*, not the task
13509/// that asked for it. A task reads as a request; a reader of the merged
13510/// history wants the change.
13511struct PrMessage {
13512    title: String,
13513    body: String,
13514}
13515
13516impl PrMessage {
13517    /// Title, blank line, body. The first line is the squash/merge commit
13518    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13519    /// has to stay one sensible line.
13520    fn commit_message(&self) -> String {
13521        format!("{}\n\n{}", self.title, self.body)
13522    }
13523}
13524
13525/// The text after a leading `TITLE:` (any case) on `line`.
13526fn title_marker(line: &str) -> Option<&str> {
13527    let line = line.trim();
13528    let head = line.get(..6)?;
13529    head.eq_ignore_ascii_case("title:")
13530        .then(|| line[6..].trim())
13531}
13532
13533/// The implementer's own one-line title: the `TITLE:` line the implement
13534/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13535/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13536/// source, and a title that says as much is refused here too.
13537fn summary_title(summary: &str) -> Option<String> {
13538    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13539    let raw = title_marker(first)?;
13540    if raw.is_empty() {
13541        return None;
13542    }
13543    let title = queue::title_from(raw, PR_TITLE_MAX);
13544    let lower = title.to_ascii_lowercase();
13545    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13546        return None;
13547    }
13548    Some(title)
13549}
13550
13551/// How `open_review`'s instruction begins; see [`landing_title`].
13552const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13553
13554/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13555pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13556
13557/// Does this run review work that already existed, rather than implement a
13558/// task? Runs recorded before `reviewed_commits` existed carry only the
13559/// candidate marker.
13560pub(crate) fn is_review_run(state: &RunState) -> bool {
13561    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13562}
13563
13564/// The title of a review-only run: the subject of the oldest commit under
13565/// review. Later commits are usually fixups, and `instruction` is the review
13566/// prompt, which says nothing about the change. GitHub text is English, so a
13567/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13568fn review_title(state: &RunState) -> Option<String> {
13569    english_subject(
13570        state.reviewed_commits.as_ref()?.first()?,
13571        state.config.graph.github_english(),
13572    )
13573}
13574
13575/// `raw` as a pull request title, or `None` when it is blank, not English
13576/// (GitHub text is), or one of magi's own candidate commit subjects.
13577fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13578    let raw = raw.trim();
13579    if raw.is_empty() {
13580        return None;
13581    }
13582    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13583        return None;
13584    }
13585    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13586        return None;
13587    }
13588    let title = queue::title_from(raw, PR_TITLE_MAX);
13589    let lower = title.to_ascii_lowercase();
13590    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13591        return None;
13592    }
13593    Some(title)
13594}
13595
13596/// What a review-only run's branch says about itself, read at the moment the
13597/// pull request is opened.
13598#[derive(Debug, Clone, PartialEq, Eq)]
13599struct BranchFacts {
13600    /// `(subject, body)` of each commit, oldest first.
13601    commits: Vec<(String, String)>,
13602    /// Trimmed `git diff --stat`.
13603    stat: String,
13604}
13605
13606/// Longest diff stat shown: this many file lines plus the summary line.
13607const STAT_FILE_LINES: usize = 25;
13608/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13609const COMMITS_MAX_CHARS: usize = 20_000;
13610
13611/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13612/// say or finds nothing, so the caller falls back to what the run recorded.
13613async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13614    let commits = git::commit_log(repo, base, branch).await.ok()?;
13615    if commits.is_empty() {
13616        return None;
13617    }
13618    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13619    let lines: Vec<&str> = stat.lines().collect();
13620    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13621        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13622        let more = format!(" ... {omitted} more file(s)");
13623        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13624        kept.push(&more);
13625        kept.push(lines[lines.len() - 1]);
13626        kept.join("\n")
13627    } else {
13628        lines.join("\n")
13629    };
13630    Some(BranchFacts { commits, stat })
13631}
13632
13633/// Defang what would break the surrounding markdown: a closing `</details>`
13634/// and a code fence.
13635fn markdown_safe(text: &str) -> String {
13636    text.replace("</details>", "&lt;/details&gt;")
13637        .replace("\x60\x60\x60", "~~~")
13638}
13639
13640fn neutral_title(state: &RunState, winner: char) -> String {
13641    format!(
13642        "chore: land candidate {} of run {}",
13643        winner.to_ascii_uppercase(),
13644        state.id
13645    )
13646}
13647
13648/// Reuse the graph's bounded fixer without starting another graph or driver.
13649/// Copy the working state back even on errors so spent rounds remain visible.
13650pub(crate) async fn repair_landing_gate(
13651    state: &mut RunState,
13652    winner: &Candidate,
13653    outcomes: &[CommandOutcome],
13654) -> Result<GateFix> {
13655    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13656        return Ok(GateFix::Stop);
13657    }
13658    let mut runner = Runner {
13659        roles: state.config.resolve_roles()?,
13660        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13661        state: state.clone(),
13662        pause: Pause::new(),
13663        interrupt: Pause::new(),
13664    };
13665    let result = runner.gate_fix_round(winner, outcomes).await;
13666    *state = runner.state;
13667    result
13668}
13669
13670/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13671/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13672pub(crate) async fn verify_current_head(
13673    state: &mut RunState,
13674    winner: &Candidate,
13675    wait: &crate::repo_lock::WaitPolicy,
13676) -> Result<bool> {
13677    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13678    // Preserve the previous record before replacing it, including on crash recovery.
13679    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13680        state
13681            .verification_history
13682            .push(crate::run::VerificationEvidence {
13683                superseded_by: Some(head.clone()),
13684                archived_at: Some(Timestamp::now()),
13685                fixes_spent: Some(state.gate_fixes.len()),
13686                gate_head: None,
13687                gate_ran: false,
13688                gate: Vec::new(),
13689                e2e: state.head_e2e.take(),
13690            });
13691    }
13692    if let Some(e) = &state.head_e2e
13693        && e.head == head
13694    {
13695        if e.passed {
13696            return Ok(true);
13697        }
13698        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13699            state.status = RunStatus::Blocked;
13700            state.save()?;
13701            return Ok(false);
13702        }
13703    } else if state.reviews.last().is_some_and(|r| {
13704        r.verified_head.as_deref() == Some(head.as_str())
13705            && (r.e2e_status() == E2eStatus::Passed
13706                || (r.e2e_status() == E2eStatus::NotConfigured
13707                    && state.config.verify.e2e.is_empty()))
13708    }) || state
13709        .gate_repair_e2e
13710        .as_ref()
13711        .is_some_and(|e| e.head == head && e.passed)
13712    {
13713        return Ok(true);
13714    }
13715    if let Some(e) = &state.gate_repair_e2e
13716        && e.head == head
13717        && !e.passed
13718        && !e.outcomes.is_empty()
13719        && !verify_inconclusive(&e.outcomes)
13720    {
13721        state.status = RunStatus::Blocked;
13722        state.save()?;
13723        return Ok(false);
13724    }
13725    // Bind the result to the base used by the candidate, not a tracking ref
13726    // that the background fetch can advance independently of verification.
13727    let base_commit = state
13728        .base_sync
13729        .as_ref()
13730        .map(|s| s.tip.clone())
13731        .filter(|tip| !tip.is_empty())
13732        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13733    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13734        head.clone(),
13735        false,
13736        Vec::new(),
13737    ));
13738    state.save()?;
13739    let commands = state.config.verify.e2e.clone();
13740    let shell = state.config.shell();
13741    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13742    let cache_dir = state.config.cache_dir();
13743    let outcomes = if commands.is_empty() {
13744        Vec::new()
13745    } else {
13746        let (outcomes, _) = with_cache_lease(
13747            state,
13748            cache_dir.as_deref(),
13749            "e2e",
13750            "e2e",
13751            &winner.worktree,
13752            &head,
13753            timeout,
13754            "current head e2e",
13755            wait,
13756            |state, budget| async move {
13757                run_e2e_with_retry(
13758                    state,
13759                    &shell,
13760                    &commands,
13761                    &winner.worktree,
13762                    budget,
13763                    "current head e2e",
13764                    None,
13765                )
13766                .await
13767            },
13768        )
13769        .await?;
13770        outcomes
13771    };
13772    let unresolved = verify_inconclusive(&outcomes);
13773    let passed = !unresolved
13774        && outcomes.iter().all(CommandOutcome::ok)
13775        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13776    if !outcomes.is_empty() && !unresolved {
13777        state.record_base_progress(&head);
13778    }
13779    let generation = Some(state.verification_history.len());
13780    let pass = state.passes.last().map(|p| p.index);
13781    let recorded_at = Some(Timestamp::now());
13782    let resumption_generation = state.entry_resumption_generation;
13783    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13784    record.base_commit = base_commit;
13785    record.generation = generation;
13786    record.pass = pass;
13787    record.recorded_at = recorded_at;
13788    record.resumption_generation = resumption_generation;
13789    if !passed && !unresolved {
13790        let detail = state
13791            .head_e2e
13792            .as_ref()
13793            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13794            .map(|d| format!(" ({d})"))
13795            .unwrap_or_default();
13796        state.status = RunStatus::Blocked;
13797        state.event(
13798            "e2e",
13799            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13800        );
13801        record.recorded_events = Some(state.events.len());
13802    }
13803    state.head_e2e = Some(record);
13804    state.save()?;
13805    Ok(passed)
13806}
13807
13808/// Recheck a repair's e2e requirement across failures, resource deferrals and
13809/// process interruptions. A successful result only applies to its exact SHA.
13810pub(crate) async fn check_gate_repair_e2e(
13811    state: &mut RunState,
13812    winner: &Candidate,
13813    wait: &crate::repo_lock::WaitPolicy,
13814) -> Result<GateFix> {
13815    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13816        return Ok(GateFix::Retry);
13817    }
13818    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13819    if let Some(record) = &state.gate_repair_e2e
13820        && record.head == head
13821    {
13822        if record.passed {
13823            return Ok(GateFix::Retry);
13824        }
13825        if !record.outcomes.is_empty()
13826            && record.outcomes.iter().all(|o| {
13827                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13828            })
13829        {
13830            return Ok(GateFix::Stop);
13831        }
13832    }
13833    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13834        head.clone(),
13835        false,
13836        Vec::new(),
13837    ));
13838    state.save()?;
13839    let commands = state.config.verify.e2e.clone();
13840    let outcomes = if commands.is_empty() {
13841        Vec::new()
13842    } else {
13843        let shell = state.config.shell();
13844        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13845        let cache_dir = state.config.cache_dir();
13846        let (outcomes, _) = with_cache_lease(
13847            state,
13848            cache_dir.as_deref(),
13849            "e2e",
13850            "e2e",
13851            &winner.worktree,
13852            &head,
13853            timeout,
13854            "gate repair e2e",
13855            wait,
13856            |state, budget| async move {
13857                run_e2e_with_retry(
13858                    state,
13859                    &shell,
13860                    &commands,
13861                    &winner.worktree,
13862                    budget,
13863                    "gate repair e2e",
13864                    None,
13865                )
13866                .await
13867            },
13868        )
13869        .await?;
13870        outcomes
13871    };
13872    let deferred = verify_inconclusive(&outcomes);
13873    let passed = outcomes.iter().all(CommandOutcome::ok)
13874        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13875    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
13876    state.save()?;
13877    if deferred {
13878        Ok(GateFix::Defer)
13879    } else if !passed {
13880        let detail = state
13881            .gate_repair_e2e
13882            .as_ref()
13883            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13884            .map(|d| format!(" ({d})"))
13885            .unwrap_or_default();
13886        state.event(
13887            "gate",
13888            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13889        );
13890        Ok(GateFix::Stop)
13891    } else {
13892        Ok(GateFix::Retry)
13893    }
13894}
13895
13896/// Run the same configured gate for a landing head and a fresh graph.
13897pub(crate) async fn run_landing_gate(
13898    state: &mut RunState,
13899    winner: &Candidate,
13900    wait: &crate::repo_lock::WaitPolicy,
13901) -> Result<Vec<CommandOutcome>> {
13902    let shell = state.config.shell();
13903    let gate_commands = state.config.verify.gate.clone();
13904    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13905    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13906        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13907        Vec::new()
13908    } else {
13909        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13910        let cache_dir = state.config.cache_dir();
13911        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13912        let (outcomes, _) = with_cache_lease(
13913            state,
13914            cache_dir.as_deref(),
13915            "gate",
13916            "gate",
13917            &winner.worktree,
13918            &head,
13919            timeout,
13920            "final gate",
13921            wait,
13922            |state, budget| {
13923                let shell = shell.clone();
13924                let gate_commands = gate_commands.clone();
13925                let winner = winner.clone();
13926                async move {
13927                    Runner::run_pre_gate(state, &winner).await;
13928                    // Bind command evidence after mechanical fixes, before commands start.
13929                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13930                    let (outcomes, timed_out_pids) = run_commands(
13931                        state,
13932                        "gate",
13933                        "gate",
13934                        0,
13935                        &shell,
13936                        &gate_commands,
13937                        &winner.worktree,
13938                        budget,
13939                    )
13940                    .await;
13941                    (outcomes, false, timed_out_pids)
13942                }
13943            },
13944        )
13945        .await?;
13946        outcomes
13947    };
13948    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13949    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13950        let mut outcomes = outcomes;
13951        outcomes.push(CommandOutcome {
13952            command: "gate head stability".into(), code: None,
13953            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13954            duration_ms: 0, resource_blocked: false,
13955            ..Default::default()
13956        });
13957        return Ok(outcomes);
13958    }
13959    if outcomes.is_empty() {
13960        // Nothing configured to check — distinct from every other
13961        // silence in this run's event log, since an empty `gate` alone
13962        // no longer says whether the gate ran at all (see
13963        // `RunState::gate_ran`'s own doc).
13964        state.event("gate", "no gate commands configured; not tested");
13965    }
13966    for o in &outcomes {
13967        state.event(
13968            "gate",
13969            format!(
13970                "`{}` -> {}",
13971                o.command,
13972                if o.ok() {
13973                    "pass".to_owned()
13974                } else {
13975                    format!(
13976                        "FAIL ({:?})\n{}",
13977                        o.code,
13978                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13979                    )
13980                }
13981            ),
13982        );
13983    }
13984    Ok(outcomes)
13985}
13986
13987/// The pull request title to hand to `land::merge_subject`. A review-only run
13988/// opened by an earlier build titled its pull request with the review prompt;
13989/// that title is dropped (empty, so the fallback applies) rather than landed.
13990/// Any other title, including an operator's rename, passes through untouched,
13991/// and so does every title of a run that implements a task.
13992pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13993    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13994        ""
13995    } else {
13996        pr_title
13997    }
13998}
13999
14000/// What the squash subject falls back to when the pull request title is empty
14001/// or candidate-shaped: for a review-only run the derived title, never the
14002/// review prompt held in `instruction`.
14003pub fn landing_subject_source(state: &RunState) -> String {
14004    if is_review_run(state) {
14005        let winner = state.candidates.first().map_or('A', |c| c.label);
14006        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14007    }
14008    state.instruction.clone()
14009}
14010
14011/// `summary` without its `TITLE:` line, which the pull request title already
14012/// carries.
14013fn summary_without_title(summary: &str) -> String {
14014    let mut lines = summary.trim().lines().peekable();
14015    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14016        lines.next();
14017    }
14018    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14019}
14020
14021/// The pull request title and body for the winning candidate.
14022///
14023/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14024/// the task's own opening line via [`queue::title_from`] when there is none.
14025/// `state.instruction` can open with blank lines (`task_text` only rejects a
14026/// body that is blank *entirely*), which `title_from` skips.
14027///
14028/// Publishing uses an independent description generated from the final diff
14029/// and structured evidence. Internal summaries and reports remain local.
14030/// Non-publishing previews may display the original task and candidate summary.
14031/// The footer retains the run and candidate provenance.
14032#[cfg(test)]
14033fn pr_message(state: &RunState, winner: char) -> PrMessage {
14034    pr_message_with(state, winner, None)
14035}
14036
14037/// [`pr_message`] with what the branch of a review-only run says about itself.
14038/// `facts` is ignored for a run that implements a task.
14039#[cfg(test)]
14040fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14041    let raw = pr_message_raw(
14042        state,
14043        winner,
14044        facts,
14045        crate::pr_outcome::FinalHead::Unreported,
14046        ChangeNote::NotAsked,
14047    );
14048    let id = crate::scrub::Identity::current();
14049    PrMessage {
14050        title: crate::scrub::scrub(&raw.title, &id),
14051        body: crate::scrub::scrub(&raw.body, &id),
14052    }
14053}
14054
14055/// What the public description may say about the change itself.
14056#[derive(Debug, Clone, Copy)]
14057enum ChangeNote<'a> {
14058    /// A local preview or non-publishing merge mode: no public generation needed.
14059    NotAsked,
14060    /// A summary written from the final diff.
14061    Summary(&'a crate::run::ChangeSummary),
14062    /// A summary was asked for and could not be produced; the text says why.
14063    Unavailable(&'a str),
14064}
14065
14066fn pr_message_raw(
14067    state: &RunState,
14068    winner: char,
14069    facts: Option<&BranchFacts>,
14070    head: crate::pr_outcome::FinalHead<'_>,
14071    change: ChangeNote<'_>,
14072) -> PrMessage {
14073    if !matches!(change, ChangeNote::NotAsked) {
14074        let (title, mut body) = match change {
14075            ChangeNote::Summary(c) => (
14076                c.title.clone(),
14077                format!("## Summary\n\n{}\n\n", c.body.trim()),
14078            ),
14079            ChangeNote::Unavailable(why) => (
14080                neutral_title(state, winner),
14081                format!(
14082                    "## 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"
14083                ),
14084            ),
14085            ChangeNote::NotAsked => unreachable!(),
14086        };
14087        body.push_str(&public_pr_evidence(state, head));
14088        body.push_str(&format!(
14089            "\n---\nmagi:run/{} magi:candidate-{}\n",
14090            state.id,
14091            winner.to_ascii_lowercase()
14092        ));
14093        return PrMessage { title, body };
14094    }
14095    pr_preview(state, winner, facts, head)
14096}
14097
14098/// Append public facts from the run records after every prose generation,
14099/// including posting-gate rewrites. The agent cannot drop this provenance.
14100fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14101    let mut body = crate::pr_outcome::review_rounds(state);
14102    body.push_str(&crate::pr_outcome::final_verification(state, head));
14103    let open = state.last_round_findings();
14104    if !open.is_empty() {
14105        body.push_str("## Open review findings\n\n");
14106        for f in open {
14107            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14108        }
14109        body.push('\n');
14110    }
14111    if let Some(c) = state.change_summary.as_ref()
14112        && head == crate::pr_outcome::FinalHead::At(&c.head)
14113    {
14114        body.push_str(&format!(
14115            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14116            c.base, c.head
14117        ));
14118    }
14119    body
14120}
14121
14122/// Local-only preview of the operator's task and candidate summary.
14123fn pr_preview(
14124    state: &RunState,
14125    winner: char,
14126    facts: Option<&BranchFacts>,
14127    head: crate::pr_outcome::FinalHead<'_>,
14128) -> PrMessage {
14129    let summary = state
14130        .candidates
14131        .iter()
14132        .find(|c| c.label == winner)
14133        .map(|c| c.summary.as_str())
14134        .unwrap_or_default();
14135    // The fallback is the operator's own words and may not be English; GitHub
14136    // text always is, so a non-English task gets a neutral title instead.
14137    let review = is_review_run(state);
14138    let title = if review {
14139        facts
14140            .and_then(|f| {
14141                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14142            })
14143            .or_else(|| review_title(state))
14144            .or_else(|| {
14145                state
14146                    .candidates
14147                    .iter()
14148                    .find(|c| c.label == winner)
14149                    .filter(|c| !c.branch.starts_with("magi/"))
14150                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14151            })
14152            .unwrap_or_else(|| neutral_title(state, winner))
14153    } else {
14154        summary_title(summary).unwrap_or_else(|| {
14155            english_title(
14156                &state.instruction,
14157                PR_TITLE_MAX,
14158                state.config.graph.github_english(),
14159            )
14160            .unwrap_or_else(|| neutral_title(state, winner))
14161        })
14162    };
14163
14164    let mut body = String::new();
14165    let what = summary_without_title(summary);
14166    if !what.is_empty() {
14167        body.push_str("## Summary\n\n");
14168        body.push_str(&what);
14169        body.push_str("\n\n");
14170    }
14171
14172    // Review history uses structured facts across all rounds, never reports.
14173    body.push_str(&crate::pr_outcome::review_rounds(state));
14174    body.push_str(&crate::pr_outcome::final_verification(state, head));
14175    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14176
14177    let open = state.open_findings();
14178    if !open.is_empty() {
14179        body.push_str("## Open review findings\n\n");
14180        for f in &open {
14181            body.push_str(&format!(
14182                "- `{}` [{:?}] {}\n",
14183                f.id, f.severity, "Context retained in local review records."
14184            ));
14185        }
14186        body.push('\n');
14187    }
14188
14189    if let Some(fix) = fix
14190        && !fix.rejected.is_empty()
14191    {
14192        body.push_str("## Declined by the fixer\n\n");
14193        for r in &fix.rejected {
14194            body.push_str(&format!(
14195                "- `{}`: {}\n",
14196                r.id, "Reason retained in local review records."
14197            ));
14198        }
14199        body.push('\n');
14200    }
14201
14202    if review {
14203        // The review prompt is not the task; list what the branch carries.
14204        body.push_str("## Commits under review\n\n");
14205        if let Some(facts) = facts {
14206            let mut left = COMMITS_MAX_CHARS;
14207            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14208                let mut entry = format!("- {}\n", markdown_safe(subject));
14209                for l in markdown_safe(text).lines() {
14210                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14211                }
14212                if left == 0 {
14213                    body.push_str(&format!(
14214                        "- ... {} more commit(s)\n",
14215                        facts.commits.len() - i
14216                    ));
14217                    break;
14218                }
14219                if entry.len() > left {
14220                    // Even the first commit is cut: one huge body must not
14221                    // push the whole description past GitHub's limit.
14222                    let mut end = left;
14223                    while !entry.is_char_boundary(end) {
14224                        end -= 1;
14225                    }
14226                    entry.truncate(end);
14227                    entry.push_str("\n  ... (truncated)\n");
14228                    left = 0;
14229                } else {
14230                    left -= entry.len();
14231                }
14232                body.push_str(&entry);
14233            }
14234            if !facts.stat.trim().is_empty() {
14235                body.push_str(&format!(
14236                    "\n## Diff stat\n\n```\n{}\n```\n",
14237                    markdown_safe(facts.stat.trim())
14238                ));
14239            }
14240        } else {
14241            match &state.reviewed_commits {
14242                Some(subjects) => {
14243                    for s in subjects {
14244                        body.push_str(&format!("- {}\n", s.trim()));
14245                    }
14246                }
14247                None => {
14248                    // An older run kept only the prompt, with the commit list
14249                    // after its first paragraph.
14250                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14251                    body.push_str(rest.trim());
14252                    body.push('\n');
14253                }
14254            }
14255        }
14256    } else {
14257        let task = state.instruction.trim();
14258        let task = if task.is_empty() {
14259            "(empty task)"
14260        } else {
14261            task
14262        };
14263        body.push_str(&format!(
14264            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14265            task.replace("</details>", "&lt;/details&gt;")
14266        ));
14267    }
14268
14269    body.push_str(&format!(
14270        "\n---\nmagi:run/{} magi:candidate-{}\n",
14271        state.id,
14272        winner.to_ascii_lowercase()
14273    ));
14274
14275    PrMessage { title, body }
14276}
14277
14278/// Source imports have already been prepared from structured inputs. Legacy
14279/// inferred references must never instruct a seat to reconstruct those imports.
14280fn seeded_instruction(state: &RunState) -> String {
14281    let mut inputs = Vec::new();
14282    if let Some(start) = &state.sources.start_from {
14283        inputs.push(format!(
14284            "Start from `{}` at `{}` (including ancestry).",
14285            start.token, start.sha
14286        ));
14287    }
14288    for pick in &state.sources.pick_commits {
14289        inputs.push(format!(
14290            "Pick `{}` at `{}` (single commit).",
14291            pick.token, pick.sha
14292        ));
14293    }
14294    if inputs.is_empty() {
14295        state.instruction.clone()
14296    } else {
14297        format!(
14298            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14299            state.instruction,
14300            inputs.join("\n")
14301        )
14302    }
14303}
14304
14305/// Does the winner have no commits ahead of the base it would land on?
14306/// Any failure to find out reads as "not empty": the merge then behaves as it
14307/// always did rather than refusing on a guess.
14308async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14309    let base = &state.base_branch;
14310    let mut against = base.clone();
14311    if mode == MergeMode::Pr {
14312        // A pull request lands on the remote's base, never the local branch
14313        // of the same name: if that cannot be read, "not empty" is the safe
14314        // answer.
14315        let remote = &state.config.merge.remote;
14316        let tracking = format!("{remote}/{base}");
14317        let fetched = git::fetch(repo, remote, base).await;
14318        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14319            against = tracking;
14320        } else {
14321            return false;
14322        }
14323    }
14324    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14325}
14326
14327/// Why nothing was opened for an empty winner, with what the task's own
14328/// references resolved to.
14329fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14330    let mut detail = format!(
14331        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14332         nothing to open a pull request for"
14333    );
14334    detail.push_str(
14335        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14336    );
14337    detail
14338}
14339
14340/// What the `Pr` merge does once it knows whether the branch already has an
14341/// open pull request.
14342#[derive(Debug, PartialEq, Eq)]
14343enum PrPlan {
14344    Create,
14345    Adopt { url: String, title: String },
14346    Stop(String),
14347}
14348
14349/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14350/// a failed lookup -> stop with the real reason. Never guesses.
14351fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14352    match found {
14353        Ok(land::OpenPr::None) => PrPlan::Create,
14354        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14355        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14356            "several open pull requests exist for this branch, not picking one: {}",
14357            urls.join(" ")
14358        )),
14359        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14360    }
14361}
14362
14363/// `gh pr create`, returning the PR url.
14364pub(crate) async fn gh_pr_create(
14365    cwd: &Path,
14366    base: &str,
14367    head: &str,
14368    title: &str,
14369    body: &str,
14370) -> Result<String> {
14371    let out = tokio::process::Command::new("gh")
14372        .args([
14373            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14374        ])
14375        .current_dir(cwd)
14376        .quiet()
14377        .stdin(std::process::Stdio::null())
14378        .output()
14379        .await
14380        .context("spawn gh")?;
14381    if out.status.success() {
14382        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14383    } else {
14384        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14385    }
14386}
14387
14388/// Never force deletion of uncommitted work, including unknown legacy trees.
14389async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14390    match std::fs::symlink_metadata(path) {
14391        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14392            // A previous cleanup may have removed the tree before a branch
14393            // deletion or state save failed. Unregister it if still present.
14394            git::worktree_remove_clean(repo, path).await?;
14395            return Ok(());
14396        }
14397        Err(e) => return Err(e.into()),
14398        Ok(_) => {}
14399    }
14400    if !git::is_clean(path).await? {
14401        bail!(
14402            "worktree has uncommitted work; refusing removal: {}",
14403            path.display()
14404        );
14405    }
14406    if !git::worktree_remove_clean(repo, path).await? {
14407        bail!("worktree removal refused: {}", path.display());
14408    }
14409    Ok(())
14410}
14411
14412/// Read seats return replies, not working-tree changes. Only registered,
14413/// detached seats directly inside this run's root may discard those changes.
14414async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14415    if !crate::retention::read_seat(path) || !path.exists() {
14416        return remove_preserved_worktree(&state.repo, path).await;
14417    }
14418    let owned = std::fs::symlink_metadata(path)?.is_dir()
14419        && path.parent().map(Path::canonicalize).transpose()?
14420            == Some(state.worktree_root().canonicalize()?)
14421        && crate::retention::worktrees(state)
14422            .await?
14423            .contains(&path.canonicalize()?);
14424    let common = crate::repo_lock::common_dir(&state.repo).await?;
14425    if !owned
14426        || common.is_none()
14427        || crate::repo_lock::common_dir(path).await? != common
14428        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14429            .await?
14430            .ok()
14431        || state.candidates.iter().any(|c| c.worktree == path)
14432    {
14433        return remove_preserved_worktree(&state.repo, path).await;
14434    }
14435    let changes = git::status_porcelain(path).await?;
14436    if !git::worktree_remove(&state.repo, path).await? {
14437        bail!(
14438            "read-only seat worktree removal refused: {}",
14439            path.display()
14440        );
14441    }
14442    if !changes.is_empty() {
14443        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14444        let paths: String = paths.chars().take(1024).collect();
14445        state.event(
14446            "fold",
14447            format!(
14448                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14449                path.file_name().unwrap_or_default().to_string_lossy(),
14450                changes.lines().count()
14451            ),
14452        );
14453    }
14454    Ok(())
14455}
14456
14457fn fold_target(
14458    home: &Path,
14459    root: &Path,
14460    path: &Path,
14461    isolated: bool,
14462) -> Option<crate::build_target::FoldTarget> {
14463    if !isolated {
14464        return None;
14465    }
14466    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14467        Ok(target) => target,
14468        Err(error) => {
14469            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14470            None
14471        }
14472    }
14473}
14474
14475fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14476    if let Some(target) = target
14477        && let Err(error) = target.reclaim_orphaned_target(home)
14478    {
14479        tracing::warn!(%error, "isolated target retained after fold");
14480    }
14481}
14482
14483/// Why a fold left a run alone. A typed refusal lets the automatic callers
14484/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14485/// turn) say *why* in their receipts; it never changes what is deleted.
14486#[derive(Debug, Clone, PartialEq, Eq)]
14487pub enum FoldRefusal {
14488    /// A lease or lock a live owner holds - the run's execution lease or
14489    /// ownership lock, a source's output lease, a Cargo build, the repository's
14490    /// coordination lease - or a live daemon claim on the run.
14491    Live(String),
14492    /// A resumable status: someone may still continue this run.
14493    Resumable,
14494    /// Finished less than the fold grace period ago.
14495    WithinGrace,
14496    /// An explicitly retained recovery source (`pr_recovery`).
14497    Retained(String),
14498    /// The proof that nothing is lost is not complete: startup or candidate
14499    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14500    /// residue, Git checkpoints, the fetched base) could not be established.
14501    ProofIncomplete(String),
14502    /// The run's record is gone, or is not the record that was locked: it was
14503    /// deleted while the fold waited for its locks. Nothing is touched and
14504    /// nothing is recreated.
14505    RecordGone,
14506    /// The record was readable when the caller first looked and cannot be read
14507    /// once the run's locks are held.
14508    Unreadable(String),
14509}
14510
14511impl std::fmt::Display for FoldRefusal {
14512    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14513        match self {
14514            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14515            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14516            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14517            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14518            Self::RecordGone => f.write_str("refusing fold: record gone"),
14519            Self::Unreadable(detail) => {
14520                write!(
14521                    f,
14522                    "refusing fold: the run record became unreadable: {detail}"
14523                )
14524            }
14525        }
14526    }
14527}
14528
14529impl std::error::Error for FoldRefusal {}
14530
14531/// Is `error` somebody else holding a lock or lease right now? Only
14532/// contention is: any other failure of a lock call is a real failure.
14533pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14534    error.chain().any(|cause| {
14535        cause.is::<crate::retention::OutputsInUse>()
14536            || cause.is::<crate::repo_lock::ResourceBlocked>()
14537            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14538                io.kind() == std::io::ErrorKind::WouldBlock
14539                    || cfg!(windows) && io.raw_os_error() == Some(33)
14540            })
14541    })
14542}
14543
14544/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14545///
14546/// The refusal is *added to* the error as context, never substituted for it:
14547/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14548/// coordination wait, which several of them treat as a resource stop), and the
14549/// receipt's classification reads the refusal. Both downcasts succeed.
14550fn live_or(error: anyhow::Error) -> anyhow::Error {
14551    if held_by_live_owner(&error) {
14552        error.context(FoldRefusal::Live(
14553            "a lock or lease is held by another owner".into(),
14554        ))
14555    } else {
14556        error
14557    }
14558}
14559
14560/// A failure to take a run's owner lock or execution lease. A run directory
14561/// that is not there (deleted, or never was) is `record gone` and is *not*
14562/// created for the lock's sake; contention is `live`; anything else stays a
14563/// failure with its own text.
14564fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14565    if is_missing(&error) {
14566        FoldRefusal::RecordGone.into()
14567    } else {
14568        live_or(error)
14569    }
14570}
14571
14572fn is_missing(error: &anyhow::Error) -> bool {
14573    error.chain().any(|cause| {
14574        cause
14575            .downcast_ref::<std::io::Error>()
14576            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14577    })
14578}
14579
14580fn preservation_refusal() -> anyhow::Error {
14581    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14582        .into()
14583}
14584
14585/// The record's own preconditions for the explicit recovery-retention override.
14586fn ensure_overridable(state: &RunState) -> Result<()> {
14587    anyhow::ensure!(
14588        state.status.done() && !state.status.resumable(),
14589        "recovery retention override requires a finished, non-resumable run"
14590    );
14591    Ok(())
14592}
14593
14594/// How a failure of the confirmed-merge source verification reaches the fold's
14595/// caller: somebody else holding a lock is `live`; a lock call that failed for
14596/// another reason is a failure of its own (`failed` in the receipt), not
14597/// evidence that the sources are unproven; anything else - missing or changed
14598/// evidence - is an incomplete proof.
14599fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14600    if held_by_live_owner(&error) {
14601        live_or(error)
14602    } else if error
14603        .chain()
14604        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14605    {
14606        error
14607    } else {
14608        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14609    }
14610}
14611
14612/// Which loader a fold uses on the record it reads again under its locks.
14613#[derive(Clone, Copy, PartialEq, Eq)]
14614enum Reload {
14615    /// Housekeeping: the record as saved, whatever schema wrote it
14616    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14617    /// always read it.
14618    Tolerant,
14619    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14620    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14621    /// the preservation checks and the saved record then rest on.
14622    Strict,
14623}
14624
14625/// Why a record read under the locks is no longer the one that was locked.
14626fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14627    if is_missing(error) {
14628        FoldRefusal::RecordGone
14629    } else {
14630        FoldRefusal::Unreadable(format!("{error:#}"))
14631    }
14632}
14633
14634/// What a test does after a fold's first look at the record and before it
14635/// takes the run's locks: where a deletion or a handover falls.
14636#[cfg(test)]
14637type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14638
14639#[cfg(test)]
14640thread_local! {
14641    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14642        const { std::cell::RefCell::new(None) };
14643}
14644
14645/// Tear a run's worktrees and branches down.
14646///
14647/// `home` is where the updated `run.json` is saved (via
14648/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14649/// a housekeeping pass already has its own honest `home` handed to it, and
14650/// falling through to the global here would write back through whichever
14651/// directory some other process or test pinned into that `OnceLock` first,
14652/// not the one the caller actually resolved its `runs` and `state` from.
14653///
14654/// Every deletion decision is made on the record as it is on disk once the
14655/// owner lock and execution lease are held, not on the `state` the caller read
14656/// earlier: see [`fold_run_when`].
14657pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14658    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14659}
14660
14661/// [`fold_run`] for the automatic callers, which decide whether the run may be
14662/// folded at all, and whether its winner goes too, from the run record.
14663///
14664/// `decide` is called on the caller's earlier read by the caller itself, and
14665/// again here on the record reloaded after taking the run's owner lock and
14666/// execution lease. A handover (`handover::release`) records `released_to` /
14667/// `released_branches` under that owner lock and removes the old worktree while
14668/// keeping the branch; a fold that acted on a record read before the handover
14669/// would delete the branch already given to the successor and save the stale
14670/// record over the handover. A run no longer eligible under the fresh record
14671/// is left alone and the refusal says why. The reload is tolerant of older
14672/// schemas, as `clean::fold_due` always was; the explicit entry points
14673/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14674/// migrating loader.
14675pub async fn fold_run_when(
14676    state: &mut RunState,
14677    home: &Path,
14678    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14679) -> Result<Vec<String>> {
14680    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14681}
14682
14683/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14684pub async fn fold_run_overriding_recovery_retention(
14685    state: &mut RunState,
14686    drop_winner: bool,
14687    home: &Path,
14688) -> Result<Vec<String>> {
14689    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14690}
14691
14692async fn fold_run_with_policy(
14693    state: &mut RunState,
14694    home: &Path,
14695    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14696    reload: Reload,
14697    override_recovery_retention: bool,
14698) -> Result<Vec<String>> {
14699    // Cheap refusals on the caller's snapshot, before any lock is taken.
14700    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14701        && !override_recovery_retention
14702    {
14703        return Err(FoldRefusal::Retained(reason).into());
14704    }
14705    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14706        return Err(preservation_refusal());
14707    }
14708    // A fold needs the saved record of the run it locks. Nothing below may
14709    // bring a deleted run's directory back, and a fold is never entitled to
14710    // write a record of its own making: the caller's `state` is only a first
14711    // look, and every decision is made on what is read under the locks.
14712    let id = state.id.clone();
14713    let record = home.join("runs").join(&id).join("run.json");
14714    if !record.try_exists()? {
14715        return Err(FoldRefusal::RecordGone.into());
14716    }
14717    #[cfg(test)]
14718    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14719        hook(home, &id);
14720    }
14721    // Serialize ordinary folding with the same starts/resumes as target-only
14722    // eviction. Otherwise a second janitor could remove the whole worktree
14723    // around a live output borrower even though target eviction was fenced.
14724    // Deleting a run record takes these same two locks (`clean::delete_run`).
14725    // The lock files are opened where they are and never created in a
14726    // directory that is not there: a refusal changes nothing, and the lock
14727    // files are never unlinked (`pr_head::owner_lock`).
14728    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14729    // An override must use current durable ownership, not a pre-lock snapshot.
14730    // Its liveness assessment has to be made before this fold holds the
14731    // execution lease itself (a held lease reads as a live driver); the record
14732    // it is made on is checked for identity like every other, and the final
14733    // record, read once both locks are held, is checked again below.
14734    if override_recovery_retention {
14735        let current =
14736            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14737        if current.id != id {
14738            return Err(FoldRefusal::RecordGone.into());
14739        }
14740        ensure_overridable(&current)?;
14741        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14742        anyhow::ensure!(
14743            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14744            "run is live or its ownership is unknown"
14745        );
14746    }
14747    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14748    // Both locks are held, so no handover, driver claim, deletion or other
14749    // fold can change the record from here on: act on it, not on the earlier
14750    // read. There is no fallback to that read - a record that cannot be read
14751    // again, or is not this run's, ends the fold and touches nothing.
14752    let loaded = match reload {
14753        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
14754        Reload::Strict => RunState::load_under(&id, home),
14755    };
14756    match loaded {
14757        Ok(fresh) if fresh.id == id => *state = fresh,
14758        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
14759        Err(e) => return Err(reload_refusal(&e).into()),
14760    }
14761    if override_recovery_retention {
14762        ensure_overridable(state)?;
14763    }
14764    let drop_winner = decide(state)?;
14765    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14766        return Err(preservation_refusal());
14767    }
14768    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14769    if let Some(reason) = &retention_reason
14770        && !override_recovery_retention
14771    {
14772        return Err(FoldRefusal::Retained(reason.clone()).into());
14773    }
14774    let mut output_guards = Vec::new();
14775    for entry in std::fs::read_dir(state.worktree_root())
14776        .into_iter()
14777        .flatten()
14778        .flatten()
14779    {
14780        if entry.path().join(".git").is_file() {
14781            output_guards
14782                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
14783        }
14784    }
14785    let repo = state.repo.clone();
14786    // CLI, Web and automatic cleanup all enter here, independently of
14787    // Runner::fold_losers. Protect deletion and shared config release too.
14788    //
14789    // Lock order. A handover (`handover::release`, a review taking a branch
14790    // over) holds repository coordination and then asks for this run's owner
14791    // lock; this fold already holds the owner lock. An automatic fold must not
14792    // *wait* for coordination here: the handover would wait for the owner lock
14793    // while the fold waited for coordination, and neither bound (the handover's
14794    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
14795    // - the handover fails its startup, which costs the task an attempt. So it
14796    // asks once; when the lease is busy it gives way: everything it holds is
14797    // released on return, nothing was changed or saved, and the run is `live`
14798    // for this pass and judged again on a later one. The explicit callers
14799    // (`magi fold`, the phone's route) were asked for by a person and still
14800    // wait, bounded as before.
14801    let _coordination = if reload == Reload::Tolerant {
14802        match crate::repo_lock::SeatLease::operation_with(
14803            &repo,
14804            state.config.coordination.as_ref(),
14805            &crate::repo_lock::WaitPolicy::immediate(),
14806        )
14807        .await
14808        {
14809            Ok(lease) => lease,
14810            Err(e) => return Err(live_or(e)),
14811        }
14812    } else {
14813        let wait = repository_wait(state, None);
14814        match coordinate_operation(state, &repo, &wait).await {
14815            Ok(lease) => lease,
14816            Err(e) => {
14817                state.save_under(home)?;
14818                return Err(live_or(e));
14819            }
14820        }
14821    };
14822    // Confirmed merges dispose of their owned sources after durable evidence
14823    // capture. Preflight every source before removing anything. A failure of
14824    // this stage is, by what the stage is for, an incomplete proof - unless
14825    // it is only a lock somebody else holds.
14826    let _source_outputs = if retention_reason.is_some()
14827        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14828    {
14829        match verify_merged_fold_sources(state, drop_winner, home).await {
14830            Ok(held) => held,
14831            Err(e) => return Err(source_proof_failure(e)),
14832        }
14833    } else {
14834        Vec::new()
14835    };
14836    if let Some(reason) = retention_reason {
14837        state.event(
14838            "fold",
14839            format!(
14840                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14841                state.id
14842            ),
14843        );
14844        state.save_under(home)?;
14845    }
14846    let root = state.worktree_root();
14847    let winner = state.tally.as_ref().map(|t| t.winner);
14848    let mut removed = Vec::new();
14849    let isolated = crate::build_target::isolated(&state.config);
14850
14851    for i in 0..state.candidates.len() {
14852        let c = state.candidates[i].clone();
14853        let is_winner = Some(c.label) == winner;
14854        if is_winner && !drop_winner {
14855            continue;
14856        }
14857        let existed = c.worktree.exists();
14858        let target = fold_target(home, &root, &c.worktree, isolated);
14859        // A vanished directory can still have a Git registration that keeps
14860        // its branch checked out. Remove that registration before the branch.
14861        remove_preserved_worktree(&repo, &c.worktree).await?;
14862        reclaim_fold_target(home, target);
14863        if existed {
14864            removed.push(c.worktree.to_string_lossy().into_owned());
14865        }
14866        // A branch handed to a later run (and its pull request) is not this
14867        // run's to delete.
14868        let handed_over = state.released_branches.contains(&c.branch);
14869        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14870            if !git::branch_delete(&repo, &c.branch).await? {
14871                bail!("candidate branch removal refused");
14872            }
14873            removed.push(c.branch.clone());
14874        }
14875        state.candidates[i].folded = true;
14876    }
14877
14878    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14879        let path = name.path();
14880        let keep = !drop_winner
14881            && winner.is_some_and(|w| {
14882                path.file_name()
14883                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14884            });
14885        if keep {
14886            continue;
14887        }
14888        let target = fold_target(home, &root, &path, isolated);
14889        remove_read_seat_worktree(state, &path).await?;
14890        reclaim_fold_target(home, target);
14891        removed.push(path.to_string_lossy().into_owned());
14892    }
14893
14894    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14895    // judge worktrees, so once the loop above has cleared all of them out,
14896    // the parent is a bare directory nobody else was ever going to remove -
14897    // git only ever managed what was inside it. Left alone, one of these
14898    // accumulates per fully-folded run; the operator's own machine had 74.
14899    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14900    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14901    // so does anything a run never claimed that happens to share the bay.
14902    remove_if_empty(&root);
14903
14904    if state.enabled_worktree_config && drop_winner {
14905        // A release, not a raw disable: some sibling run in this repository
14906        // may still hold its own reference (see `git::acquire_worktree_config`),
14907        // and only the last release actually turns the setting back off.
14908        git::release_worktree_config(&repo).await.ok();
14909        state.enabled_worktree_config = false;
14910    }
14911    // What this fold itself found, written in the same locked save: nothing
14912    // left to remove and no bay on disk (a failed or erroring check is not
14913    // "gone"). The busy-time fold turn skips such a run only while the bay is
14914    // still confirmed absent; any fold that found work clears the mark.
14915    state.fold_settled_at =
14916        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
14917    state.save_under(home)?;
14918    Ok(removed)
14919}
14920
14921async fn verify_merged_fold_sources(
14922    state: &RunState,
14923    drop_winner: bool,
14924    home: &Path,
14925) -> Result<Vec<std::fs::File>> {
14926    let winner = state.tally.as_ref().map(|t| t.winner);
14927    let mut heads = BTreeSet::new();
14928    for candidate in &state.candidates {
14929        if Some(candidate.label) == winner && !drop_winner {
14930            continue;
14931        }
14932        anyhow::ensure!(
14933            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14934            "candidate recovery source is outside the inventoried run root: {}",
14935            candidate.worktree.display()
14936        );
14937        match std::fs::symlink_metadata(&candidate.worktree) {
14938            Ok(_) => {}
14939            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14940            Err(error) => return Err(error.into()),
14941        }
14942        if !state.released_branches.contains(&candidate.branch)
14943            && git::branch_exists(&state.repo, &candidate.branch).await?
14944        {
14945            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14946        }
14947    }
14948    let mut cargo_guards = Vec::new();
14949    let entries = match std::fs::read_dir(state.worktree_root()) {
14950        Ok(entries) => Some(entries),
14951        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14952        Err(error) => return Err(error.into()),
14953    };
14954    for entry in entries.into_iter().flatten() {
14955        let path = entry?.path();
14956        let metadata = std::fs::symlink_metadata(&path)?;
14957        anyhow::ensure!(
14958            metadata.is_dir() && !metadata.file_type().is_symlink(),
14959            "non-directory or symlink recovery source retained: {}",
14960            path.display()
14961        );
14962        if !drop_winner
14963            && winner.is_some_and(|w| {
14964                path.file_name()
14965                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14966            })
14967        {
14968            continue;
14969        }
14970        anyhow::ensure!(
14971            path.join(".git").is_file(),
14972            "unregistered recovery source retained: {}",
14973            path.display()
14974        );
14975        anyhow::ensure!(
14976            git::git(
14977                &path,
14978                &[
14979                    "status",
14980                    "--porcelain",
14981                    "--untracked-files=all",
14982                    "--ignored",
14983                    "--",
14984                    ".",
14985                    ":(exclude)target"
14986                ]
14987            )
14988            .await?
14989            .is_empty(),
14990            "source changes or ignored recovery files retained: {}",
14991            path.display()
14992        );
14993        match std::fs::symlink_metadata(path.join("target")) {
14994            Ok(_) => {
14995                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14996            }
14997            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14998            Err(error) => return Err(error.into()),
14999        }
15000        for checkpoint in [
15001            "rebase-merge",
15002            "rebase-apply",
15003            "sequencer",
15004            "CHERRY_PICK_HEAD",
15005            "MERGE_HEAD",
15006            "REBASE_HEAD",
15007            "REVERT_HEAD",
15008            "BISECT_LOG",
15009            "AUTO_MERGE",
15010            "MERGE_MSG",
15011        ] {
15012            let location = git::git(
15013                &path,
15014                &[
15015                    "rev-parse",
15016                    "--path-format=absolute",
15017                    "--git-path",
15018                    checkpoint,
15019                ],
15020            )
15021            .await?;
15022            anyhow::ensure!(
15023                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15024                if e.kind() == std::io::ErrorKind::NotFound),
15025                "Git recovery checkpoint retained: {checkpoint}"
15026            );
15027        }
15028        heads.insert(git::rev_parse(&path, "HEAD").await?);
15029    }
15030    crate::fold_evidence::preserve(state, home, &heads).await?;
15031
15032    Ok(cargo_guards)
15033}
15034
15035/// Remove `dir` if it exists and has nothing in it.
15036///
15037/// Best-effort and silent by design: a directory that is not empty (a run
15038/// whose winner is still parked there, a stray file some other process left)
15039/// is exactly the case this must refuse, and a directory that is already gone
15040/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15041/// already refuses a non-empty directory, so the emptiness check below is
15042/// belt, not suspenders - it is what keeps this from ever attempting the
15043/// removal in the case that matters, rather than trusting `remove_dir`'s
15044/// error path to have no side effects if it ever changed.
15045fn remove_if_empty(dir: &Path) {
15046    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15047        std::fs::remove_dir(dir).ok();
15048    }
15049}
15050
15051/// Severity of the worst open finding in the last review round, for reporting.
15052pub fn worst_open(state: &RunState) -> Option<Severity> {
15053    state
15054        .reviews
15055        .last()?
15056        .reviews
15057        .iter()
15058        .flat_map(|r| r.findings.iter())
15059        .map(|f| f.severity)
15060        .max()
15061}
15062
15063/// `[worktree] setup` hides its products per worktree, which needs
15064/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15065/// worktrees, like the hook's; every place that runs setup calls this first.
15066async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15067    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15068        git::acquire_worktree_config(repo).await?;
15069        state.enabled_worktree_config = true;
15070    }
15071    Ok(())
15072}
15073
15074#[cfg(test)]
15075mod tests {
15076    #[tokio::test]
15077    async fn launcher_base_fetch_requires_remote_success() {
15078        let tmp = tempfile::tempdir().unwrap();
15079        let repo = tmp.path().join("repo");
15080        let remote = tmp.path().join("remote");
15081        std::fs::create_dir(&repo).unwrap();
15082        std::fs::create_dir(&remote).unwrap();
15083        git::git(&remote, &["init", "--bare", "-b", "main"])
15084            .await
15085            .unwrap();
15086        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15087        git::git(
15088            &repo,
15089            &[
15090                "-c",
15091                "user.name=Fixture",
15092                "-c",
15093                "user.email=fixture@example.invalid",
15094                "commit",
15095                "--allow-empty",
15096                "-m",
15097                "fixture",
15098            ],
15099        )
15100        .await
15101        .unwrap();
15102        git::git(
15103            &repo,
15104            &["remote", "add", "origin", remote.to_str().unwrap()],
15105        )
15106        .await
15107        .unwrap();
15108        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15109        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15110        assert_eq!(
15111            resolve_base(&repo, "main", "origin", None)
15112                .await
15113                .unwrap()
15114                .commit,
15115            head
15116        );
15117        #[cfg(unix)]
15118        {
15119            let policy: crate::config::Coordination = toml::from_str(
15120                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15121            ).unwrap();
15122            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15123            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15124            let held = crate::repo_lock::SeatLease::operation_with(
15125                &repo,
15126                Some(&policy),
15127                &crate::repo_lock::WaitPolicy::default(),
15128            )
15129            .await
15130            .unwrap();
15131            assert!(held.is_some());
15132            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15133            tokio::pin!(fetch);
15134            assert!(
15135                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15136                    .await
15137                    .is_err()
15138            );
15139            assert!(
15140                !repo.join(".git/FETCH_HEAD").exists(),
15141                "no fetch before admission"
15142            );
15143            drop(held);
15144            let fetched = fetch.await.unwrap();
15145            assert_eq!(fetched.commit, head);
15146            assert_eq!(fetched.remote, "origin");
15147            assert_eq!(fetched.branch, "main");
15148        }
15149        // A surviving tracking ref is not successful fetch evidence.
15150        git::git(
15151            &repo,
15152            &[
15153                "remote",
15154                "set-url",
15155                "origin",
15156                tmp.path().join("missing").to_str().unwrap(),
15157            ],
15158        )
15159        .await
15160        .unwrap();
15161        let error = resolve_base(&repo, "main", "origin", None)
15162            .await
15163            .unwrap_err()
15164            .to_string();
15165        assert!(error.contains("cannot read origin/main"));
15166        assert!(error.contains("refusing to branch off"));
15167    }
15168
15169    #[test]
15170    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15171        let leaked = vec!["chore(deps): update a crate".to_owned()];
15172        let own = "fix(daemon): apply a chosen action";
15173        assert!(should_retitle("", own, &leaked));
15174        assert!(should_retitle(
15175            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15176            own,
15177            &leaked
15178        ));
15179        assert!(should_retitle(
15180            "chore: land candidate A of run 1",
15181            own,
15182            &leaked
15183        ));
15184        assert!(should_retitle(
15185            "magi: candidate A (uncommitted work)",
15186            own,
15187            &leaked
15188        ));
15189        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15190        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15191        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15192    }
15193
15194    #[test]
15195    fn pr_merge_plan_creates_adopts_or_stops() {
15196        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15197        assert_eq!(
15198            pr_merge_plan(Ok(land::OpenPr::One {
15199                url: "u".into(),
15200                title: "t".into()
15201            })),
15202            PrPlan::Adopt {
15203                url: "u".into(),
15204                title: "t".into()
15205            }
15206        );
15207        let PrPlan::Stop(many) =
15208            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15209        else {
15210            panic!("many must stop");
15211        };
15212        assert!(many.contains('a') && many.contains('b'));
15213        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15214            panic!("a failed lookup must stop");
15215        };
15216        assert!(err.contains("bad token"));
15217    }
15218
15219    use super::*;
15220    use crate::run::GateStatus;
15221    use std::collections::BTreeMap;
15222    use std::time::Duration;
15223
15224    fn conductor() -> AgentSpec {
15225        AgentSpec {
15226            id: "conductor".to_owned(),
15227            kind: crate::config::AgentKind::Command,
15228            model: None,
15229            command: vec!["true".to_owned()],
15230            extra_args: Vec::new(),
15231            env: BTreeMap::new(),
15232            prompt_delivery: None,
15233            max_turn_secs: None,
15234        }
15235    }
15236
15237    fn spec(id: &str) -> AgentSpec {
15238        AgentSpec {
15239            id: id.to_owned(),
15240            kind: crate::config::AgentKind::Command,
15241            model: None,
15242            command: vec!["true".to_owned()],
15243            extra_args: Vec::new(),
15244            env: BTreeMap::new(),
15245            prompt_delivery: None,
15246            max_turn_secs: None,
15247        }
15248    }
15249
15250    fn ids(xs: &[&str]) -> BTreeSet<String> {
15251        xs.iter().map(|s| (*s).to_owned()).collect()
15252    }
15253
15254    #[test]
15255    fn pick_successor_skips_an_agent_another_seat_holds() {
15256        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15257        let roster = [spec("a"), spec("b"), spec("c")];
15258        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15259        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15260    }
15261
15262    #[test]
15263    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15264        // The other seat started on c but was handed to d; c is free again.
15265        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15266        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15267        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15268        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15269        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15270    }
15271
15272    #[test]
15273    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15274        let roster = [spec("a"), spec("b")];
15275        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15276        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15277        let carried = ids(&["b"]);
15278        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15279        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15280    }
15281
15282    #[test]
15283    fn pick_successor_returns_none_without_any_untried_successor() {
15284        let roster = [spec("a"), spec("b")];
15285        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15286        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15287        let carried = ids(&["a"]);
15288        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15289    }
15290
15291    #[test]
15292    fn pick_successor_rescue_avoids_another_seats_occupant() {
15293        // b is a carried failure and free; a is held by the other seat.
15294        let roster = [spec("a"), spec("b"), spec("c")];
15295        let carried = ids(&["b", "c"]);
15296        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15297        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15298    }
15299
15300    #[test]
15301    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15302        let roster = [spec("a"), spec("b"), spec("c")];
15303        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15304        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15305    }
15306
15307    #[test]
15308    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15309        let roster = [spec("a"), spec("b"), spec("c")];
15310        let failed = ids(&["a", "b", "c"]);
15311        // Rescue looks at the whole roster, once per id, then runs out.
15312        let mut tried = ids(&["b"]);
15313        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15314        assert_eq!(first.id, "a");
15315        tried.insert(first.id.clone());
15316        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15317        assert_eq!(second.id, "c");
15318        tried.insert(second.id.clone());
15319        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15320    }
15321
15322    #[test]
15323    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15324        let roster = [spec("a"), spec("b")];
15325        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15326        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15327    }
15328
15329    #[test]
15330    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15331        let roster = [spec("a"), spec("b"), spec("c")];
15332        let h = SeatHistory {
15333            failed: ids(&["a"]),
15334            last_ok: Some("b".to_owned()),
15335            last_fail: None,
15336        };
15337        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15338        // A last answerer that left the roster, or later failed, is ignored.
15339        let gone = SeatHistory {
15340            last_ok: Some("zzz".to_owned()),
15341            ..h.clone()
15342        };
15343        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15344        let failed = SeatHistory {
15345            failed: ids(&["a", "b"]),
15346            last_ok: Some("b".to_owned()),
15347            last_fail: None,
15348        };
15349        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15350    }
15351
15352    #[test]
15353    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15354        let first = SeatState::new("review-1", "alpha", 7);
15355        let next = handover_seat("review-1", "gamma", 7);
15356        assert_ne!(first.claude_session, next.claude_session);
15357    }
15358
15359    #[test]
15360    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15361        let mut state = state_with_summary("x", "y");
15362        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15363        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15364        assert_ne!(a.claude_session, b.claude_session);
15365    }
15366
15367    #[test]
15368    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15369        let roster = [spec("a"), spec("b")];
15370        let h = SeatHistory {
15371            failed: ids(&["a", "b"]),
15372            ..SeatHistory::default()
15373        };
15374        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15375        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15376        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15377    }
15378
15379    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15380    // fallback loop depends on to terminate: it must walk forward from the
15381    // seat's own position, never restart at the front of the roster, and it
15382    // must never hand back an id already tried, however many times that id
15383    // happens to appear.
15384
15385    #[test]
15386    fn failure_signature_ignores_numbers_and_paths() {
15387        assert_eq!(
15388            failure_signature("exited with Some(2) and no usable output"),
15389            failure_signature("exited with Some(137) and no usable output")
15390        );
15391        assert_eq!(
15392            failure_signature("process exited with no usable output (exit code 2)"),
15393            failure_signature("process exited with no usable output (exit code 137)")
15394        );
15395        for (old, new) in [
15396            (
15397                "exited with Some(2) and no usable output",
15398                "process exited with no usable output (exit code 2)",
15399            ),
15400            (
15401                "exited with None and no usable output",
15402                "process exited with no usable output (exit code unavailable)",
15403            ),
15404        ] {
15405            let previous = FailClass::Other(failure_signature(old));
15406            let current = FailClass::Other(failure_signature(new));
15407            assert_eq!(previous, current, "resumption retains the failure class");
15408            assert!(!should_hand_over(Some(&previous), &current));
15409        }
15410        assert_eq!(
15411            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15412            failure_signature("cannot open /var/x.txt: denied")
15413        );
15414        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15415    }
15416
15417    #[test]
15418    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15419        let other = FailClass::Other("x".into());
15420        assert!(should_hand_over(None, &FailClass::Quota));
15421        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15422        assert!(should_hand_over(
15423            Some(&FailClass::Timeout),
15424            &FailClass::Timeout
15425        ));
15426        assert!(should_hand_over(None, &other));
15427        assert!(!should_hand_over(Some(&other), &other));
15428        assert!(should_hand_over(
15429            Some(&other),
15430            &FailClass::Other("y".into())
15431        ));
15432        // A quota or timeout in between ends the run of identical failures.
15433        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15434        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15435    }
15436
15437    #[test]
15438    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15439        let a = SeatState::new("judge-1", "alpha", 7);
15440        let b = handover_seat("judge-1", "beta", 7);
15441        assert_ne!(a.claude_session, b.claude_session);
15442        assert_eq!(b.turns, 0);
15443    }
15444
15445    #[test]
15446    fn a_timeout_is_classified_apart_from_other_failures() {
15447        assert_eq!(
15448            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15449            Some(FailClass::Timeout)
15450        );
15451        assert!(matches!(
15452            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15453            Some(FailClass::Other(_))
15454        ));
15455    }
15456
15457    #[test]
15458    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15459        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15460        let tried = BTreeSet::from(["beta".to_owned()]);
15461        // beta sits at index 1; the next candidate is gamma, never alpha —
15462        // which is very likely a different candidate slot's own agent.
15463        let next = next_untried_in_roster(&roster, 1, &tried);
15464        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15465    }
15466
15467    #[test]
15468    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15469        let roster = vec![spec("alpha"), spec("beta")];
15470        let tried = BTreeSet::from(["beta".to_owned()]);
15471        // beta is the roster's last entry: nothing follows it, and alpha —
15472        // earlier in the roster, almost certainly a different candidate
15473        // slot's own agent — must not be reached by wrapping back to it.
15474        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15475    }
15476
15477    #[test]
15478    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15479        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15480        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15481        // beta (index 1) and gamma (index 2, the only entry after it) have
15482        // both been tried; alpha (index 0) never has, but it comes before
15483        // beta's own position, so there is nothing further for this seat.
15484        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15485    }
15486
15487    #[test]
15488    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15489        let roster = vec![spec("a"), spec("a"), spec("b")];
15490        let tried = BTreeSet::from(["a".to_owned()]);
15491        let next = next_untried_in_roster(&roster, 0, &tried);
15492        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15493    }
15494
15495    #[test]
15496    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15497        let roster = vec![spec("a"), spec("b")];
15498        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15499        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15500    }
15501
15502    #[test]
15503    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15504        let dir = tempfile::tempdir().unwrap();
15505        let bay = dir.path().join("ffff");
15506
15507        // Not there yet: nothing to do, nothing to panic on.
15508        remove_if_empty(&bay);
15509        assert!(!bay.exists());
15510
15511        // Something still inside - the winner's worktree, or a stray file -
15512        // keeps the directory standing.
15513        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15514        remove_if_empty(&bay);
15515        assert!(bay.exists(), "non-empty directory must survive");
15516
15517        // Once the last entry is gone, so is the directory itself.
15518        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15519        remove_if_empty(&bay);
15520        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15521    }
15522
15523    // `round_is_clean` is the exact decision this task fixed: a round with a
15524    // seat that never answered must not read the same as a round every seat
15525    // actually reviewed. These are deterministic and process-free by design —
15526    // the equivalent end-to-end check (a real reviewer timing out under a
15527    // live graph run) is a genuine race against wall-clock contention, and a
15528    // spawn slow enough to blow even a generous budget under a loaded test
15529    // run must not turn this specific regression check flaky.
15530
15531    #[test]
15532    fn a_full_panel_that_found_nothing_is_clean() {
15533        assert!(round_is_clean(
15534            0,
15535            true,
15536            2,
15537            2,
15538            0,
15539            IncompleteReviewPolicy::Block
15540        ));
15541    }
15542
15543    #[test]
15544    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15545        assert!(!round_is_clean(
15546            0,
15547            true,
15548            1,
15549            2,
15550            0,
15551            IncompleteReviewPolicy::Block
15552        ));
15553    }
15554
15555    #[test]
15556    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15557        assert!(!round_is_clean(
15558            1,
15559            true,
15560            1,
15561            2,
15562            0,
15563            IncompleteReviewPolicy::Warn
15564        ));
15565    }
15566
15567    #[test]
15568    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15569        assert!(round_is_clean(
15570            0,
15571            true,
15572            1,
15573            2,
15574            0,
15575            IncompleteReviewPolicy::Warn
15576        ));
15577    }
15578
15579    #[test]
15580    fn a_full_panel_with_an_open_finding_is_not_clean() {
15581        assert!(!round_is_clean(
15582            1,
15583            true,
15584            2,
15585            2,
15586            0,
15587            IncompleteReviewPolicy::Block
15588        ));
15589    }
15590
15591    #[test]
15592    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15593        assert!(!round_is_clean(
15594            0,
15595            false,
15596            2,
15597            2,
15598            0,
15599            IncompleteReviewPolicy::Block
15600        ));
15601    }
15602
15603    // The stall this task closes: under the default `block` policy, a seat
15604    // missing only because it was rate limited must not force a wait for a
15605    // session limit that will not lift by the next round. `round_is_clean`
15606    // is where that quorum carve-out lives; the review loop around it never
15607    // changes what a reviewer's vote or a finding's severity means.
15608
15609    #[test]
15610    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15611        // 1 of 2 answered, and the one missing was quota'd — the exact
15612        // "review-2 rate limited (quota)" shape from the field report.
15613        assert!(round_is_clean(
15614            0,
15615            true,
15616            1,
15617            2,
15618            1,
15619            IncompleteReviewPolicy::Block
15620        ));
15621    }
15622
15623    #[test]
15624    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15625        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15626        // not a quota loss (`quota_missing` stays 0) — worth another try.
15627        assert!(!round_is_clean(
15628            0,
15629            true,
15630            1,
15631            2,
15632            0,
15633            IncompleteReviewPolicy::Block
15634        ));
15635    }
15636
15637    #[test]
15638    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15639        assert!(!round_is_clean(
15640            1,
15641            true,
15642            1,
15643            2,
15644            1,
15645            IncompleteReviewPolicy::Block
15646        ));
15647        assert!(!round_is_clean(
15648            0,
15649            false,
15650            1,
15651            2,
15652            1,
15653            IncompleteReviewPolicy::Block
15654        ));
15655    }
15656
15657    #[test]
15658    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15659        // Every seat quota'd, nobody answered: there is no panel to decide
15660        // on, so this must fall through to the existing block-and-retry
15661        // fallback rather than call an unreviewed patch clean.
15662        assert!(!round_is_clean(
15663            0,
15664            true,
15665            0,
15666            2,
15667            2,
15668            IncompleteReviewPolicy::Block
15669        ));
15670    }
15671
15672    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15673        CommandOutcome {
15674            command: "test".to_owned(),
15675            code,
15676            output_tail: String::new(),
15677            duration_ms: 0,
15678            resource_blocked,
15679            ..Default::default()
15680        }
15681    }
15682
15683    #[cfg(unix)]
15684    #[tokio::test]
15685    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15686        ask_test_home();
15687        let temp = tempfile::tempdir().unwrap();
15688        let mut runner = runner_at(RunStatus::Gating);
15689        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15690        let commands = vec![
15691            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15692            "touch must-not-run".to_owned(),
15693        ];
15694        let (outcomes, retried, pids) = run_e2e_with_retry(
15695            &mut runner.state,
15696            &shell,
15697            &commands,
15698            temp.path(),
15699            Duration::from_secs(5),
15700            "fixture",
15701            None,
15702        )
15703        .await;
15704        assert_eq!(outcomes.len(), 1);
15705        assert!(outcomes[0].resource_blocked);
15706        assert!(!outcomes[0].build_failed());
15707        assert!(!retried);
15708        assert!(pids.is_empty());
15709        assert!(!temp.path().join("must-not-run").exists());
15710        assert_eq!(
15711            runner.state.resource_block.as_ref().unwrap().kind,
15712            "incremental cache admission"
15713        );
15714    }
15715
15716    #[test]
15717    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15718        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15719        assert!(
15720            !verify_inconclusive(&[outcome(Some(1), false)]),
15721            "an ordinary failure is still evidence about the patch"
15722        );
15723        assert!(verify_inconclusive(&[outcome(None, true)]));
15724        assert!(
15725            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15726            "one inconclusive outcome taints the whole batch"
15727        );
15728        assert!(!verify_inconclusive(&[]));
15729    }
15730
15731    #[tokio::test]
15732    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15733        // Alive for the first two checks, then dead - confirms the loop
15734        // actually re-polls rather than deciding once and sleeping out the
15735        // ceiling regardless.
15736        let calls = std::sync::atomic::AtomicUsize::new(0);
15737        let started = Instant::now();
15738        wait_for_pids_with(
15739            &[123],
15740            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15741            Duration::from_millis(5),
15742            Duration::from_secs(5),
15743        )
15744        .await;
15745        assert!(
15746            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15747            "must keep checking rather than deciding on the first answer"
15748        );
15749        assert!(
15750            started.elapsed() < Duration::from_secs(1),
15751            "must return the moment it is confirmed dead, not wait out the ceiling"
15752        );
15753    }
15754
15755    #[tokio::test]
15756    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15757        let started = Instant::now();
15758        wait_for_pids_with(
15759            &[123],
15760            |_| true, // never reports dead
15761            Duration::from_millis(5),
15762            Duration::from_millis(30),
15763        )
15764        .await;
15765        let elapsed = started.elapsed();
15766        assert!(
15767            elapsed >= Duration::from_millis(30),
15768            "must not give up before its own ceiling: {elapsed:?}"
15769        );
15770        assert!(
15771            elapsed < Duration::from_secs(1),
15772            "must not wait past its own ceiling either: {elapsed:?}"
15773        );
15774    }
15775
15776    #[tokio::test]
15777    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15778        let started = Instant::now();
15779        wait_for_pids_with(
15780            &[],
15781            |_| true,
15782            Duration::from_secs(5),
15783            Duration::from_secs(5),
15784        )
15785        .await;
15786        assert!(
15787            started.elapsed() < Duration::from_millis(200),
15788            "an empty pid list has nothing to confirm"
15789        );
15790    }
15791
15792    // `review_conclusion` is the exact decision the review hand-off task
15793    // fixed: a round budget spent (or a tree that stopped moving) must not
15794    // collapse into `Blocked` regardless of what verification actually
15795    // said. Deterministic and process-free for the same reason the
15796    // `round_is_clean` family above is.
15797    fn review_round(
15798        clean: bool,
15799        blocking: usize,
15800        answered: usize,
15801        expected: usize,
15802        progressed: bool,
15803        e2e_ok: bool,
15804    ) -> ReviewRound {
15805        ReviewRound {
15806            round: 1,
15807            head: "h".to_owned(),
15808            verified_head: None,
15809            verified_at: None,
15810            reviews: Vec::new(),
15811            e2e: vec![CommandOutcome {
15812                command: "test".to_owned(),
15813                code: Some(if e2e_ok { 0 } else { 1 }),
15814                output_tail: String::new(),
15815                duration_ms: 0,
15816                resource_blocked: false,
15817                ..Default::default()
15818            }],
15819            verify_retried: false,
15820            e2e_deferred: false,
15821            e2e_defer_reason: None,
15822            fix: None,
15823            blocking,
15824            answered,
15825            expected,
15826            clean,
15827            progressed,
15828            vote_split: false,
15829            reconsideration: Vec::new(),
15830            verdict: None,
15831        }
15832    }
15833
15834    #[test]
15835    fn review_conclusion_is_none_when_nothing_has_run() {
15836        assert_eq!(review_conclusion(&[], 3), None);
15837    }
15838
15839    #[test]
15840    fn review_conclusion_is_none_while_rounds_remain() {
15841        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15842        assert_eq!(review_conclusion(&rounds, 3), None);
15843    }
15844
15845    #[test]
15846    fn review_conclusion_is_gating_once_a_round_is_clean() {
15847        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15848        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15849    }
15850
15851    #[test]
15852    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15853        let rounds = vec![
15854            review_round(false, 1, 2, 2, true, true),
15855            review_round(false, 1, 2, 2, true, true),
15856        ];
15857        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15858    }
15859
15860    #[test]
15861    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15862        let rounds = vec![
15863            review_round(false, 1, 2, 2, true, true),
15864            review_round(false, 1, 2, 2, true, false),
15865        ];
15866        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15867    }
15868
15869    #[test]
15870    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15871        // Magi never got a command to run against this round's own head — a
15872        // resource-blocked attempt, not a red one — so this must never
15873        // settle on `Blocked` the way a genuine e2e failure would. `None`
15874        // here is what tells `Runner::review_loop` to retry the check
15875        // itself rather than trust this cheap recomputation with a verdict
15876        // it cannot actually produce.
15877        let mut blocked = review_round(false, 1, 2, 2, true, false);
15878        blocked.e2e[0].resource_blocked = true;
15879        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15880        assert_eq!(review_conclusion(&rounds, 2), None);
15881    }
15882
15883    #[test]
15884    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15885        // Missing input, not a verified tree — never a hand-off candidate.
15886        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15887        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15888    }
15889
15890    #[test]
15891    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15892        let rounds = vec![
15893            review_round(false, 1, 2, 2, false, true),
15894            review_round(false, 1, 2, 2, false, true),
15895        ];
15896        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15897    }
15898
15899    fn secs(n: u64) -> Duration {
15900        Duration::from_secs(n)
15901    }
15902
15903    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15904    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15905    #[tokio::test]
15906    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15907        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15908        if std::env::var_os(CHILD).is_none() {
15909            // Other tests reconcile every run in the process-global home,
15910            // briefly taking owner locks. This ancestry test expects an idle
15911            // predecessor, so give it its own process and pinned test home.
15912            let output = std::process::Command::new(std::env::current_exe().unwrap())
15913                .args([
15914                    "--exact",
15915                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15916                    "--nocapture",
15917                ])
15918                .env(CHILD, "1")
15919                .env_remove("MAGI_WORKER_HOME")
15920                .env_remove("MAGI_WORKER_ID")
15921                .output()
15922                .unwrap();
15923            assert!(
15924                output.status.success()
15925                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15926                "{}\n{}",
15927                String::from_utf8_lossy(&output.stdout),
15928                String::from_utf8_lossy(&output.stderr)
15929            );
15930            return;
15931        }
15932        ask_test_home();
15933        let tmp = tempfile::tempdir().unwrap();
15934        let repo = tmp.path().join("repo");
15935        std::fs::create_dir_all(&repo).unwrap();
15936        init_repo(&repo);
15937        let g = |args: &[&str]| {
15938            let out = std::process::Command::new("git")
15939                .args(args)
15940                .current_dir(&repo)
15941                .quiet()
15942                .output()
15943                .unwrap();
15944            assert!(
15945                out.status.success(),
15946                "{}",
15947                String::from_utf8_lossy(&out.stderr)
15948            );
15949        };
15950        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15951        g(&["checkout", "-b", "historical"]);
15952        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15953        g(&["add", "."]);
15954        g(&["commit", "-m", "old alternative"]);
15955        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15956        g(&["checkout", "-b", "magi/task-selected", &base]);
15957        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15958        g(&["add", "."]);
15959        g(&["commit", "-m", "measurement infrastructure"]);
15960        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15961        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15962        g(&["add", "."]);
15963        g(&["commit", "-m", "dependent implementation"]);
15964        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15965        g(&["checkout", "main"]);
15966        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15967        g(&["add", "."]);
15968        g(&["commit", "-m", "unrelated base change"]);
15969        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15970        let origin = tmp.path().join("origin.git");
15971        g(&[
15972            "clone",
15973            "--bare",
15974            repo.to_str().unwrap(),
15975            origin.to_str().unwrap(),
15976        ]);
15977        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15978        g(&["fetch", "origin"]);
15979        let selection = crate::pr_recovery::Selection {
15980            url: "https://example.test/project/pull/1".into(),
15981            branch: "magi/task-selected".into(),
15982            head: head.clone(),
15983            source_head: None,
15984            source_run: None,
15985            source_proof: None,
15986            disposition: Some(crate::pr_recovery::Disposition::Review),
15987            instruction: "preserve measured behavior".into(),
15988            approved_at: jiff::Timestamp::now(),
15989        };
15990        let mut template = runner_at(RunStatus::Reviewing);
15991        template.state.repo = repo.clone();
15992        template.state.base_commit = current.clone();
15993        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15994        template.state.origin = Some(crate::run::Origin::queue("selected"));
15995        template.state.pr_head = Some(selection.branch.clone());
15996        template.state.pr_recovery = Some(selection.clone());
15997        let mut runner =
15998            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15999                .await
16000                .unwrap();
16001        let wt = runner.state.winner().unwrap().worktree.clone();
16002        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16003        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16004        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16005        assert!(runner.state.seeds.is_empty());
16006        assert_eq!(runner.state.instruction, "preserve measured behavior");
16007        runner.sync_to_base().await.unwrap();
16008        assert_eq!(
16009            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16010            "prerequisite"
16011        );
16012        assert_eq!(
16013            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16014            "measured implementation"
16015        );
16016        assert_eq!(
16017            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16018            "current main change"
16019        );
16020        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16021        assert_eq!(
16022            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16023            head
16024        );
16025
16026        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16027        let mut partial = runner_at(RunStatus::Reviewing);
16028        partial.state.repo = repo.clone();
16029        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16030        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16031            run: Some("exit 1".into()),
16032            ..Default::default()
16033        }];
16034        let selection = runner.state.pr_recovery.clone().unwrap();
16035        partial.state.pr_recovery = Some(selection.clone());
16036        partial.state.pr_head = Some(selection.branch.clone());
16037        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16038        let id = partial.state.id.clone();
16039        let error = match Runner::open_selected(
16040            &repo,
16041            partial.state,
16042            partial.roles,
16043            1,
16044            runner.state.base_commit.clone(),
16045            selection,
16046        )
16047        .await
16048        {
16049            Ok(_) => panic!("setup must fail"),
16050            Err(e) => e,
16051        };
16052        assert_eq!(
16053            error
16054                .downcast_ref::<crate::run::StartupFailure>()
16055                .unwrap()
16056                .run,
16057            id
16058        );
16059        let failed = RunState::load(&id).unwrap();
16060        assert_eq!(failed.status, RunStatus::Failed);
16061        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16062        assert!(Runner::resume(&id).is_err());
16063        runner.state.status = RunStatus::Ready;
16064        runner.state.driver_exited = true;
16065        runner.state.save().unwrap();
16066        let mut retry = runner_at(RunStatus::Reviewing);
16067        retry.state.repo = repo.clone();
16068        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16069        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16070        reselected.approved_at = jiff::Timestamp::now();
16071        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16072        retry.state.pr_head = Some(reselected.branch.clone());
16073        retry.state.pr_recovery = Some(reselected.clone());
16074        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16075            .await
16076            .unwrap();
16077        let restarted = Runner::open_selected(
16078            &repo,
16079            retry.state,
16080            retry.roles,
16081            1,
16082            runner.state.base_commit.clone(),
16083            reselected,
16084        )
16085        .await
16086        .unwrap();
16087        assert_eq!(
16088            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16089                .await
16090                .unwrap(),
16091            head
16092        );
16093        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16094        assert_eq!(
16095            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16096            head
16097        );
16098    }
16099
16100    #[tokio::test]
16101    #[cfg(unix)]
16102    async fn fallback_and_interrupted_restoration_require_coordination() {
16103        use std::os::fd::AsRawFd as _;
16104        ask_test_home();
16105        let tmp = tempfile::tempdir().unwrap();
16106        let mut runner = registered_runner(tmp.path()).await;
16107        runner.state.config.graph.timeout_resource_wait = 1;
16108        let winner = runner.state.candidates[0].clone();
16109        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16110        let leftover = winner.worktree.join("leftover");
16111        std::fs::write(&leftover, "untrusted edits").unwrap();
16112        let next = tmp.path().join("next-fixer");
16113        let mut failed = spec("first");
16114        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16115        let mut successor = spec("second");
16116        successor.command = vec![
16117            "sh".into(),
16118            "-c".into(),
16119            format!("touch '{}'; echo done", next.display()),
16120        ];
16121        let attempts = vec![
16122            (failed.clone(), "first".into()),
16123            (successor.clone(), "second".into()),
16124        ];
16125        let lock_path = runner.state.repo.join(".git/updater.lock");
16126        let external = std::fs::File::create(&lock_path).unwrap();
16127        assert_eq!(
16128            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16129            0
16130        );
16131        let artifacts = tmp.path().join("artifacts");
16132        let build = |spec, seat| SeatJob {
16133            spec,
16134            seat,
16135            cwd: winner.worktree.clone(),
16136            prompt: "fixture".into(),
16137            timeout: Duration::from_secs(10),
16138            allow_write: true,
16139            sessions: false,
16140            artifacts: artifacts.clone(),
16141            stem: "fix".into(),
16142            handover: None,
16143        };
16144        let (_, _, out) = runner
16145            .ask_fixer_among(
16146                attempts.clone(),
16147                "graft",
16148                None,
16149                Some((&winner.worktree, &head)),
16150                build,
16151            )
16152            .await;
16153        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16154        assert!(leftover.exists(), "contention must prevent clean");
16155        assert!(!next.exists());
16156        assert!(runner.state.handovers.is_empty());
16157        // Early interrupted-repair rollback uses the same protected route.
16158        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16159            from_run: "earlier".into(),
16160            generation: 1,
16161            mode: crate::recovery::Mode::VerifyRepair,
16162            reasons: Vec::new(),
16163            reviewed_head: None,
16164            rounds: Vec::new(),
16165            open_findings: Vec::new(),
16166            evidence: None,
16167            criteria_inherited: true,
16168            repair: crate::recovery::Repair::Started {
16169                before: head.clone(),
16170            },
16171        });
16172        assert!(
16173            runner
16174                .recovery_repair(&winner)
16175                .await
16176                .unwrap_err()
16177                .is::<crate::repo_lock::ResourceBlocked>()
16178        );
16179        assert!(matches!(
16180            runner.state.recovery.as_ref().unwrap().repair,
16181            crate::recovery::Repair::Started { .. }
16182        ));
16183        assert!(leftover.exists());
16184        drop(external);
16185        runner.recovery_repair(&winner).await.unwrap();
16186        assert!(!leftover.exists());
16187        assert!(matches!(
16188            runner.state.recovery.as_ref().unwrap().repair,
16189            crate::recovery::Repair::Done { .. }
16190        ));
16191        // A hard lock-open failure also leaves HEAD and untracked work intact.
16192        std::fs::remove_file(&lock_path).unwrap();
16193        std::fs::create_dir(&lock_path).unwrap();
16194        std::fs::write(&leftover, "untrusted edits").unwrap();
16195        let (_, _, out) = runner
16196            .ask_fixer_among(
16197                attempts,
16198                "graft",
16199                None,
16200                Some((&winner.worktree, &head)),
16201                build,
16202            )
16203            .await;
16204        assert!(matches!(out, AgentOutcome::Failed(_)));
16205        assert!(leftover.exists());
16206        assert!(!next.exists());
16207        assert_eq!(
16208            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16209            head
16210        );
16211    }
16212
16213    #[cfg(unix)]
16214    async fn registered_runner(root: &Path) -> Runner {
16215        repository_runner(root, crate::config::test_coordination()).await
16216    }
16217
16218    async fn repository_runner(
16219        root: &Path,
16220        coordination: Option<crate::config::Coordination>,
16221    ) -> Runner {
16222        ask_test_home();
16223        let repo = root.join("repo");
16224        std::fs::create_dir_all(&repo).unwrap();
16225        init_repo(&repo);
16226        if coordination.is_some() {
16227            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16228        }
16229        let mut runner = runner_at(RunStatus::Prep);
16230        runner.state.repo = repo.clone();
16231        runner.state.config.coordination = coordination;
16232        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16233        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16234        runner.state.config.graph.advise = false;
16235        runner.roles.implementers = vec![spec("implement")];
16236        runner.roles.judges = vec![spec("judge")];
16237        runner.prep().await.unwrap();
16238        runner
16239    }
16240
16241    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16242
16243    #[tokio::test]
16244    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16245        let tmp = tempfile::tempdir().unwrap();
16246        let mut runner = repository_runner(tmp.path(), None).await;
16247        let prompts = runner.state.config.prompts.clone();
16248        let run = runner.state.id.clone();
16249        let ctx = WaveCtx {
16250            carry_seats: false,
16251            pauses: None,
16252            run: &run,
16253            node: "advise",
16254            prompts: &prompts,
16255            cache: None,
16256            round: None,
16257        };
16258        let jobs: Vec<_> = ["alpha", "beta"]
16259            .into_iter()
16260            .map(|id| SeatJob {
16261                spec: scripted(id, AUTH_OUTAGE),
16262                seat: SeatState::new(id, id, 7),
16263                prompt: "propose".into(),
16264                cwd: runner.state.candidates[0].worktree.clone(),
16265                timeout: Duration::from_secs(10),
16266                allow_write: false,
16267                sessions: false,
16268                artifacts: agent::artifacts_dir(&runner.state.dir()),
16269                stem: id.into(),
16270                handover: None,
16271            })
16272            .collect();
16273        let mut losses = Vec::new();
16274        let results = ask_wave_with(
16275            jobs.clone(),
16276            runner.sem.clone(),
16277            2,
16278            &[],
16279            &ctx,
16280            &mut losses,
16281            &mut runner.state,
16282            &|_: &str| Ok(()),
16283        )
16284        .await;
16285        assert!(
16286            results
16287                .iter()
16288                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16289        );
16290        assert_eq!(runner.state.quota.len(), 2);
16291        assert!(
16292            runner
16293                .state
16294                .quota
16295                .iter()
16296                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16297        );
16298        assert!(!runner.state.advise_attempted);
16299        runner.stop_for_resource().unwrap();
16300        assert_eq!(runner.state.status, RunStatus::Blocked);
16301        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16302        assert_eq!(
16303            runner.state.resource_block.as_ref().unwrap().kind,
16304            "agent authentication"
16305        );
16306        // A machine loss followed by an ordinary failure is not evidence
16307        // that the whole node was unavailable, and must not earn a refund.
16308        runner.state.resource_block = None;
16309        runner.state.quota.clear();
16310        let mut mixed = jobs;
16311        mixed[1].spec.command = vec!["false".into()];
16312        let results = ask_wave_with(
16313            mixed,
16314            runner.sem.clone(),
16315            0,
16316            &[],
16317            &ctx,
16318            &mut losses,
16319            &mut runner.state,
16320            &|_: &str| Ok(()),
16321        )
16322        .await;
16323        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16324        assert!(runner.state.resource_block.is_none());
16325        assert_eq!(losses.len(), 1);
16326    }
16327
16328    #[tokio::test]
16329    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16330        let tmp = tempfile::tempdir().unwrap();
16331        let mut runner = repository_runner(tmp.path(), None).await;
16332        let implementer = scripted("implement", AUTH_OUTAGE);
16333        runner.roles.implementers = vec![implementer.clone()];
16334        runner.state.config.agents = vec![implementer];
16335        runner.implement().await.unwrap();
16336        assert_eq!(runner.state.status, RunStatus::Blocked);
16337        assert_eq!(runner.state.quota.len(), 1);
16338        assert_eq!(
16339            runner.state.quota[0].cause,
16340            agent::QuotaCause::Authentication
16341        );
16342        let candidate = &runner.state.candidates[0];
16343        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16344        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16345    }
16346
16347    #[tokio::test]
16348    #[cfg(unix)]
16349    async fn parked_implementer_persists_completed_work() {
16350        for registered in [false, true] {
16351            let tmp = tempfile::tempdir().unwrap();
16352            let mut runner = registered_runner(tmp.path()).await;
16353            if !registered {
16354                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16355            }
16356            let marker = tmp.path().join("started");
16357            let release = tmp.path().join("release");
16358            let mut implementer = spec("implement");
16359            implementer.command = vec![
16360                "sh".into(),
16361                "-c".into(),
16362                format!(
16363                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16364                    marker.display(),
16365                    release.display()
16366                ),
16367            ];
16368            runner.roles.implementers = vec![implementer.clone()];
16369            runner.state.config.agents = vec![implementer];
16370            let pause = runner.pause.clone();
16371            let (result, ()) = tokio::join!(runner.implement(), async {
16372                tokio::time::timeout(Duration::from_secs(10), async {
16373                    while !marker.exists() {
16374                        tokio::time::sleep(Duration::from_millis(10)).await;
16375                    }
16376                })
16377                .await
16378                .unwrap();
16379                pause.park();
16380                std::fs::write(&release, "go").unwrap();
16381            });
16382            result.unwrap();
16383            let candidate = &runner.state.candidates[0];
16384            assert!(candidate.commits > 0, "{candidate:?}");
16385            assert!(candidate.summary.contains("saved-result"));
16386            assert_eq!(candidate.files, 1);
16387            let before = candidate.commits;
16388            runner.implement().await.unwrap();
16389            assert_eq!(runner.state.candidates[0].commits, before);
16390        }
16391    }
16392
16393    #[tokio::test]
16394    #[cfg(unix)]
16395    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16396        let tmp = tempfile::tempdir().unwrap();
16397        let mut runner = registered_runner(tmp.path()).await;
16398        let winner = runner.state.candidates[0].clone();
16399        let cache = tmp.path().join("cache");
16400        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16401        runner.state.config.graph.timeout_resource_wait = 0;
16402        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16403        let crate::cache::AcquireOutcome::Acquired(held) =
16404            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16405        else {
16406            panic!("cache must be free")
16407        };
16408        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16409            from_run: "earlier".into(),
16410            generation: 1,
16411            mode: crate::recovery::Mode::VerifyRepair,
16412            reasons: Vec::new(),
16413            reviewed_head: None,
16414            rounds: Vec::new(),
16415            open_findings: Vec::new(),
16416            evidence: None,
16417            criteria_inherited: true,
16418            repair: crate::recovery::Repair::NotStarted,
16419        });
16420        runner.recovery_repair(&winner).await.unwrap();
16421        assert!(matches!(
16422            runner.state.recovery.as_ref().unwrap().repair,
16423            crate::recovery::Repair::WaitingForRestore { .. }
16424        ));
16425        drop(held);
16426        runner.state.resource_block = None;
16427        runner.state.config.graph.timeout_resource_wait = 1;
16428        runner.recovery_repair(&winner).await.unwrap();
16429        assert!(matches!(
16430            runner.state.recovery.as_ref().unwrap().repair,
16431            crate::recovery::Repair::Done { .. }
16432        ));
16433        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16434    }
16435
16436    #[tokio::test]
16437    #[cfg(unix)]
16438    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16439        use std::os::fd::AsRawFd as _;
16440        for graft in [false, true] {
16441            let tmp = tempfile::tempdir().unwrap();
16442            let mut runner = registered_runner(tmp.path()).await;
16443            runner.state.config.graph.timeout_resource_wait = 1;
16444            let winner = runner.state.candidates[0].clone();
16445            let marker = tmp.path().join("fixer-started");
16446            let mut fixer = spec("fixer");
16447            fixer.command = vec![
16448                "sh".into(),
16449                "-c".into(),
16450                format!("echo started >> '{}'; echo done", marker.display()),
16451            ];
16452            runner.roles.fixer = Some(vec![fixer]);
16453            if graft {
16454                let mut loser = winner.clone();
16455                loser.label = 'B';
16456                loser.index = 1;
16457                runner.state.candidates.push(loser);
16458                runner.state.config.graph.graft_runner_up = true;
16459                runner.state.tally = Some(Tally {
16460                    first_choice: BTreeMap::new(),
16461                    borda: BTreeMap::new(),
16462                    winner: winner.label,
16463                    rankings: 1,
16464                    unanimous_initial: true,
16465                    deliberated: false,
16466                    changed_votes: 0,
16467                    unanimous_final: true,
16468                    tie_break: None,
16469                    judges: 1,
16470                    present: 1,
16471                    quorum: 1,
16472                    met_quorum: true,
16473                    uncontested: None,
16474                });
16475                runner.state.judgements.push(crate::run::Judgement {
16476                    judge: 1,
16477                    seat: "judge-1".into(),
16478                    agent: "judge".into(),
16479                    ranking: vec![winner.label, 'B'],
16480                    reasons: BTreeMap::new(),
16481                    confidence: None,
16482                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16483                    order: vec![0, 1],
16484                    failed: None,
16485                    duration_ms: 0,
16486                });
16487            } else {
16488                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16489                    from_run: "earlier".into(),
16490                    generation: 1,
16491                    mode: crate::recovery::Mode::VerifyRepair,
16492                    reasons: Vec::new(),
16493                    reviewed_head: None,
16494                    rounds: Vec::new(),
16495                    open_findings: Vec::new(),
16496                    evidence: None,
16497                    criteria_inherited: true,
16498                    repair: crate::recovery::Repair::NotStarted,
16499                });
16500            }
16501            let reader = crate::repo_lock::SeatLease::for_checkout(
16502                &winner.worktree,
16503                false,
16504                crate::config::test_coordination().as_ref(),
16505            )
16506            .await
16507            .unwrap();
16508            let pause = runner.pause.clone();
16509            let (result, ()) = tokio::join!(
16510                async {
16511                    if graft {
16512                        runner.graft().await
16513                    } else {
16514                        runner.recovery_repair(&winner).await
16515                    }
16516                },
16517                async {
16518                    tokio::time::sleep(Duration::from_millis(100)).await;
16519                    pause.park();
16520                }
16521            );
16522            result.unwrap();
16523            assert!(!marker.exists(), "a blocked seat must not spawn");
16524            // Exercise the persisted state, as a binary replacement/resume does.
16525            runner.state = RunState::load(&runner.state.id).unwrap();
16526            if graft {
16527                assert_eq!(
16528                    runner.state.graft.as_ref().unwrap().outcome,
16529                    GraftOutcome::WaitingForRestore
16530                );
16531            } else {
16532                assert!(matches!(
16533                    runner.state.recovery.as_ref().unwrap().repair,
16534                    crate::recovery::Repair::WaitingForRestore { .. }
16535                ));
16536            }
16537            drop(reader);
16538            runner.pause = Pause::new();
16539            runner.state.resource_block = None;
16540            // Deferred restoration must still respect an external lock owner.
16541            let external =
16542                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16543            assert_eq!(
16544                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16545                0
16546            );
16547            let leftover = winner.worktree.join("leftover");
16548            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16549            let result = if graft {
16550                runner.graft().await
16551            } else {
16552                runner.recovery_repair(&winner).await
16553            };
16554            assert!(
16555                result
16556                    .unwrap_err()
16557                    .is::<crate::repo_lock::ResourceBlocked>()
16558            );
16559            assert!(leftover.exists());
16560            assert!(!marker.exists());
16561            drop(external);
16562            runner.state.resource_block = None;
16563            let result = if graft {
16564                runner.graft().await
16565            } else {
16566                runner.recovery_repair(&winner).await
16567            };
16568            result.unwrap();
16569            assert!(!leftover.exists(), "restore must precede retry");
16570            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16571            if graft {
16572                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16573            } else {
16574                assert!(matches!(
16575                    runner.state.recovery.as_ref().unwrap().repair,
16576                    crate::recovery::Repair::Done { .. }
16577                ));
16578            }
16579        }
16580    }
16581
16582    #[tokio::test]
16583    #[cfg(unix)]
16584    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16585        use std::os::fd::AsRawFd as _;
16586        let tmp = tempfile::tempdir().unwrap();
16587        let mut runner = registered_runner(tmp.path()).await;
16588        runner.state.config.graph.timeout_resource_wait = 1;
16589        let winner = runner.state.candidates[0].clone();
16590        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16591        runner.state.tally = Some(Tally {
16592            first_choice: BTreeMap::new(),
16593            borda: BTreeMap::new(),
16594            winner: winner.label,
16595            rankings: 0,
16596            unanimous_initial: false,
16597            deliberated: false,
16598            changed_votes: 0,
16599            unanimous_final: false,
16600            tie_break: None,
16601            judges: 0,
16602            present: 0,
16603            quorum: 0,
16604            met_quorum: true,
16605            uncontested: Some("fixture".into()),
16606        });
16607        runner.state.graft = Some(GraftRecord {
16608            pre: pre.clone(),
16609            post: None,
16610            lines: None,
16611            limit: None,
16612            agent: None,
16613            outcome: GraftOutcome::Running,
16614            requested: Vec::new(),
16615            adoption: None,
16616            adoption_error: None,
16617        });
16618        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16619        git::commit_all(&winner.worktree, "unfinished graft")
16620            .await
16621            .unwrap();
16622        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16623        let leftover = winner.worktree.join("leftover");
16624        std::fs::write(&leftover, "untrusted edits").unwrap();
16625        let path = runner.state.repo.join(".git/updater.lock");
16626        let external = std::fs::File::create(&path).unwrap();
16627        assert_eq!(
16628            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16629            0
16630        );
16631        assert!(
16632            runner
16633                .graft()
16634                .await
16635                .unwrap_err()
16636                .is::<crate::repo_lock::ResourceBlocked>()
16637        );
16638        assert!(matches!(
16639            runner.state.graft.as_ref().unwrap().outcome,
16640            GraftOutcome::Running
16641        ));
16642        assert_eq!(
16643            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16644            unfinished
16645        );
16646        assert!(leftover.exists());
16647        drop(external);
16648        std::fs::remove_file(&path).unwrap();
16649        std::fs::create_dir(&path).unwrap();
16650        assert!(runner.graft().await.is_err());
16651        assert!(matches!(
16652            runner.state.graft.as_ref().unwrap().outcome,
16653            GraftOutcome::Running
16654        ));
16655        assert_eq!(
16656            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16657            unfinished
16658        );
16659        assert!(leftover.exists());
16660        std::fs::remove_dir(&path).unwrap();
16661        runner.graft().await.unwrap();
16662        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16663        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16664        assert!(!leftover.exists());
16665    }
16666
16667    #[tokio::test]
16668    #[cfg(unix)]
16669    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16670        use std::os::fd::AsRawFd as _;
16671        let tmp = tempfile::tempdir().unwrap();
16672        let mut runner = registered_runner(tmp.path()).await;
16673        runner.state.prep_complete = Some(false);
16674        runner.state.config.graph.timeout_resource_wait = 1;
16675        runner.state.save().unwrap();
16676        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16677        assert_eq!(
16678            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16679            0
16680        );
16681        runner.execute().await.unwrap();
16682        let disk = RunState::load(&runner.state.id).unwrap();
16683        assert!(disk.driver_exited);
16684        assert_eq!(disk.driver_pid, None);
16685        assert_eq!(runner.state.status, RunStatus::Blocked);
16686        assert_eq!(
16687            runner.state.resource_block.as_ref().unwrap().kind,
16688            "repository coordination"
16689        );
16690        assert!(runner.state.prep_failure.is_none());
16691        assert!(runner.state.seats.is_empty());
16692        runner.pause.park();
16693        // Include headroom for Git subprocesses under parallel test load;
16694        // the repository contention deadline itself remains one second.
16695        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16696            .await
16697            .unwrap()
16698            .unwrap();
16699        assert!(runner.state.parked);
16700        assert!(runner.state.prep_failure.is_none());
16701        let disk = RunState::load(&runner.state.id).unwrap();
16702        assert!(disk.driver_exited);
16703        assert_eq!(disk.driver_pid, None);
16704    }
16705
16706    #[tokio::test]
16707    #[cfg(unix)]
16708    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16709        use std::os::fd::AsRawFd as _;
16710        let tmp = tempfile::tempdir().unwrap();
16711        let mut runner = registered_runner(tmp.path()).await;
16712        runner.state.prep_complete = Some(false);
16713        runner.state.config.graph.timeout_resource_wait = 30;
16714        runner.state.save().unwrap();
16715        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16716        assert_eq!(
16717            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16718            0
16719        );
16720        assert!(
16721            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16722                .await
16723                .is_err()
16724        );
16725        let disk = RunState::load(&runner.state.id).unwrap();
16726        assert!(disk.driver_exited);
16727        assert_eq!(disk.driver_pid, None);
16728        assert!(disk.status.resumable());
16729        assert!(runner.state.driver_exited);
16730        assert_eq!(runner.state.driver_pid, None);
16731        runner.state.save().unwrap();
16732        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16733    }
16734
16735    #[tokio::test]
16736    #[cfg(unix)]
16737    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16738        let tmp = tempfile::tempdir().unwrap();
16739        let mut runner = registered_runner(tmp.path()).await;
16740        let winner = runner.state.candidates[0].clone();
16741        let cache = tmp.path().join("cache");
16742        let started = tmp.path().join("pre-gate-started");
16743        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16744        runner.state.config.verify.gate =
16745            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16746        let home = crate::run::home();
16747        let owner =
16748            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16749        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16750            crate::cache::AcquireOutcome::Acquired(g) => g,
16751            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16752        };
16753        let mut gate = Box::pin(runner.run_gate(&winner));
16754        assert!(
16755            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16756                .await
16757                .is_err()
16758        );
16759        assert!(!started.exists(), "pre-gate must wait for the cache too");
16760        // Simulate the wave that already owns the cache entering invoke.
16761        // It must obtain the editor reservation and finish without waiting
16762        // for the gate that is queued behind its cache.
16763        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16764        let editor = crate::repo_lock::SeatLease::checkout_with(
16765            &winner.worktree,
16766            true,
16767            crate::config::test_coordination().as_ref(),
16768            &wait,
16769        )
16770        .await
16771        .unwrap();
16772        drop(editor);
16773        guard.release();
16774        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16775            .await
16776            .unwrap()
16777            .unwrap();
16778        drop(gate);
16779        assert!(outcomes.iter().all(CommandOutcome::ok));
16780        assert!(started.exists());
16781    }
16782
16783    #[tokio::test]
16784    #[cfg(unix)]
16785    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16786        use std::os::fd::AsRawFd as _;
16787
16788        ask_test_home();
16789        let tmp = tempfile::tempdir().unwrap();
16790        let repo = tmp.path().join("repo");
16791        std::fs::create_dir_all(&repo).unwrap();
16792        init_repo(&repo);
16793        let common = repo.join(".git");
16794        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16795        let mut runner = runner_at(RunStatus::Prep);
16796        runner.state.repo = repo.clone();
16797        runner.state.config.coordination = crate::config::test_coordination();
16798        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16799        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16800        runner.state.config.graph.advise = false;
16801        runner.roles.implementers = vec![spec("implement")];
16802        runner.roles.judges = vec![spec("judge")];
16803        runner.prep().await.unwrap();
16804        let winner = runner.state.candidates[0].clone();
16805        // Emulate edits already left by a completed seat. The fixture CLI
16806        // only reports completion; it performs no repository operations.
16807        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16808        let completed = tmp.path().join("seat-completed");
16809        runner.roles.implementers[0].command = vec![
16810            "sh".into(),
16811            "-c".into(),
16812            format!("touch '{}'; echo completed", completed.display()),
16813        ];
16814        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16815        assert_eq!(
16816            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16817            0
16818        );
16819        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16820        let mut implement = Box::pin(runner.implement());
16821        tokio::select! {
16822            result = &mut implement => panic!("rescue must wait: {result:?}"),
16823            result = tokio::time::timeout(Duration::from_secs(10), async {
16824                while !completed.exists() {
16825                    tokio::time::sleep(Duration::from_millis(20)).await;
16826                }
16827            }) => result.unwrap(),
16828        }
16829        assert!(
16830            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16831                .await
16832                .is_err()
16833        );
16834        assert_eq!(
16835            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16836            before
16837        );
16838        assert_eq!(
16839            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16840            0
16841        );
16842        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16843            .await
16844            .unwrap()
16845            .unwrap();
16846        drop(implement);
16847        assert_ne!(
16848            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16849            before
16850        );
16851        assert!(git::is_clean(&winner.worktree).await.unwrap());
16852
16853        let started = tmp.path().join("pre-gate-started");
16854        let proceed = tmp.path().join("pre-gate-proceed");
16855        let checked = tmp.path().join("gate-ran");
16856        runner.state.config.verify.pre_gate = vec![format!(
16857            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16858            started.display(),
16859            proceed.display()
16860        )];
16861        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16862        assert_eq!(
16863            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16864            0
16865        );
16866        let mut gate = Box::pin(runner.run_gate(&winner));
16867        assert!(
16868            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16869                .await
16870                .is_err()
16871        );
16872        assert!(!started.exists());
16873        assert!(!checked.exists());
16874        assert!(git::is_clean(&winner.worktree).await.unwrap());
16875        assert_eq!(
16876            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16877            0
16878        );
16879        tokio::select! {
16880            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16881            result = tokio::time::timeout(Duration::from_secs(10), async {
16882                while !started.exists() {
16883                    tokio::time::sleep(Duration::from_millis(20)).await;
16884                }
16885            }) => result.unwrap(),
16886        }
16887        assert_eq!(
16888            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16889            -1,
16890            "mechanical edits must hold the real lock"
16891        );
16892        std::fs::write(proceed, "ready").unwrap();
16893        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16894            .await
16895            .unwrap()
16896            .unwrap();
16897        drop(gate);
16898        assert!(outcomes.iter().all(CommandOutcome::ok));
16899        assert!(checked.exists());
16900        assert!(runner.state.pre_gate_commit.is_some());
16901        assert!(git::is_clean(&winner.worktree).await.unwrap());
16902        assert_eq!(
16903            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16904            0,
16905            "gate completion must release coordination"
16906        );
16907        drop(outsider);
16908        std::fs::remove_file(common.join("updater.lock")).unwrap();
16909        std::fs::create_dir(common.join("updater.lock")).unwrap();
16910        std::fs::remove_file(&started).unwrap();
16911        std::fs::remove_file(&checked).unwrap();
16912        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16913        let error = runner.run_gate(&winner).await.unwrap_err();
16914        assert!(
16915            error
16916                .to_string()
16917                .contains("acquire mandatory repository lock")
16918        );
16919        assert!(
16920            !started.exists(),
16921            "failed acquisition must prevent pre-gate"
16922        );
16923        assert!(!checked.exists(), "failed acquisition must prevent gate");
16924        assert!(git::is_clean(&winner.worktree).await.unwrap());
16925        assert_eq!(
16926            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16927            head
16928        );
16929    }
16930
16931    #[tokio::test]
16932    #[cfg(unix)]
16933    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16934        use std::os::fd::AsRawFd as _;
16935        use std::time::Duration;
16936
16937        ask_test_home();
16938        let tmp = tempfile::tempdir().unwrap();
16939        let repo = tmp.path().join("repo");
16940        std::fs::create_dir_all(&repo).unwrap();
16941        init_repo(&repo);
16942        let common = repo.join(".git");
16943        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16944        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16945        assert_eq!(
16946            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16947            0
16948        );
16949        let mut runner = runner_at(RunStatus::Prep);
16950        runner.state.repo = repo.clone();
16951        runner.state.config.coordination = crate::config::test_coordination();
16952        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16953        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16954        runner.state.config.graph.advise = true;
16955        runner.state.config.graph.advisors = 1;
16956        runner.roles.implementers = vec![spec("implement")];
16957        runner.roles.judges = vec![spec("judge")];
16958        let root = runner.state.worktree_root();
16959        let started = tmp.path().join("setup-started");
16960        let proceed = tmp.path().join("setup-proceed");
16961        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16962            run: Some(format!(
16963                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16964                started.display(),
16965                proceed.display()
16966            )),
16967            ..Default::default()
16968        }];
16969        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16970        let config = git::git(&repo, &["config", "--local", "--list"])
16971            .await
16972            .unwrap();
16973        let mut prep = Box::pin(runner.prep());
16974        assert!(
16975            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16976                .await
16977                .is_err()
16978        );
16979        assert!(
16980            !root.exists(),
16981            "contention must prevent even checkout creation"
16982        );
16983        assert!(!started.exists(), "contention must prevent setup");
16984        assert_eq!(
16985            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16986            branches
16987        );
16988        assert_eq!(
16989            git::git(&repo, &["config", "--local", "--list"])
16990                .await
16991                .unwrap(),
16992            config
16993        );
16994        drop(lock);
16995        tokio::select! {
16996            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16997            result = tokio::time::timeout(Duration::from_secs(10), async {
16998                while !started.exists() {
16999                    tokio::time::sleep(Duration::from_millis(20)).await;
17000                }
17001            }) => result.unwrap(),
17002        }
17003        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17004        assert_eq!(
17005            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17006            -1
17007        );
17008        assert!(
17009            tokio::time::timeout(
17010                Duration::from_millis(100),
17011                crate::repo_lock::SeatLease::for_checkout(
17012                    &repo,
17013                    true,
17014                    crate::config::test_coordination().as_ref()
17015                )
17016            )
17017            .await
17018            .is_err(),
17019            "preparation must also exclude local editors"
17020        );
17021        std::fs::write(proceed, "ready").unwrap();
17022        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17023            .await
17024            .unwrap()
17025            .unwrap();
17026        drop(prep);
17027        assert_eq!(runner.state.prep_complete, Some(true));
17028        assert!(root.join("judge-1").exists());
17029        assert!(root.join("advisor-1").exists());
17030        assert_eq!(
17031            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17032            0
17033        );
17034    }
17035
17036    #[tokio::test]
17037    #[cfg(unix)]
17038    async fn preparation_lock_failure_prevents_repository_changes() {
17039        ask_test_home();
17040        let tmp = tempfile::tempdir().unwrap();
17041        let repo = tmp.path().join("repo");
17042        std::fs::create_dir_all(&repo).unwrap();
17043        init_repo(&repo);
17044        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17045        // A directory at the required lock path makes opening the real lock
17046        // fail, rather than merely exercising an invalid registration.
17047        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17048        let mut runner = runner_at(RunStatus::Prep);
17049        runner.state.repo = repo.clone();
17050        runner.state.config.coordination = crate::config::test_coordination();
17051        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17052        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17053        runner.roles.implementers = vec![spec("implement")];
17054        let error = runner.prep().await.unwrap_err();
17055        assert!(
17056            error
17057                .to_string()
17058                .contains("acquire mandatory repository lock")
17059        );
17060        assert!(!runner.state.worktree_root().exists());
17061        assert!(runner.state.candidates.is_empty());
17062        assert!(!repo.join(".git/config.worktree").exists());
17063        assert_eq!(
17064            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17065            "* main"
17066        );
17067    }
17068
17069    #[tokio::test]
17070    async fn preparation_records_creation_intent_before_git_can_fail() {
17071        ask_test_home();
17072        let tmp = tempfile::tempdir().unwrap();
17073        let repo = tmp.path().join("repo");
17074        std::fs::create_dir_all(&repo).unwrap();
17075        init_repo(&repo);
17076        let mut runner = runner_at(RunStatus::Prep);
17077        runner.state.repo = repo.clone();
17078        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17079        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17080        runner.state.config.blind.commit_msg_hook = false;
17081        runner.roles.implementers = vec![spec("one")];
17082        let label = blind::assign_labels(1, runner.state.seed)[0];
17083        let branch = runner.state.branch_for(label);
17084        // A conflicting branch makes Git refuse creation before a candidate
17085        // can be registered. The durable intent must still identify it.
17086        git::git(&repo, &["branch", &branch]).await.unwrap();
17087        assert!(runner.prep().await.is_err());
17088        let saved = RunState::load(&runner.state.id).unwrap();
17089        assert!(saved.candidates.is_empty());
17090        let event = saved
17091            .events
17092            .iter()
17093            .find(|e| e.node == "prep-intent")
17094            .unwrap();
17095        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17096        assert_eq!(intent["branch"], branch);
17097        assert_eq!(intent["start"], runner.state.base_commit);
17098        assert_eq!(
17099            intent["worktree"],
17100            runner
17101                .state
17102                .worktree_root()
17103                .join(format!("cand-{label}"))
17104                .to_string_lossy()
17105                .as_ref()
17106        );
17107        assert_eq!(intent["picks"], serde_json::json!([]));
17108    }
17109
17110    #[tokio::test]
17111    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17112        ask_test_home();
17113        let tmp = tempfile::tempdir().unwrap();
17114        let repo = tmp.path().join("repo");
17115        std::fs::create_dir_all(&repo).unwrap();
17116        init_repo(&repo);
17117        let mut runner = runner_at(RunStatus::Prep);
17118        runner.state.repo = repo.clone();
17119        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17120        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17121        runner.state.sources.pick_commits.push(refs::Input {
17122            token: "missing".into(),
17123            sha: "0".repeat(40),
17124            provenance: refs::Provenance::ExplicitCli,
17125        });
17126        assert!(runner.prep().await.is_err());
17127        assert!(runner.state.candidates.is_empty());
17128        assert!(!runner.state.worktree_root().exists());
17129    }
17130
17131    #[tokio::test]
17132    async fn prose_and_legacy_inference_never_import_into_candidates() {
17133        ask_test_home();
17134        let tmp = tempfile::tempdir().unwrap();
17135        let repo = tmp.path().join("repo");
17136        std::fs::create_dir_all(&repo).unwrap();
17137        init_repo(&repo);
17138        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17139        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17140            .await
17141            .unwrap();
17142        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17143        git::git(&repo, &["add", "."]).await.unwrap();
17144        git::git(&repo, &["commit", "-m", "historical implementation"])
17145            .await
17146            .unwrap();
17147        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17148        git::git(&repo, &["checkout", "main"]).await.unwrap();
17149        for instruction in [
17150            format!("Example: magi/history/A at {source}"),
17151            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17152            format!("Never import magi/history/A or {source}"),
17153            format!("Conversation answer: I mentioned {source} only as background"),
17154        ] {
17155            let mut runner = runner_at(RunStatus::Prep);
17156            runner.state.repo = repo.clone();
17157            runner.state.base_commit = base.clone();
17158            runner.state.instruction = instruction.clone();
17159            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17160            runner.state.config.blind.commit_msg_hook = false;
17161            runner.state.seeds = vec![refs::Seed {
17162                token: "magi/history/A".into(),
17163                sha: source.clone(),
17164                kind: refs::SeedKind::Unmerged,
17165                branch: true,
17166                detail: String::new(),
17167            }];
17168            runner.roles.implementers = vec![spec("one")];
17169            assert_eq!(seeded_instruction(&runner.state), instruction);
17170            // Model an old record with inferred seeds but no structured input field.
17171            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17172            legacy.as_object_mut().unwrap().remove("sources");
17173            runner.state = serde_json::from_value(legacy).unwrap();
17174            assert_eq!(runner.state.sources, refs::Sources::default());
17175            runner.state.save().unwrap();
17176            runner.state = RunState::load(&runner.state.id).unwrap();
17177            runner.prep().await.unwrap();
17178            for candidate in &runner.state.candidates {
17179                assert_eq!(
17180                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17181                    base
17182                );
17183                assert!(!candidate.worktree.join("unwanted").exists());
17184            }
17185        }
17186    }
17187
17188    #[tokio::test]
17189    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17190        ask_test_home();
17191        let tmp = tempfile::tempdir().unwrap();
17192        let repo = tmp.path().join("repo");
17193        std::fs::create_dir_all(&repo).unwrap();
17194        init_repo(&repo);
17195        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17196        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17197        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17198        git::git(&repo, &["add", "."]).await.unwrap();
17199        git::git(&repo, &["commit", "-m", "required seed"])
17200            .await
17201            .unwrap();
17202        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17203        git::git(&repo, &["checkout", "main"]).await.unwrap();
17204        let mut runner = runner_at(RunStatus::Prep);
17205        runner.state.repo = repo.clone();
17206        runner.state.base_commit = base.clone();
17207        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17208        runner.state.config.graph.advise = false;
17209        runner.state.config.blind.commit_msg_hook = false;
17210        runner.state.sources =
17211            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17212                .await
17213                .unwrap();
17214        runner.roles.implementers = vec![spec("one"), spec("two")];
17215        runner.roles.judges = vec![spec("judge")];
17216        let label = blind::assign_labels(2, runner.state.seed)[0];
17217        let branch = runner.state.branch_for(label);
17218        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17219        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17220            .await
17221            .unwrap();
17222        runner.state.candidates.push(Candidate {
17223            index: 0,
17224            label,
17225            agent: "one".into(),
17226            branch,
17227            worktree,
17228            summary: String::new(),
17229            stat: String::new(),
17230            files: 0,
17231            commits: 0,
17232            empty: false,
17233            failed: None,
17234            verified_noop: None,
17235            duration_ms: 0,
17236            folded: false,
17237        });
17238        runner.state.save().unwrap();
17239        // Reload the checkpoint immediately before its first cherry-pick.
17240        runner.state = RunState::load(&runner.state.id).unwrap();
17241        assert_eq!(runner.state.prep_complete, Some(false));
17242        runner.prep().await.unwrap();
17243        assert_eq!(runner.state.prep_complete, Some(true));
17244        assert_eq!(runner.state.candidates.len(), 2);
17245        for candidate in &runner.state.candidates {
17246            assert_eq!(
17247                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17248                git::tree_of(&repo, &seed).await.unwrap()
17249            );
17250            assert_eq!(
17251                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17252                "required commit"
17253            );
17254        }
17255        assert!(runner.state.worktree_root().join("judge-1").exists());
17256        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17257        runner.prep().await.unwrap();
17258        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17259
17260        runner.state.prep_complete = Some(false);
17261        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17262            run: Some(format!(
17263                "test -f '{}'",
17264                tmp.path().join("dependency-ready").display()
17265            )),
17266            ..Default::default()
17267        }];
17268        assert!(runner.prep().await.is_err());
17269        assert!(runner.state.prep_failure.is_some());
17270        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17271        runner.state = RunState::load(&runner.state.id).unwrap();
17272        assert!(
17273            runner.prep().await.is_err(),
17274            "correcting the cause alone must not auto-retry"
17275        );
17276        let failed_at = runner.state.events.last().unwrap().at;
17277        assert!(
17278            runner.retry_preparation(failed_at).is_err(),
17279            "old approvals cannot unlock the hold"
17280        );
17281        let mut task = crate::queue::Task::new(
17282            "retry".into(),
17283            "retry setup".into(),
17284            repo.clone(),
17285            crate::queue::Source::Human,
17286        );
17287        task.start(runner.state.id.clone());
17288        task.hold_machine(Some("setup failed".into()));
17289        task.release_operator("cli", None);
17290        runner
17291            .retry_preparation(task.resumption.as_ref().unwrap().at)
17292            .unwrap();
17293        runner.prep().await.unwrap();
17294        assert!(runner.state.prep_failure.is_none());
17295        assert_eq!(runner.state.prep_complete, Some(true));
17296        assert_eq!(runner.state.candidates.len(), 2);
17297        assert!(runner.state.worktree_root().join("judge-1").exists());
17298        for candidate in &runner.state.candidates {
17299            assert_eq!(
17300                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17301                git::tree_of(&repo, &seed).await.unwrap()
17302            );
17303        }
17304    }
17305
17306    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17307        let mut heads = Vec::new();
17308        for candidate in candidates {
17309            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17310        }
17311        heads
17312    }
17313
17314    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17315        ask_test_home();
17316        let tmp = tempfile::tempdir().unwrap();
17317        let repo = tmp.path().join("repo");
17318        std::fs::create_dir(&repo).unwrap();
17319        init_repo(&repo);
17320        let mut runner = runner_at(RunStatus::Reviewing);
17321        runner.state.repo = repo.clone();
17322        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17323        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17324        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17325            let branch = format!("candidate-{label}");
17326            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17327            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17328                .await
17329                .unwrap();
17330            if label == 'B' {
17331                std::fs::write(worktree.join("change"), "winner").unwrap();
17332                git::rescue_commit(&worktree, "candidate change")
17333                    .await
17334                    .unwrap();
17335            }
17336            runner.state.candidates.push(Candidate {
17337                index,
17338                label,
17339                agent: "alpha".into(),
17340                branch,
17341                worktree,
17342                summary: "completed reply".into(),
17343                stat: String::new(),
17344                files: usize::from(label == 'B'),
17345                commits: usize::from(label == 'B'),
17346                empty: label == 'A',
17347                failed: None,
17348                verified_noop: None,
17349                duration_ms: 1,
17350                folded: false,
17351            });
17352        }
17353        runner.state.judge_skipped = true;
17354        runner.state.tally = Some(Tally {
17355            first_choice: BTreeMap::new(),
17356            borda: BTreeMap::new(),
17357            winner: 'B',
17358            rankings: 0,
17359            unanimous_initial: false,
17360            deliberated: false,
17361            changed_votes: 0,
17362            unanimous_final: false,
17363            tie_break: None,
17364            judges: 0,
17365            present: 0,
17366            quorum: 0,
17367            met_quorum: true,
17368            uncontested: Some("only B produced a change".into()),
17369        });
17370        runner.state.save().unwrap();
17371        (tmp, runner)
17372    }
17373
17374    #[tokio::test]
17375    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17376        let (_tmp, mut runner) = preservation_resume_fixture().await;
17377        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17378        runner.state.config.disk.cache_limit_bytes = 0;
17379        runner.state.config.graph.advise = true;
17380        runner.state.config.graph.advisors = 1;
17381        let advisor = runner.state.worktree_root().join("advisor-1");
17382        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17383            .await
17384            .unwrap();
17385        let home = crate::run::home();
17386        let loser =
17387            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17388        let winner =
17389            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17390        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17391        for target in [&loser, &winner, &advisor] {
17392            std::fs::write(target.join("build-output"), "compiled").unwrap();
17393        }
17394
17395        runner.fold_losers().await.unwrap();
17396
17397        assert!(!loser.join("build-output").exists());
17398        assert!(!advisor.join("build-output").exists());
17399        assert!(winner.join("build-output").is_file());
17400    }
17401
17402    #[tokio::test]
17403    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17404        let (_tmp, mut runner) = preservation_resume_fixture().await;
17405        runner.state.candidates[0].folded = true;
17406        runner.state.config.graph.advise = true;
17407        runner.state.config.graph.advisors = 2;
17408        let repo = runner.state.repo.clone();
17409        let root = runner.state.worktree_root();
17410        let discarded = root.join("advisor-1");
17411        git::worktree_add_detached(&repo, &discarded, "main")
17412            .await
17413            .unwrap();
17414        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17415        let protected = root.join("advisor-2");
17416        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17417            .await
17418            .unwrap();
17419        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17420        runner.state.save().unwrap();
17421
17422        assert!(runner.fold_losers().await.is_err());
17423        assert!(!discarded.exists());
17424        assert!(protected.join("keep").exists());
17425        let saved = RunState::load(&runner.state.id).unwrap();
17426        assert!(saved.events.iter().any(|event| {
17427            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17428        }));
17429    }
17430
17431    #[tokio::test]
17432    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17433        let (tmp, mut runner) = preservation_resume_fixture().await;
17434        let repo = runner.state.repo.clone();
17435        let root = runner.state.worktree_root();
17436        for name in ["advisor-3", "judge-1", "review-2"] {
17437            let path = root.join(name);
17438            git::worktree_add_detached(&repo, &path, "main")
17439                .await
17440                .unwrap();
17441            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17442            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17443            remove_read_seat_worktree(&mut runner.state, &path)
17444                .await
17445                .unwrap();
17446            assert!(!path.exists());
17447        }
17448        let outside = tmp.path().join("advisor-1");
17449        let unknown = root.join("unknown");
17450        let attached = root.join("advisor-4");
17451        git::worktree_add_detached(&repo, &outside, "main")
17452            .await
17453            .unwrap();
17454        git::worktree_add_detached(&repo, &unknown, "main")
17455            .await
17456            .unwrap();
17457        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17458            .await
17459            .unwrap();
17460        let foreign = tmp.path().join("foreign");
17461        std::fs::create_dir(&foreign).unwrap();
17462        init_repo(&foreign);
17463        let wrong_repo = root.join("judge-2");
17464        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17465            .await
17466            .unwrap();
17467        let candidate = runner.state.candidates[0].worktree.clone();
17468        for path in [outside, unknown, attached, wrong_repo, candidate] {
17469            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17470            assert!(
17471                remove_read_seat_worktree(&mut runner.state, &path)
17472                    .await
17473                    .is_err()
17474            );
17475            assert_eq!(
17476                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17477                "keep"
17478            );
17479        }
17480    }
17481
17482    #[tokio::test]
17483    #[cfg(unix)]
17484    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17485        for (solo, failed_checkpoint) in
17486            [(true, false), (false, false), (true, true), (false, true)]
17487        {
17488            let (_tmp, mut runner) = preservation_resume_fixture().await;
17489            if solo {
17490                runner.state.candidates.retain(|c| c.label == 'A');
17491            }
17492            runner.state.candidates[0].empty = false;
17493            runner.state.candidates[0].summary.clear();
17494            runner.state.tally = None;
17495            runner.state.judge_skipped = false;
17496            runner.state.status = RunStatus::Implementing;
17497            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17498            let mut implementer = spec("alpha");
17499            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17500            runner.roles.implementers = vec![implementer];
17501            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17502            if failed_checkpoint {
17503                std::fs::create_dir_all(&patch).unwrap();
17504            }
17505            runner.state.save().unwrap();
17506            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17507            drop(pressure);
17508            runner.state = RunState::load(&runner.state.id).unwrap();
17509            assert_eq!(runner.state.status, RunStatus::Blocked);
17510            assert!(runner.state.interrupted_implementations.contains(&'A'));
17511            assert_eq!(runner.state.candidates[0].commits, 0);
17512            assert!(!runner.state.candidates[0].empty);
17513            assert!(runner.state.candidates[0].failed.is_none());
17514            if failed_checkpoint {
17515                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17516                std::fs::remove_dir(patch).unwrap();
17517            }
17518            runner.state.resource_block = None;
17519            runner.state.config.disk.min_free_bytes = 0;
17520            runner.roles.implementers[0].command = vec![
17521                "sh".into(),
17522                "-c".into(),
17523                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17524            ];
17525            runner.implement().await.unwrap();
17526            assert!(runner.state.interrupted_implementations.is_empty());
17527            assert!(runner.state.candidate_preservation.is_empty());
17528            assert_eq!(runner.state.candidates[0].commits, 1);
17529            assert!(!runner.state.candidates[0].empty);
17530            assert!(
17531                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17532                    .unwrap()
17533                    .contains("retried empty interrupted seat")
17534            );
17535            if !solo {
17536                assert_eq!(runner.state.candidates[1].commits, 1);
17537            }
17538        }
17539    }
17540
17541    #[tokio::test]
17542    #[cfg(unix)]
17543    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17544        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17545            let (_tmp, mut runner) = preservation_resume_fixture().await;
17546            runner.state.candidates.retain(|c| c.label == 'A');
17547            runner.state.candidates[0].empty = false;
17548            runner.state.candidates[0].summary.clear();
17549            runner.state.tally = None;
17550            runner.state.judge_skipped = false;
17551            runner.state.status = RunStatus::Implementing;
17552            // Force only the real post-spawn watchdog, without failing the
17553            // separate admission check. Existing edits predate its measurement.
17554            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17555            let wt = runner.state.candidates[0].worktree.clone();
17556            std::fs::write(
17557                wt.join("interrupted-source"),
17558                "retain implementation work\n",
17559            )
17560            .unwrap();
17561            if committed {
17562                git::rescue_commit(&wt, "implementation checkpoint")
17563                    .await
17564                    .unwrap();
17565            }
17566            let lock = git::git(
17567                &wt,
17568                &[
17569                    "rev-parse",
17570                    "--path-format=absolute",
17571                    "--git-path",
17572                    "index.lock",
17573                ],
17574            )
17575            .await
17576            .unwrap();
17577            if block_rescue {
17578                std::fs::write(&lock, "fixture-owned lock").unwrap();
17579            }
17580            let mut implementer = spec("alpha");
17581            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17582            runner.roles.implementers = vec![implementer];
17583            runner.state.save().unwrap();
17584            let result = runner.implement().await;
17585            drop(pressure);
17586            assert_eq!(result.is_err(), block_rescue);
17587            assert_eq!(
17588                runner.state.resource_block.as_ref().unwrap().kind,
17589                "disk pressure"
17590            );
17591            assert!(
17592                runner
17593                    .state
17594                    .events
17595                    .iter()
17596                    .any(|e| e.message.contains("agent execution interrupted"))
17597            );
17598            assert!(
17599                runner
17600                    .state
17601                    .dir()
17602                    .join("artifacts/candidate-A-recovery/staged.patch")
17603                    .exists()
17604            );
17605            if block_rescue {
17606                let saved = RunState::load(&runner.state.id).unwrap();
17607                assert!(saved.candidate_preservation.contains_key(&'A'));
17608                assert!(!saved.candidates[0].empty);
17609                assert_eq!(
17610                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17611                    "retain implementation work\n"
17612                );
17613                std::fs::remove_file(lock).unwrap();
17614                runner.state = saved;
17615            } else {
17616                assert_eq!(runner.state.status, RunStatus::Blocked);
17617                assert_eq!(runner.state.candidates[0].commits, 1);
17618            }
17619            // Recovery must save the candidate before deciding whether another
17620            // implementation is needed. No implementer is available on retry.
17621            runner.roles.implementers.clear();
17622            runner.state.config.disk.min_free_bytes = 0;
17623            runner.state.resource_block = None;
17624            runner.implement().await.unwrap();
17625            assert!(runner.state.candidate_preservation.is_empty());
17626            assert_eq!(runner.state.candidates[0].commits, 1);
17627            assert!(!runner.state.candidates[0].empty);
17628            assert!(git::is_clean(&wt).await.unwrap());
17629            assert!(
17630                crate::run::read_artifact(&runner.state, "cand-A.patch")
17631                    .unwrap()
17632                    .contains("retain implementation work")
17633            );
17634        }
17635    }
17636
17637    #[tokio::test]
17638    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17639        let (_tmp, mut runner) = preservation_resume_fixture().await;
17640        // Schema 15 already confirmed the unfolded no-change result.
17641        runner.implement().await.unwrap();
17642        assert!(runner.state.candidate_preservation.is_empty());
17643        assert!(
17644            !runner
17645                .state
17646                .dir()
17647                .join("artifacts/candidate-A-recovery")
17648                .exists()
17649        );
17650        runner.fold_losers().await.unwrap();
17651        assert!(!runner.state.candidates[0].worktree.exists());
17652        for schema in [14, crate::run::SCHEMA] {
17653            runner.state.schema = schema;
17654            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17655            runner.state.save().unwrap();
17656            runner.state = RunState::load(&runner.state.id).unwrap();
17657            runner.implement().await.unwrap();
17658            assert!(runner.state.candidate_preservation.is_empty());
17659            assert!(runner.state.candidates[0].folded);
17660            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17661        }
17662    }
17663
17664    #[tokio::test]
17665    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17666        let (_tmp, mut runner) = preservation_resume_fixture().await;
17667        runner.state.candidates.retain(|c| c.label == 'A');
17668        runner.state.tally = None;
17669        runner.state.judge_skipped = false;
17670        let candidate = &mut runner.state.candidates[0];
17671        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17672        candidate.failed = Some("deployment validation unavailable".into());
17673        std::fs::write(
17674            candidate.worktree.join("repair"),
17675            "future launcher policy\n",
17676        )
17677        .unwrap();
17678        runner
17679            .state
17680            .candidate_preservation
17681            .insert('A', "awaiting persistence".into());
17682        runner.persist_candidates().await.unwrap();
17683        let candidate = &runner.state.candidates[0];
17684        assert!(!candidate.empty);
17685        assert_eq!(candidate.commits, 1);
17686        assert_eq!(candidate.files, 1);
17687        assert!(candidate.failed.is_none());
17688        assert!(candidate.summary.contains("EPERM"));
17689        assert!(
17690            crate::run::read_artifact(&runner.state, "cand-A.patch")
17691                .unwrap()
17692                .contains("future launcher policy")
17693        );
17694        assert!(runner.state.candidate_preservation.is_empty());
17695    }
17696
17697    #[tokio::test]
17698    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17699        let (_tmp, mut runner) = preservation_resume_fixture().await;
17700        let wt = runner.state.candidates[0].worktree.clone();
17701        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17702        runner.state.schema = 14;
17703        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17704        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17705        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17706        for _ in 0..2 {
17707            assert!(runner.implement().await.is_err());
17708            assert_eq!(runner.state.status, RunStatus::Blocked);
17709            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17710            assert!(
17711                runner.state.candidates[0].empty,
17712                "old verdict must remain unusable"
17713            );
17714            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17715            assert!(runner.state.judge_skipped);
17716            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17717            assert!(
17718                crate::run::read_artifact(&runner.state, "cand-A.patch")
17719                    .unwrap()
17720                    .contains("owned edits")
17721            );
17722            assert!(wt.exists());
17723            assert_eq!(
17724                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17725                    .await
17726                    .unwrap(),
17727                1
17728            );
17729            runner.state = RunState::load(&runner.state.id).unwrap();
17730        }
17731    }
17732
17733    #[tokio::test]
17734    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17735        let (_tmp, mut runner) = preservation_resume_fixture().await;
17736        let wt = runner.state.candidates[0].worktree.clone();
17737        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17738        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17739        let index_lock = PathBuf::from(
17740            git::git(
17741                &wt,
17742                &[
17743                    "rev-parse",
17744                    "--path-format=absolute",
17745                    "--git-path",
17746                    "index.lock",
17747                ],
17748            )
17749            .await
17750            .unwrap(),
17751        );
17752        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17753        runner.state.schema = 14;
17754        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17755        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17756        assert!(runner.implement().await.is_err());
17757        assert!(runner.after_implement().is_err());
17758        assert!(runner.fold_losers().await.is_err());
17759        assert_eq!(
17760            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17761            "failed seat edits"
17762        );
17763        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17764        runner.state = RunState::load(&runner.state.id).unwrap();
17765        std::fs::remove_file(index_lock).unwrap();
17766        // Recovery finds changes that the old uncontested result never judged.
17767        assert!(runner.implement().await.is_err());
17768        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17769        assert!(runner.state.candidates[0].empty);
17770        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17771        assert!(
17772            crate::run::read_artifact(&runner.state, "cand-A.patch")
17773                .unwrap()
17774                .contains("failed seat edits")
17775        );
17776        assert!(wt.exists());
17777    }
17778
17779    #[tokio::test]
17780    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17781        let (_tmp, mut runner) = preservation_resume_fixture().await;
17782        let repo = runner.state.repo.clone();
17783        let common = git::git(
17784            &repo,
17785            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17786        )
17787        .await
17788        .unwrap();
17789        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17790        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17791        assert!(runner.fold_losers().await.is_err());
17792        assert!(!runner.state.candidates[0].worktree.exists());
17793        assert!(!runner.state.candidates[0].folded);
17794        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17795        runner.state = RunState::load(&runner.state.id).unwrap();
17796        std::fs::remove_file(branch_lock).unwrap();
17797        let judge = runner.state.worktree_root().join("judge-1");
17798        git::worktree_add_detached(&repo, &judge, "main")
17799            .await
17800            .unwrap();
17801        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17802        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17803            .await
17804            .unwrap();
17805        runner.roles.judges = vec![spec("judge")];
17806        assert!(runner.fold_losers().await.is_err());
17807        runner.state = RunState::load(&runner.state.id).unwrap();
17808        assert!(
17809            runner.state.candidates[0].folded,
17810            "candidate progress saved before judge failure"
17811        );
17812        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17813        assert!(judge.join("uncommitted").exists());
17814        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17815            .await
17816            .unwrap();
17817        runner.fold_losers().await.unwrap();
17818        assert!(!judge.exists());
17819        runner.fold_losers().await.unwrap();
17820    }
17821
17822    #[tokio::test]
17823    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17824        let (_tmp, mut runner) = preservation_resume_fixture().await;
17825        runner.state.candidates.retain(|c| c.label == 'B');
17826        runner.state.tally = None;
17827        runner.state.judge_skipped = false;
17828        runner.state.prep_complete = Some(true);
17829        runner.state.config.graph.advise = false;
17830        runner.state.config.graph.selected_implementer = Some("alpha".into());
17831        let wt = runner.state.candidates[0].worktree.clone();
17832        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17833        runner
17834            .state
17835            .candidate_preservation
17836            .insert('B', "awaiting persistence".into());
17837        let index_lock = git::git(
17838            &wt,
17839            &[
17840                "rev-parse",
17841                "--path-format=absolute",
17842                "--git-path",
17843                "index.lock",
17844            ],
17845        )
17846        .await
17847        .unwrap();
17848        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17849        runner.state.save().unwrap();
17850        assert!(runner.execute_graph().await.is_err());
17851        assert_eq!(runner.state.status, RunStatus::Blocked);
17852        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17853        std::fs::remove_file(index_lock).unwrap();
17854        // Park at the next graph boundary: this tests the real selected-seat
17855        // hold guard without dispatching reviewers or publishing anything.
17856        for _ in 0..2 {
17857            runner.state = RunState::load(&runner.state.id).unwrap();
17858            runner.pause.park();
17859            runner.execute_graph().await.unwrap();
17860            assert_eq!(runner.state.status, RunStatus::Implementing);
17861            assert!(runner.state.candidate_preservation.is_empty());
17862            assert_eq!(runner.state.candidates[0].commits, 2);
17863            assert!(runner.state.tally.is_none());
17864        }
17865        runner.implement().await.unwrap();
17866        assert_eq!(runner.state.status, RunStatus::Judging);
17867        // A genuine selected-implementer hold must still require release.
17868        runner.state.status = RunStatus::Blocked;
17869        runner.state.candidates[0].failed = Some("implementation failed".into());
17870        runner.state.save().unwrap();
17871        let error = runner.execute_graph().await.unwrap_err();
17872        assert!(
17873            error
17874                .to_string()
17875                .contains("selected implementation is held")
17876        );
17877    }
17878
17879    #[tokio::test]
17880    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17881        let (_tmp, mut runner) = preservation_resume_fixture().await;
17882        let repo = runner.state.repo.clone();
17883        let candidate = runner.state.candidates[0].clone();
17884        // Remove only the disposable fixture directory, leaving Git's linked
17885        // worktree registration and branch intact, as in a vanished checkout.
17886        let registered = git::worktree_holding(&repo, &candidate.branch)
17887            .await
17888            .unwrap()
17889            .unwrap();
17890        assert_eq!(
17891            registered.canonicalize().unwrap(),
17892            candidate.worktree.canonicalize().unwrap()
17893        );
17894        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17895        assert_eq!(
17896            git::worktree_holding(&repo, &candidate.branch)
17897                .await
17898                .unwrap(),
17899            Some(registered)
17900        );
17901        assert!(
17902            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17903            "the stale registration initially keeps the branch checked out"
17904        );
17905        runner.fold_losers().await.unwrap();
17906        assert!(runner.state.candidates[0].folded);
17907        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17908        assert_eq!(
17909            git::worktree_holding(&repo, &candidate.branch)
17910                .await
17911                .unwrap(),
17912            None
17913        );
17914        runner.state = RunState::load(&runner.state.id).unwrap();
17915        runner.fold_losers().await.unwrap();
17916    }
17917
17918    #[tokio::test]
17919    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17920        let (_tmp, mut runner) = preservation_resume_fixture().await;
17921        let repo = runner.state.repo.clone();
17922        let candidate = runner.state.candidates[0].clone();
17923        let winner = runner.state.candidates[1].clone();
17924        let registered = git::worktree_holding(&repo, &candidate.branch)
17925            .await
17926            .unwrap()
17927            .unwrap();
17928        assert_eq!(
17929            registered.canonicalize().unwrap(),
17930            candidate.worktree.canonicalize().unwrap()
17931        );
17932        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17933        assert_eq!(
17934            git::worktree_holding(&repo, &candidate.branch)
17935                .await
17936                .unwrap(),
17937            Some(registered)
17938        );
17939        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17940
17941        for _ in 0..2 {
17942            fold_run(&mut runner.state, false, &crate::run::home())
17943                .await
17944                .unwrap();
17945            runner.state = RunState::load(&runner.state.id).unwrap();
17946            assert!(runner.state.candidates[0].folded);
17947            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17948            assert_eq!(
17949                git::worktree_holding(&repo, &candidate.branch)
17950                    .await
17951                    .unwrap(),
17952                None
17953            );
17954            assert!(!runner.state.candidates[1].folded);
17955            assert!(winner.worktree.exists());
17956            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17957        }
17958    }
17959
17960    /// The recovery-retention override, refused for the rule under test. The
17961    /// arrangement is saved in `home` before each call, so `record gone` or
17962    /// `unreadable` would be the fixture's mistake and fails here.
17963    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
17964        let error = fold_run_overriding_recovery_retention(state, true, home)
17965            .await
17966            .expect_err("the override is refused");
17967        assert!(
17968            !matches!(
17969                error.downcast_ref::<FoldRefusal>(),
17970                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
17971            ),
17972            "refused for the wrong reason: {error:#}"
17973        );
17974        error
17975    }
17976
17977    #[tokio::test]
17978    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17979        for sidecar in [false, true] {
17980            let tmp = tempfile::tempdir().unwrap();
17981            let home = tmp.path().join("home");
17982            let repo = tmp.path().join("repo");
17983            std::fs::create_dir(&repo).unwrap();
17984            init_repo(&repo);
17985            let mut state = runner_at(RunStatus::Superseded).state;
17986            state.repo = repo.clone();
17987            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17988            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17989            state.driver_exited = true;
17990            state.reserve_under(&home).unwrap();
17991            git::git(
17992                &repo,
17993                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17994            )
17995            .await
17996            .unwrap();
17997            let wt = state.worktree_root().join("cand-A");
17998            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17999                .await
18000                .unwrap();
18001            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18002            git::commit_all(&wt, "fixture: independent source")
18003                .await
18004                .unwrap();
18005            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18006            state.candidates.push(Candidate {
18007                index: 0,
18008                label: 'A',
18009                agent: "fixture".into(),
18010                branch: "candidate".into(),
18011                worktree: wt.clone(),
18012                summary: String::new(),
18013                stat: String::new(),
18014                files: 0,
18015                commits: 0,
18016                empty: false,
18017                failed: None,
18018                verified_noop: None,
18019                duration_ms: 0,
18020                folded: false,
18021            });
18022            let mut task = crate::queue::Task::new(
18023                "task".into(),
18024                "task".into(),
18025                repo.clone(),
18026                crate::queue::Source::Human,
18027            );
18028            task.runs.push(state.id.clone());
18029            crate::queue::Queue::at(home.join("queue"))
18030                .put(&mut task)
18031                .unwrap();
18032            if sidecar {
18033                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18034            }
18035            state.save_under(&home).unwrap();
18036            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18037            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18038            assert!(
18039                matches!(
18040                    refusal.downcast_ref::<FoldRefusal>(),
18041                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18042                ),
18043                "{refusal:#}"
18044            );
18045            let mut disk = state.config.disk.clone();
18046            disk.fold_grace_secs = 0;
18047            assert_eq!(
18048                crate::clean::fold_due(
18049                    &home.join("runs"),
18050                    &home,
18051                    &state.worktree_root(),
18052                    &disk,
18053                    Timestamp::now() + std::time::Duration::from_secs(10),
18054                )
18055                .await
18056                .unwrap(),
18057                (0, 0)
18058            );
18059            assert!(wt.exists());
18060            state.status = RunStatus::Blocked;
18061            state.save_under(&home).unwrap();
18062            let error = override_refusal(&mut state, &home).await;
18063            assert!(
18064                error
18065                    .to_string()
18066                    .contains("requires a finished, non-resumable run"),
18067                "{error:#}"
18068            );
18069            state.status = RunStatus::Superseded;
18070            state.driver_exited = false;
18071            state.driver_claimed = None;
18072            state.save_under(&home).unwrap();
18073            let error = override_refusal(&mut state, &home).await;
18074            assert!(
18075                error
18076                    .to_string()
18077                    .contains("run is live or its ownership is unknown"),
18078                "{error:#}"
18079            );
18080            state.driver_pid = Some(std::process::id());
18081            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18082            state.save_under(&home).unwrap();
18083            let error = override_refusal(&mut state, &home).await;
18084            assert!(
18085                error
18086                    .to_string()
18087                    .contains("run is live or its ownership is unknown"),
18088                "{error:#}"
18089            );
18090            state.driver_exited = true;
18091            state.driver_pid = None;
18092            state.driver_started_at = None;
18093            state.save_under(&home).unwrap();
18094            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18095            let error = override_refusal(&mut state, &home).await;
18096            assert!(
18097                matches!(
18098                    error.downcast_ref::<FoldRefusal>(),
18099                    Some(FoldRefusal::Live(_))
18100                ),
18101                "{error:#}"
18102            );
18103            drop(lease);
18104            #[cfg(unix)]
18105            {
18106                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18107                let error = override_refusal(&mut state, &home).await;
18108                assert!(
18109                    matches!(
18110                        error.downcast_ref::<FoldRefusal>(),
18111                        Some(FoldRefusal::Live(_))
18112                    ),
18113                    "{error:#}"
18114                );
18115                drop(output);
18116            }
18117            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18118            let error = override_refusal(&mut state, &home).await;
18119            assert!(
18120                matches!(
18121                    error.downcast_ref::<FoldRefusal>(),
18122                    Some(FoldRefusal::Live(_))
18123                ),
18124                "{error:#}"
18125            );
18126            drop(owner);
18127            let checkpoint = git::git(
18128                &wt,
18129                &[
18130                    "rev-parse",
18131                    "--path-format=absolute",
18132                    "--git-path",
18133                    "CHERRY_PICK_HEAD",
18134                ],
18135            )
18136            .await
18137            .unwrap();
18138            std::fs::write(&checkpoint, &head).unwrap();
18139            let error = override_refusal(&mut state, &home).await;
18140            assert!(
18141                matches!(
18142                    error.downcast_ref::<FoldRefusal>(),
18143                    Some(FoldRefusal::ProofIncomplete(detail))
18144                        if detail.contains("Git recovery checkpoint retained")
18145                ),
18146                "{error:#}"
18147            );
18148            std::fs::remove_file(checkpoint).unwrap();
18149            std::fs::write(wt.join("dirty"), "keep").unwrap();
18150            let error = override_refusal(&mut state, &home).await;
18151            assert!(
18152                matches!(
18153                    error.downcast_ref::<FoldRefusal>(),
18154                    Some(FoldRefusal::ProofIncomplete(_))
18155                ),
18156                "{error:#}"
18157            );
18158            assert!(wt.join("dirty").exists());
18159            std::fs::remove_file(wt.join("dirty")).unwrap();
18160            let evidence = home
18161                .join("runs")
18162                .join(&state.id)
18163                .join("artifacts/fold-evidence");
18164            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18165            std::fs::write(&evidence, "blocked archive").unwrap();
18166            let error = override_refusal(&mut state, &home).await;
18167            assert!(
18168                matches!(
18169                    error.downcast_ref::<FoldRefusal>(),
18170                    Some(FoldRefusal::ProofIncomplete(_))
18171                ),
18172                "{error:#}"
18173            );
18174            assert!(wt.exists());
18175            assert!(
18176                !RunState::load_under(&state.id, &home)
18177                    .unwrap()
18178                    .events
18179                    .iter()
18180                    .any(|event| event.message.contains("--override-recovery-retention"))
18181            );
18182            std::fs::remove_file(&evidence).unwrap();
18183            fold_run_overriding_recovery_retention(&mut state, true, &home)
18184                .await
18185                .unwrap();
18186            assert!(!wt.exists());
18187            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18188            assert!(
18189                git::worktree_holding(&repo, "candidate")
18190                    .await
18191                    .unwrap()
18192                    .is_none()
18193            );
18194            assert!(
18195                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18196                    .unwrap()
18197                    .contains("retained implementation")
18198            );
18199            assert!(evidence.join(format!("{head}.index")).is_file());
18200            let saved = RunState::load_under(&state.id, &home).unwrap();
18201            assert_eq!(saved.status, RunStatus::Superseded);
18202            assert!(saved.candidates[0].folded);
18203            assert!(saved.events.iter().any(|event| {
18204                event.message.contains("--override-recovery-retention")
18205                    && event.message.contains(&state.id)
18206                    && event.message.contains(&reason)
18207            }));
18208            assert_eq!(
18209                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18210                sidecar
18211            );
18212        }
18213    }
18214
18215    #[tokio::test]
18216    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18217        ask_test_home();
18218        let tmp = tempfile::tempdir().unwrap();
18219        let repo = tmp.path().join("repo");
18220        std::fs::create_dir(&repo).unwrap();
18221        init_repo(&repo);
18222        let mut runner = runner_at(RunStatus::Implementing);
18223        runner.state.repo = repo.clone();
18224        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18225        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18226        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18227            let branch = format!("candidate-{label}");
18228            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18229            git::worktree_add_branch(&repo, &wt, &branch, "main")
18230                .await
18231                .unwrap();
18232            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18233            git::git(&wt, &["add", "README.md"]).await.unwrap();
18234            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18235            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18236            runner.state.candidates.push(Candidate {
18237                index,
18238                label,
18239                agent: "alpha".to_owned(),
18240                branch,
18241                worktree: wt,
18242                summary: "completed implementation".to_owned(),
18243                stat: String::new(),
18244                files: 0,
18245                commits: 0,
18246                empty: false,
18247                failed: None,
18248                verified_noop: None,
18249                duration_ms: 42,
18250                folded: false,
18251            });
18252            runner
18253                .state
18254                .candidate_preservation
18255                .insert(label, "awaiting persistence".to_owned());
18256        }
18257        let wt = runner.state.candidates[0].worktree.clone();
18258        let index_lock = git::git(
18259            &wt,
18260            &[
18261                "rev-parse",
18262                "--path-format=absolute",
18263                "--git-path",
18264                "index.lock",
18265            ],
18266        )
18267        .await
18268        .unwrap();
18269        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18270        runner.state.save().unwrap();
18271        assert!(runner.persist_candidates().await.is_err());
18272        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18273        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18274        assert_eq!(
18275            runner.state.candidates[1].commits, 1,
18276            "other results are still collected"
18277        );
18278        assert!(
18279            !runner.state.candidates[0].empty,
18280            "failed rescue is not no change"
18281        );
18282        assert_eq!(
18283            runner.state.candidates[0].summary,
18284            "completed implementation"
18285        );
18286        assert!(runner.after_implement().is_err());
18287        // The record the fold locks is the one on disk, so the arrangement is
18288        // saved first; the refusal asserted is the preservation rule's own,
18289        // never `record gone`.
18290        runner.state.save().unwrap();
18291        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18292            .await
18293            .unwrap_err();
18294        assert!(
18295            matches!(
18296                refusal.downcast_ref::<FoldRefusal>(),
18297                Some(FoldRefusal::ProofIncomplete(detail))
18298                    if detail.contains("candidate preservation incomplete")
18299            ),
18300            "{refusal:#}"
18301        );
18302        assert!(wt.join("new-file").exists());
18303        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18304        assert!(recovery.join("staged.patch").exists());
18305        assert!(recovery.join("unstaged.patch").exists());
18306        assert_eq!(
18307            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18308            "untracked edits\n"
18309        );
18310        runner.state.begin_pass();
18311        runner.state.end_pass_parked(ParkCause::Upgrade {
18312            from: "1.0".into(),
18313            to: Some("1.1".into()),
18314        });
18315        runner.state.save().unwrap();
18316        runner.state = RunState::load(&runner.state.id).unwrap();
18317        assert!(matches!(
18318            runner.state.passes.last().unwrap().end,
18319            Some(crate::run::PassEnd::Parked {
18320                cause: ParkCause::Upgrade { .. }
18321            })
18322        ));
18323        std::fs::remove_file(index_lock).unwrap();
18324        // No implementer is configured: a persistence retry cannot dispatch a seat.
18325        runner.implement().await.unwrap();
18326        assert!(runner.state.candidate_preservation.is_empty());
18327        assert!(
18328            runner
18329                .state
18330                .candidates
18331                .iter()
18332                .all(|c| c.commits == 1 && !c.empty)
18333        );
18334        assert!(git::is_clean(&wt).await.unwrap());
18335        assert!(
18336            crate::run::read_artifact(&runner.state, "cand-A.patch")
18337                .unwrap()
18338                .contains("later tracked edits")
18339        );
18340    }
18341
18342    #[tokio::test]
18343    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18344        ask_test_home();
18345        let tmp = tempfile::tempdir().unwrap();
18346        let repo = tmp.path().join("repo");
18347        std::fs::create_dir(&repo).unwrap();
18348        init_repo(&repo);
18349        let wt = tmp.path().join("candidate");
18350        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18351            .await
18352            .unwrap();
18353        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18354        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18355        assert!(wt.join("uncommitted").exists());
18356        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18357        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18358        let mut runner = runner_at(RunStatus::Implementing);
18359        runner.state.repo = repo.clone();
18360        runner.state.base_commit = "missing-base".to_owned();
18361        runner.state.candidates.push(Candidate {
18362            index: 0,
18363            label: 'A',
18364            agent: "alpha".into(),
18365            branch: "candidate".into(),
18366            worktree: wt.clone(),
18367            summary: "completed".into(),
18368            stat: String::new(),
18369            files: 0,
18370            commits: 0,
18371            empty: false,
18372            failed: None,
18373            verified_noop: None,
18374            duration_ms: 1,
18375            folded: false,
18376        });
18377        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18378        // Saved in the home the fold uses: without a record the fold would
18379        // refuse as `record gone` and say nothing about the dirty tree.
18380        let home = tmp.path().join("home");
18381        runner.state.save_under(&home).unwrap();
18382        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18383        assert!(
18384            refusal
18385                .to_string()
18386                .contains("worktree has uncommitted work; refusing removal"),
18387            "{refusal:#}"
18388        );
18389        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18390        assert!(!runner.state.candidates[0].folded);
18391        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18392        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18393        runner
18394            .state
18395            .candidate_preservation
18396            .insert('A', "pending".into());
18397        assert!(runner.persist_candidates().await.is_err());
18398        assert!(!runner.state.candidates[0].empty);
18399        assert!(!runner.state.candidates[0].folded);
18400        assert!(wt.exists());
18401        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18402        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18403        std::fs::create_dir_all(&patch_path).unwrap();
18404        assert!(
18405            runner.persist_candidates().await.is_err(),
18406            "artifact failure stays pending"
18407        );
18408        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18409        assert!(!runner.state.candidates[0].empty);
18410        std::fs::remove_dir(patch_path).unwrap();
18411        runner.persist_candidates().await.unwrap();
18412        assert!(
18413            runner.state.candidates[0].empty,
18414            "only successful inspection confirms no change"
18415        );
18416    }
18417
18418    fn init_repo(dir: &Path) {
18419        let run = |args: &[&str]| {
18420            let out = std::process::Command::new("git")
18421                .args(args)
18422                .current_dir(dir)
18423                .quiet()
18424                .output()
18425                .expect("spawn git");
18426            assert!(
18427                out.status.success(),
18428                "git {args:?} failed: {}",
18429                String::from_utf8_lossy(&out.stderr)
18430            );
18431        };
18432        run(&["init", "-b", "main"]);
18433        run(&["config", "user.name", "magi test"]);
18434        run(&["config", "user.email", "magi@example.com"]);
18435        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18436        run(&["add", "-A"]);
18437        run(&["commit", "-m", "init"]);
18438    }
18439
18440    // `settle_questions` is what closes the ghost the phone showed: a run's
18441    // seat asked something, the run then ended, and nothing was left to
18442    // abandon the question it left `open`. `HOME` is a process-wide
18443    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18444    // first time it runs in the binary — every test below still reaches the
18445    // same directory whichever call won, and each gets its own run id from
18446    // `RunState::new`, so they never collide there.
18447    fn ask_test_home() {
18448        crate::run::pin_test_home();
18449    }
18450
18451    #[test]
18452    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18453        ask_test_home();
18454        let mut runner = runner_at(RunStatus::Prep);
18455        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18456        // A blocked temporary output path makes the terminal save fail while
18457        // preserving the already published reservation.
18458        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18459        let error = guard
18460            .finish(
18461                &mut runner.state,
18462                Err(
18463                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18464                        .into(),
18465                ),
18466            )
18467            .unwrap_err();
18468        assert_eq!(
18469            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18470            std::io::ErrorKind::PermissionDenied
18471        );
18472        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18473        let message = format!("{error:#}");
18474        assert!(message.contains("original refusal"));
18475        assert!(!message.contains("could not save terminal"));
18476        assert_eq!(
18477            error.chain().count(),
18478            2,
18479            "only startup attribution wraps the original error"
18480        );
18481        let saved = RunState::load(&runner.state.id).unwrap();
18482        assert_eq!(saved.status, RunStatus::Blocked);
18483        assert!(!saved.startup.unwrap().complete);
18484    }
18485
18486    #[test]
18487    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18488        ask_test_home();
18489        let mut runner = runner_at(RunStatus::Prep);
18490        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18491        let id = runner.state.id.clone();
18492        drop(guard);
18493        let saved = RunState::load(&id).unwrap();
18494        assert_eq!(saved.status, RunStatus::Blocked);
18495        assert!(!saved.startup.as_ref().unwrap().complete);
18496        assert!(
18497            saved
18498                .startup
18499                .unwrap()
18500                .failure
18501                .unwrap()
18502                .contains("interrupted")
18503        );
18504        assert!(Runner::resume(&id).is_err());
18505    }
18506
18507    #[test]
18508    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18509        ask_test_home();
18510        let mut runner = runner_at(RunStatus::Prep);
18511        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18512        let error = guard
18513            .finish(
18514                &mut runner.state,
18515                Err(
18516                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18517                        .into(),
18518                ),
18519            )
18520            .unwrap_err();
18521        assert_eq!(
18522            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18523            std::io::ErrorKind::PermissionDenied
18524        );
18525        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18526        let mut task = crate::queue::Task::new(
18527            "review".into(),
18528            "criteria".into(),
18529            runner.state.repo.clone(),
18530            crate::queue::Source::Human,
18531        );
18532        task.record_startup_failure(failure.clone());
18533        task.record_startup_failure(failure.clone());
18534        assert_eq!(task.startup_failures.len(), 1);
18535        assert!(task.runs.is_empty());
18536        assert_eq!(task.attempts, 0);
18537    }
18538
18539    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18540        ask_test_home();
18541        let tmp = tempfile::tempdir().unwrap();
18542        let repo = tmp.path().join("repo");
18543        std::fs::create_dir(&repo).unwrap();
18544        init_repo(&repo);
18545        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18546        let origin = tmp.path().join("origin.git");
18547        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18548            .await
18549            .unwrap();
18550        git::git(
18551            &repo,
18552            &["remote", "add", "origin", origin.to_str().unwrap()],
18553        )
18554        .await
18555        .unwrap();
18556        git::git(&repo, &["checkout", "-b", "fix/retained"])
18557            .await
18558            .unwrap();
18559        std::fs::write(repo.join("retained"), "retained change").unwrap();
18560        git::git(&repo, &["add", "."]).await.unwrap();
18561        git::git(&repo, &["commit", "-m", "retained implementation"])
18562            .await
18563            .unwrap();
18564        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18565        git::git(&repo, &["checkout", "main"]).await.unwrap();
18566        std::fs::write(repo.join("base-change"), "new base").unwrap();
18567        git::git(&repo, &["add", "."]).await.unwrap();
18568        git::git(&repo, &["commit", "-m", "base moved"])
18569            .await
18570            .unwrap();
18571        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18572        git::git(&repo, &["checkout", "fix/retained"])
18573            .await
18574            .unwrap();
18575        let mut runner = runner_at(RunStatus::Voting);
18576        runner.state.repo = repo.clone();
18577        runner.state.base_commit = base;
18578        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18579        runner.state.config.disk.min_free_bytes = 0;
18580        runner.state.config.graph.review_rounds = 1;
18581        runner.state.config.verify.e2e = vec!["true".into()];
18582        runner.state.config.verify.gate = vec!["true".into()];
18583        runner.state.candidates = vec![Candidate {
18584            index: 0,
18585            label: 'A',
18586            agent: "fixture".into(),
18587            branch: "fix/retained".into(),
18588            worktree: repo.clone(),
18589            summary: String::new(),
18590            stat: String::new(),
18591            files: 1,
18592            commits: 1,
18593            empty: false,
18594            failed: None,
18595            verified_noop: None,
18596            duration_ms: 0,
18597            folded: false,
18598        }];
18599        runner.state.tally = Some(Tally {
18600            first_choice: BTreeMap::new(),
18601            borda: BTreeMap::new(),
18602            winner: 'A',
18603            rankings: 0,
18604            unanimous_initial: true,
18605            deliberated: false,
18606            changed_votes: 0,
18607            unanimous_final: true,
18608            tie_break: None,
18609            judges: 0,
18610            present: 0,
18611            quorum: 0,
18612            met_quorum: true,
18613            uncontested: Some("review-only".into()),
18614        });
18615        let mut task = crate::queue::Task::new(
18616            "fixture".into(),
18617            "fixture".into(),
18618            repo,
18619            crate::queue::Source::Human,
18620        );
18621        task.link_run(&runner.state.id);
18622        crate::queue::Queue::open().put(&mut task).unwrap();
18623        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18624        runner.state.base_sync = Some(BaseSync {
18625            tip: String::new(),
18626            behind: 1,
18627            attempts: BASE_SYNC_ROUNDS,
18628            conflict: None,
18629            already_in: None,
18630        });
18631        runner.sync_to_base().await.unwrap();
18632        assert_eq!(runner.state.status, RunStatus::Blocked);
18633        (tmp, runner, head, task.id)
18634    }
18635
18636    #[tokio::test]
18637    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18638        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18639        runner.state.status = RunStatus::Voting;
18640        runner.state.base_sync = None;
18641        runner.state.base_sync_recovery = Default::default();
18642        let scratch = runner.state.dir().join("base-sync");
18643        std::fs::create_dir_all(&scratch).unwrap();
18644        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18645        runner.sync_to_base().await.unwrap();
18646        assert!(runner.state.resource_block.is_some());
18647        assert!(!runner.state.base_sync_blocked());
18648        assert!(runner.state.base_sync.is_none());
18649        assert_eq!(
18650            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18651            "keep"
18652        );
18653        assert_eq!(runner.state.base_episode_used(), 0);
18654        assert!(runner.state.base_sync_recovery.operations.is_empty());
18655        assert!(runner.state.rebase_fixes.is_empty());
18656        assert_eq!(
18657            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18658            head
18659        );
18660        std::fs::remove_dir_all(&scratch).unwrap();
18661        runner.state.resource_block = None;
18662        runner.sync_to_base().await.unwrap();
18663        assert!(!runner.state.base_sync_blocked());
18664        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18665        assert_eq!(runner.state.base_episode_used(), 1);
18666        assert!(runner.state.base_sync_recovery.operations[0].finished);
18667        assert!(runner.state.rebase_fixes.is_empty());
18668        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18669        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18670    }
18671
18672    #[tokio::test]
18673    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18674        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18675        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18676        runner.state.base_sync_recovery = Default::default();
18677        runner.state.task_instruction = Some("fixture".into());
18678        runner.state.config.agents = vec![spec("fixture")];
18679        runner.state.config.graph.review_rounds = 0;
18680        runner.state.config.merge.mode = MergeMode::None;
18681        runner.state.driver_exited = true;
18682        let sync = runner.state.base_sync.as_mut().unwrap();
18683        sync.conflict = None;
18684        sync.attempts = 0;
18685        runner.state.reserve_base_operation(&head, &tip);
18686        runner.state.finish_base_operation(None);
18687        let detail = format!(
18688            "fix/retained conflicts with origin/main and did not rebase: \
18689             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18690             remaining conflicted path(s): none recorded; git said: \
18691             warning: execution failed: {}",
18692            git::REBASE_EXEC
18693        );
18694        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18695        runner.state.record_base_sync_stop(&head);
18696        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18697            unstarted: false,
18698            agent: "fixture".into(),
18699            paths: Vec::new(),
18700            from: Some(head.clone()),
18701            finished: true,
18702            error: None,
18703            stop: None,
18704            onto: None,
18705            index_outside: None,
18706            launcher: None,
18707            infra: None,
18708            outage: None,
18709        });
18710        runner.state.save().unwrap();
18711        assert_eq!(
18712            crate::resume::validate(&crate::run::home(), &runner.state.id)
18713                .unwrap()
18714                .id,
18715            runner.state.id
18716        );
18717
18718        let dirty = runner.state.repo.join("owner-work");
18719        std::fs::write(&dirty, "keep").unwrap();
18720        runner.sync_to_base().await.unwrap();
18721        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18722        assert!(runner.state.base_sync_recovery.operations[0].finished);
18723        assert!(runner.state.base_sync_blocked());
18724        std::fs::remove_file(dirty).unwrap();
18725
18726        let queue = crate::queue::Queue::open();
18727        let id = runner.state.id.clone();
18728        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18729        let _claim = queue.claim(&owner).unwrap();
18730        let mut task = queue.get(&owner).unwrap();
18731        let config = tmp.path().join("test-config.toml");
18732        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18733        let opts = crate::daemon::Opts {
18734            repo: task.repo.clone(),
18735            config: Some(config),
18736            ..Default::default()
18737        };
18738        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18739        let task = queue.get(&owner).unwrap();
18740        assert_eq!(
18741            task.runs.as_slice(),
18742            std::slice::from_ref(&id),
18743            "{:?}",
18744            task.hold_reason
18745        );
18746        runner.state = RunState::load(&id).unwrap();
18747        assert!(!runner.state.base_sync_blocked());
18748        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18749        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18750        assert!(runner.state.base_sync_recovery.operations[0].finished);
18751        assert_eq!(
18752            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18753            detail
18754        );
18755        assert_eq!(runner.state.rebase_fixes.len(), 1);
18756        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18757    }
18758
18759    #[cfg(unix)]
18760    #[tokio::test]
18761    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18762        for routed in [false, true] {
18763            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18764            let home = crate::run::home();
18765            let queue = crate::queue::Queue::open();
18766            let task = queue.get(&owner).unwrap();
18767            runner.state.task_instruction = Some(task.instruction.clone());
18768            runner.state.driver_exited = true;
18769            runner.state.save().unwrap();
18770            let questions = crate::ask::Questions::at(home.join("questions"));
18771            let mut q = crate::ask::Question::new(
18772                runner.state.id.clone(),
18773                "base-recovery".into(),
18774                "owner".into(),
18775                "Recover bounded base movement?".into(),
18776                String::new(),
18777                vec!["recover".into()],
18778            );
18779            q.actions.insert(
18780                "recover".into(),
18781                crate::ask::ChoiceAction::RecoverBase {
18782                    run: runner.state.id.clone(),
18783                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18784                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18785                },
18786            );
18787            q.routed_task = Some(owner.clone());
18788            q.answer(crate::ask::Answer::Choice("recover".into()))
18789                .unwrap();
18790            questions.put(&mut q).unwrap();
18791            crate::base_recovery_control::recover(
18792                &queue,
18793                &home,
18794                crate::base_recovery_control::Request {
18795                    run: runner.state.id.clone(),
18796                    head: head.clone(),
18797                    actor: "decisions".into(),
18798                    request: q.id.clone(),
18799                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18800                    expected_stop: Some((
18801                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18802                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18803                    )),
18804                    evidence_digest: None,
18805                },
18806            )
18807            .await
18808            .unwrap();
18809            if routed {
18810                questions
18811                    .update(&q.id, |q| {
18812                        q.routed_task = Some("another-owner".into());
18813                        Ok(())
18814                    })
18815                    .unwrap();
18816            } else {
18817                let mut task = queue.get(&owner).unwrap();
18818                task.hold_manual(Some("new owner decision".into()));
18819                // Keep the generation to exercise the separate owner-decision binding.
18820                task.status = crate::queue::TaskStatus::Queued;
18821                queue.put(&mut task).unwrap();
18822            }
18823            runner.state = RunState::load(&runner.state.id).unwrap();
18824            runner.sync_to_base().await.unwrap();
18825            let approval = runner
18826                .state
18827                .base_sync_recovery
18828                .authorizations
18829                .last()
18830                .unwrap();
18831            assert!(approval.consumed);
18832            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18833                "routing"
18834            } else {
18835                "owner decision"
18836            }));
18837            assert_eq!(
18838                runner.state.base_sync.as_ref().unwrap().attempts,
18839                BASE_SYNC_ROUNDS
18840            );
18841            assert_eq!(
18842                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18843                head
18844            );
18845        }
18846    }
18847
18848    #[cfg(unix)]
18849    #[tokio::test]
18850    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
18851        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
18852        if std::env::var_os(CHILD).is_none() {
18853            let home = tempfile::tempdir().unwrap();
18854            let output = std::process::Command::new(std::env::current_exe().unwrap())
18855                .args([
18856                    "--exact",
18857                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
18858                    "--nocapture",
18859                ])
18860                .env(CHILD, "1")
18861                .env("MAGI_HOME", home.path())
18862                .env("MAGI_WORKER_HOME", home.path())
18863                .env("MAGI_WORKER_ID", "abcdef")
18864                .output()
18865                .unwrap();
18866            assert!(
18867                output.status.success()
18868                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18869                "{}\n{}",
18870                String::from_utf8_lossy(&output.stdout),
18871                String::from_utf8_lossy(&output.stderr)
18872            );
18873            return;
18874        }
18875        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
18876        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18877        let home = crate::run::home();
18878        let queue = crate::queue::Queue::open();
18879        let mut owner = queue.get(&task).unwrap();
18880        owner.release_operator("test-release", None);
18881        owner.start(runner.state.id.clone());
18882        queue.put(&mut owner).unwrap();
18883        runner.state.driver_exited = true;
18884        runner.state.task_instruction = Some(owner.instruction.clone());
18885        runner.state.save().unwrap();
18886        let _claim = queue.claim(&task).unwrap();
18887        let reserve = |id: &str| {
18888            let directory = home.join("workers/jobs").join(id);
18889            std::fs::create_dir_all(&directory).unwrap();
18890            let job = crate::worker::Job {
18891                id: id.into(),
18892                sequence: 1,
18893                kind: "task".into(),
18894                key: format!("task:{task}"),
18895                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
18896                generation: "fixture-generation".into(),
18897                version: None,
18898                status: crate::worker::Status::Running,
18899                result: None,
18900                pid: Some(std::process::id()),
18901                created_at: 0,
18902                finished_at: None,
18903            };
18904            std::fs::write(
18905                directory.join("job.json"),
18906                serde_json::to_vec(&job).unwrap(),
18907            )
18908            .unwrap();
18909            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
18910        };
18911        let _own = reserve("abcdef");
18912        let other = reserve("fedcba");
18913        assert!(
18914            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18915                .await
18916                .is_err()
18917        );
18918        assert!(
18919            RunState::load(&runner.state.id)
18920                .unwrap()
18921                .base_sync_recovery
18922                .authorizations
18923                .is_empty()
18924        );
18925        drop(other);
18926        assert!(crate::daemon::is_working_on(
18927            &home,
18928            &runner.state.id,
18929            Timestamp::now()
18930        ));
18931        assert!(
18932            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
18933        );
18934        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18935            .await
18936            .unwrap();
18937        assert!(
18938            RunState::load(&runner.state.id)
18939                .unwrap()
18940                .base_recovery_pending()
18941        );
18942    }
18943
18944    #[cfg(unix)]
18945    #[tokio::test]
18946    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
18947        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18948        let home = crate::run::home();
18949        runner.state.driver_pid = Some(std::process::id());
18950        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
18951        runner.state.driver_exited = false;
18952        runner.state.begin_pass();
18953        runner.state.save().unwrap();
18954        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
18955        driver.record(&runner.state).unwrap();
18956        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
18957        // Preserve the durable claim as if the process died before Drop saved.
18958        drop(driver);
18959        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
18960        assert_eq!(
18961            runner.state.liveness_under(&home, false),
18962            crate::run::Liveness::Dead
18963        );
18964        let queue = crate::queue::Queue::open();
18965        let _claim = queue.claim(&task).unwrap();
18966        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18967            .await
18968            .unwrap();
18969        let disk = RunState::load(&runner.state.id).unwrap();
18970        assert!(!disk.driver_exited);
18971        assert!(disk.base_recovery_pending());
18972    }
18973
18974    #[cfg(unix)]
18975    #[tokio::test]
18976    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18977        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18978        if std::env::var_os(CHILD).is_none() {
18979            use std::os::unix::fs::PermissionsExt;
18980            let tmp = tempfile::tempdir().unwrap();
18981            let gh = tmp.path().join("gh");
18982            std::fs::write(&gh, r#"#!/bin/sh
18983case "$1 $2" in
18984  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18985  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18986  *) exit 2 ;;
18987esac
18988"#).unwrap();
18989            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18990            let mut paths = vec![tmp.path().to_path_buf()];
18991            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18992            let output = std::process::Command::new(std::env::current_exe().unwrap())
18993                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18994                .env(CHILD, "1")
18995                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18996                .env("PATH", std::env::join_paths(paths).unwrap())
18997                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18998                .output().unwrap();
18999            assert!(
19000                output.status.success()
19001                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19002                "{}\n{}",
19003                String::from_utf8_lossy(&output.stdout),
19004                String::from_utf8_lossy(&output.stderr)
19005            );
19006            return;
19007        }
19008        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19009        let repo = runner.state.repo.clone();
19010        git::git(&repo, &["checkout", "main"]).await.unwrap();
19011        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19012        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19013        git::git(&repo, &["checkout", "fix/retained"])
19014            .await
19015            .unwrap();
19016        runner.state.pr = Some(crate::run::PrRecord {
19017            url: "https://example.test/project/pull/1".into(),
19018            number: 1,
19019            state: "open".into(),
19020            checks: "unknown".into(),
19021            round: 0,
19022            rounds: 1,
19023            red_at_merge: Vec::new(),
19024        });
19025        runner.sync_to_base().await.unwrap();
19026        assert_eq!(runner.state.status, RunStatus::Blocked);
19027        assert_eq!(
19028            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19029            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19030        );
19031        assert!(runner.state.base_sync_closure_pending());
19032        assert!(crate::handover::can_resume(&runner.state));
19033        let queue = crate::queue::Queue::open();
19034        assert!(!crate::base_sync_recovery::held_task(
19035            &queue,
19036            &queue.get(&task).unwrap()
19037        ));
19038        assert!(runner.state.authorize_base_sync(&task).is_err());
19039        // Legacy closure stops have no typed stop but must retain the checkpoint.
19040        runner.state.base_sync_recovery.stop = None;
19041        runner.state.status = RunStatus::Voting;
19042        runner.state.gate_ran = true;
19043        runner.state.config.graph.review_rounds = 0;
19044        runner.state.save().unwrap();
19045        assert!(crate::handover::can_resume(&runner.state));
19046        runner.state = RunState::load(&runner.state.id).unwrap();
19047        runner.execute_graph().await.unwrap();
19048        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19049        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19050        assert_eq!(
19051            runner.state.base_sync.as_ref().unwrap().attempts,
19052            BASE_SYNC_ROUNDS
19053        );
19054        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19055        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19056        assert!(runner.state.reviews.is_empty());
19057        assert!(runner.state.gate.is_empty());
19058    }
19059
19060    #[cfg(unix)]
19061    #[tokio::test]
19062    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19063        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19064        runner.state.driver_exited = true;
19065        runner.state.save().unwrap();
19066        let home = crate::run::home();
19067        let queue = crate::queue::Queue::open();
19068        let _claim = queue.claim(&task).unwrap();
19069        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19070        assert!(
19071            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19072                .await
19073                .is_err()
19074        );
19075        drop(lease);
19076        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19077        assert!(
19078            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19079                .await
19080                .is_err()
19081        );
19082        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19083        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19084            .await
19085            .unwrap();
19086        let disk = RunState::load(&runner.state.id).unwrap();
19087        assert!(disk.base_recovery_pending());
19088        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19089        assert!(
19090            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19091                .await
19092                .is_err()
19093        );
19094        assert_eq!(
19095            RunState::load(&runner.state.id)
19096                .unwrap()
19097                .base_sync_recovery
19098                .authorizations
19099                .len(),
19100            1
19101        );
19102        let mut owner = queue.get(&task).unwrap();
19103        owner.runs.push("20260101-000000-ffff".into());
19104        queue.put(&mut owner).unwrap();
19105        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19106            .await
19107            .unwrap_err();
19108        assert!(error.to_string().contains("run task ownership changed"));
19109    }
19110
19111    #[cfg(unix)]
19112    #[tokio::test]
19113    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19114        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19115        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19116        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19117        legacy["status"] = serde_json::json!("voting");
19118        runner.state = serde_json::from_value(legacy).unwrap();
19119        runner.state.save().unwrap();
19120        for _ in 0..3 {
19121            runner.execute_graph().await.unwrap();
19122            assert_eq!(runner.state.status, RunStatus::Blocked);
19123            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19124            assert!(!crate::handover::can_resume(&runner.state));
19125            assert_eq!(
19126                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19127                head
19128            );
19129            assert!(runner.state.reviews.is_empty());
19130            assert!(!runner.state.gate_ran);
19131        }
19132        let notice = crate::notices::run_ended(&runner.state).unwrap();
19133        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19134        runner.state.begin_pass();
19135        runner.state.status = RunStatus::Voting;
19136        runner.deliberate().await.unwrap();
19137        runner.vote().await.unwrap();
19138        runner.finish_after_tally().await.unwrap();
19139        assert_eq!(runner.state.status, RunStatus::Blocked);
19140        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19141        assert_eq!(
19142            crate::notices::run_ended(&runner.state).unwrap().since,
19143            notice.since
19144        );
19145    }
19146
19147    #[cfg(unix)]
19148    #[tokio::test]
19149    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19150        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19151        for detail in [
19152            "fix/retained conflicts with origin/main and did not rebase: conflict",
19153            "rebased fix/retained locally but origin refused the push",
19154            "unknown failure",
19155        ] {
19156            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19157            runner.state.record_base_sync_stop(&head);
19158            assert!(runner.state.authorize_base_sync(&task).is_err());
19159            runner.state.status = RunStatus::Voting;
19160            runner.execute_graph().await.unwrap();
19161            assert_eq!(runner.state.status, RunStatus::Blocked);
19162            assert!(!crate::handover::can_resume(&runner.state));
19163            assert_eq!(
19164                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19165                head
19166            );
19167        }
19168    }
19169
19170    #[tokio::test]
19171    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19172        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19173        let state = &mut runner.state;
19174        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19175        let branch = state.winner().unwrap().branch.clone();
19176        state.base_sync_recovery = Default::default();
19177        state.base_sync.as_mut().unwrap().attempts = 0;
19178        state.reserve_base_operation(&head, &tip);
19179        state.finish_base_operation(None);
19180        let detail = format!(
19181            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19182        );
19183        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19184        state.event("land", detail);
19185        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19186        assert!(state.unknown_preparation_stop(&head));
19187        let digest = state.preparation_digest(&head).unwrap();
19188        state
19189            .base_sync_recovery
19190            .operations
19191            .last_mut()
19192            .unwrap()
19193            .validated_head = Some(head.clone());
19194        assert!(!state.unknown_preparation_stop(&head));
19195        state
19196            .base_sync_recovery
19197            .operations
19198            .last_mut()
19199            .unwrap()
19200            .validated_head = None;
19201        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19202        state.driver_exited = true;
19203        state.save().unwrap();
19204        let home = crate::run::home();
19205        let queue = crate::queue::Queue::open();
19206        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19207            .await
19208            .unwrap();
19209        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19210        assert_eq!(inspection["evidence_digest"], digest);
19211        let request = crate::base_recovery_control::Request {
19212            run: state.id.clone(),
19213            head: head.clone(),
19214            actor: "test".into(),
19215            request: "preparation".into(),
19216            decision: None,
19217            expected_stop: None,
19218            evidence_digest: Some(digest),
19219        };
19220        let mut stale = request.clone();
19221        stale.evidence_digest = Some("stale".into());
19222        assert!(
19223            crate::base_recovery_control::recover(&queue, &home, stale)
19224                .await
19225                .is_err()
19226        );
19227        let scratch = state.dir().join("base-sync");
19228        std::fs::create_dir(&scratch).unwrap();
19229        assert!(
19230            crate::base_recovery_control::recover(&queue, &home, request.clone())
19231                .await
19232                .is_err()
19233        );
19234        std::fs::remove_dir(&scratch).unwrap();
19235        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19236        git::git(
19237            &state.repo,
19238            &[
19239                "commit",
19240                "--allow-empty",
19241                "-m",
19242                "base advanced after inspection",
19243            ],
19244        )
19245        .await
19246        .unwrap();
19247        git::git(&state.repo, &["push", "origin", "main"])
19248            .await
19249            .unwrap();
19250        git::git(&state.repo, &["checkout", "fix/retained"])
19251            .await
19252            .unwrap();
19253        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19254            .await
19255            .unwrap();
19256        assert!(!outcome.repeated);
19257        assert!(
19258            crate::base_recovery_control::recover(&queue, &home, request)
19259                .await
19260                .unwrap()
19261                .repeated
19262        );
19263        runner.state = RunState::load(&runner.state.id).unwrap();
19264        assert!(runner.state.base_recovery_pending());
19265        runner.sync_to_base().await.unwrap();
19266        assert!(!runner.state.base_sync_blocked());
19267        assert!(!runner.state.consume_base_recovery(&head));
19268        assert_eq!(runner.state.base_episode_used(), 2);
19269        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19270        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19271        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19272    }
19273
19274    #[cfg(unix)]
19275    #[tokio::test]
19276    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19277        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19278        runner.state.authorize_base_sync(&task).unwrap();
19279        assert!(runner.state.consume_base_recovery(&head));
19280        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19281        runner.state.reserve_base_operation(&head, &tip);
19282        runner.state.save().unwrap();
19283        runner.state = RunState::load(&runner.state.id).unwrap();
19284        assert!(!runner.state.consume_base_recovery(&head));
19285        runner.sync_to_base().await.unwrap();
19286        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19287        assert_eq!(runner.state.base_episode_used(), 1);
19288        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19289        assert!(
19290            runner
19291                .state
19292                .base_sync_recovery
19293                .operations
19294                .last()
19295                .unwrap()
19296                .finished
19297        );
19298        assert!(!runner.state.base_sync_blocked());
19299        runner.sync_to_base().await.unwrap();
19300        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19301    }
19302
19303    #[cfg(unix)]
19304    #[tokio::test]
19305    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19306        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19307        // Both historical diagnostic spellings retain an exhaustion identity.
19308        let original = runner
19309            .state
19310            .base_sync
19311            .as_ref()
19312            .unwrap()
19313            .conflict
19314            .clone()
19315            .unwrap();
19316        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19317            original
19318                .replace("synchronization(s)", "rebase(s)")
19319                .replace("synchronizing", "rebasing"),
19320        );
19321        runner.state.base_sync_recovery = Default::default();
19322        runner.state.record_base_sync_stop(&head);
19323        assert_eq!(
19324            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19325            crate::base_sync_recovery::StopKind::Exhausted
19326        );
19327        runner.state.authorize_base_sync(&task).unwrap();
19328        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19329        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19330            .as_object_mut()
19331            .unwrap();
19332        auth.remove("interval");
19333        auth.remove("scope");
19334        runner.state = serde_json::from_value(legacy).unwrap();
19335        assert!(runner.state.consume_base_recovery(&head));
19336        assert_eq!(runner.state.base_episode_used(), 3);
19337        runner.sync_to_base().await.unwrap();
19338        assert_eq!(runner.state.base_episode_used(), 4);
19339        runner.state.resource_block = Some(crate::run::ResourceBlock {
19340            node: "gate".into(),
19341            kind: "cache".into(),
19342            detail: "legacy wait".into(),
19343            at: Timestamp::now(),
19344            cause: crate::run::ResourceBlockCause::Unrecorded,
19345        });
19346        runner.state.save().unwrap();
19347        assert!(
19348            runner
19349                .state
19350                .base_sync_recovery
19351                .episodes
19352                .last()
19353                .unwrap()
19354                .boundary
19355                .is_none()
19356        );
19357        runner.state.resource_block = None;
19358        advance_base_fixture(&runner).await;
19359        runner.sync_to_base().await.unwrap();
19360        assert!(runner.state.base_sync_blocked());
19361        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19362    }
19363
19364    #[cfg(unix)]
19365    async fn advance_base_fixture(runner: &Runner) {
19366        let repo = &runner.state.repo;
19367        for args in [
19368            vec!["checkout", "main"],
19369            vec!["commit", "--allow-empty", "-m", "base advanced"],
19370            vec!["push", "origin", "main"],
19371            vec!["checkout", "fix/retained"],
19372        ] {
19373            git::git(repo, &args).await.unwrap();
19374        }
19375    }
19376
19377    #[cfg(unix)]
19378    fn fresh_base_interval_fixture(runner: &mut Runner) {
19379        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19380        runner.state.base_sync.as_mut().unwrap().conflict = None;
19381        runner.state.base_sync_recovery = Default::default();
19382        runner.state.status = RunStatus::Voting;
19383    }
19384
19385    #[cfg(unix)]
19386    #[tokio::test]
19387    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19388        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19389        fresh_base_interval_fixture(&mut runner);
19390        runner.state.begin_pass();
19391        runner.sync_to_base().await.unwrap();
19392        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19393        runner.state.resource_block = Some(crate::run::ResourceBlock {
19394            node: "gate".into(),
19395            kind: "build cache".into(),
19396            detail: "busy".into(),
19397            at: Timestamp::now(),
19398            cause: crate::run::ResourceBlockCause::Timeout {
19399                waited_secs: 1,
19400                limit_secs: 1,
19401            },
19402        });
19403        runner.state.save().unwrap();
19404        let queue = crate::queue::Queue::open();
19405        let mut owner = queue.get(&task).unwrap();
19406        runner.state.task_instruction = Some(owner.instruction.clone());
19407        owner.release_operator("fixture-owner", None);
19408        queue.put(&mut owner).unwrap();
19409        let approval = owner.resumption.clone().unwrap();
19410        runner.state.resource_block = None;
19411        runner.state.save().unwrap();
19412        runner.state = RunState::load(&runner.state.id).unwrap();
19413        advance_base_fixture(&runner).await;
19414        runner.sync_to_base().await.unwrap();
19415        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19416        assert_eq!(runner.state.base_episode_used(), 1);
19417        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19418        assert!(
19419            runner.state.base_sync_recovery.episodes[0]
19420                .boundary
19421                .as_ref()
19422                .unwrap()
19423                .consumed
19424        );
19425        assert!(
19426            !runner
19427                .state
19428                .renew_base_episode(&task, &approval, &head, "base")
19429        );
19430        for _ in 0..3 {
19431            owner.release_operator("fixture-owner", None);
19432            queue.put(&mut owner).unwrap();
19433            runner.state = RunState::load(&runner.state.id).unwrap();
19434            runner.state.begin_pass();
19435            runner.sync_to_base().await.unwrap();
19436            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19437            assert_eq!(runner.state.base_episode_used(), 1);
19438        }
19439        runner.state.resource_block = Some(crate::run::ResourceBlock {
19440            node: "gate".into(),
19441            kind: "disk pressure".into(),
19442            detail: "free space required".into(),
19443            at: Timestamp::now(),
19444            cause: crate::run::ResourceBlockCause::Other,
19445        });
19446        runner.state.end_pass_parked(ParkCause::Interrupt {
19447            reason: "disk pressure".into(),
19448        });
19449        runner.state.save().unwrap();
19450        owner.release_operator("fixture-owner-after-disk", None);
19451        queue.put(&mut owner).unwrap();
19452        runner.state.resource_block = None;
19453        advance_base_fixture(&runner).await;
19454        runner.sync_to_base().await.unwrap();
19455        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19456        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19457        assert_eq!(runner.state.base_episode_used(), 1);
19458        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19459    }
19460
19461    #[cfg(unix)]
19462    #[tokio::test]
19463    async fn base_recovery_continuous_advancement_stops_at_four() {
19464        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19465        fresh_base_interval_fixture(&mut runner);
19466        for spent in 1..=BASE_SYNC_ROUNDS {
19467            runner.sync_to_base().await.unwrap();
19468            assert!(!runner.state.base_sync_blocked());
19469            assert_eq!(runner.state.base_episode_used(), spent);
19470            advance_base_fixture(&runner).await;
19471        }
19472        runner.sync_to_base().await.unwrap();
19473        assert_eq!(
19474            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19475            crate::base_sync_recovery::StopKind::Exhausted
19476        );
19477        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19478        assert!(stop.unverified_sync);
19479        let action = runner.state.base_sync_next_action();
19480        assert!(action.contains("never reached its gate"));
19481        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19482        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19483        runner.state = RunState::load(&runner.state.id).unwrap();
19484        runner.sync_to_base().await.unwrap();
19485        assert_eq!(runner.state.base_episode_used(), 4);
19486        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19487    }
19488
19489    #[cfg(unix)]
19490    #[tokio::test]
19491    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19492        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19493        runner.state.ensure_base_episode();
19494        // Verification progress alone is not evidence of a successful sync.
19495        runner.state.record_base_progress(&head);
19496        runner.state.base_sync_recovery.stop = None;
19497        runner.state.record_base_sync_stop(&head);
19498        assert!(
19499            !runner
19500                .state
19501                .base_sync_recovery
19502                .stop
19503                .as_ref()
19504                .unwrap()
19505                .unverified_sync
19506        );
19507
19508        runner.state.finish_base_operation(Some(&head));
19509        // A gate for another head cannot verify this synchronization.
19510        runner.state.gate_ran = true;
19511        runner.state.gate_head = Some("older-head".into());
19512        runner.state.base_sync_recovery.stop = None;
19513        runner.state.record_base_sync_stop(&head);
19514        runner.state.save().unwrap();
19515        runner.state = RunState::load(&runner.state.id).unwrap();
19516        assert!(
19517            runner
19518                .state
19519                .base_sync_recovery
19520                .stop
19521                .as_ref()
19522                .unwrap()
19523                .unverified_sync
19524        );
19525
19526        runner.state.gate_head = Some(head.clone());
19527        runner.state.base_sync_recovery.stop = None;
19528        runner.state.record_base_sync_stop(&head);
19529        assert!(
19530            !runner
19531                .state
19532                .base_sync_recovery
19533                .stop
19534                .as_ref()
19535                .unwrap()
19536                .unverified_sync
19537        );
19538        assert!(
19539            !runner
19540                .state
19541                .base_sync_next_action()
19542                .contains("never reached its gate")
19543        );
19544
19545        // Historical records cannot establish the missing synchronization evidence.
19546        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19547        legacy["base_sync_recovery"]["stop"]
19548            .as_object_mut()
19549            .unwrap()
19550            .remove("unverified_sync");
19551        legacy["base_sync_recovery"]["episodes"][0]
19552            .as_object_mut()
19553            .unwrap()
19554            .remove("last_sync_head");
19555        runner.state = serde_json::from_value(legacy).unwrap();
19556        assert!(
19557            !runner
19558                .state
19559                .base_sync_recovery
19560                .stop
19561                .as_ref()
19562                .unwrap()
19563                .unverified_sync
19564        );
19565        assert!(
19566            runner.state.base_sync_recovery.episodes[0]
19567                .last_sync_head
19568                .is_none()
19569        );
19570    }
19571
19572    #[cfg(unix)]
19573    #[tokio::test]
19574    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19575        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19576        runner.state.authorize_base_sync(&task).unwrap();
19577        assert!(
19578            runner
19579                .state
19580                .base_sync_next_action()
19581                .contains("Approval recorded")
19582        );
19583        assert!(
19584            runner
19585                .state
19586                .base_sync_next_action()
19587                .contains("4/4 in episode 0, 4 lifetime")
19588        );
19589        assert!(runner.state.consume_base_recovery(&head));
19590        assert!(
19591            runner
19592                .state
19593                .base_sync_next_action()
19594                .contains("0/4 in episode 1, 4 lifetime")
19595        );
19596    }
19597
19598    #[cfg(unix)]
19599    #[tokio::test]
19600    async fn base_recovery_changed_head_invalidates_without_spending() {
19601        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19602        runner.state.authorize_base_sync(&task).unwrap();
19603        git::git(
19604            &runner.state.repo,
19605            &["commit", "--allow-empty", "-m", "external head change"],
19606        )
19607        .await
19608        .unwrap();
19609        runner.sync_to_base().await.unwrap();
19610        let a = runner
19611            .state
19612            .base_sync_recovery
19613            .authorizations
19614            .last()
19615            .unwrap();
19616        assert!(a.consumed);
19617        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19618        runner.state = RunState::load(&runner.state.id).unwrap();
19619        assert!(
19620            runner
19621                .state
19622                .base_sync_next_action()
19623                .contains("Approval invalidated")
19624        );
19625        assert!(!runner.state.base_recovery_pending());
19626        assert!(runner.state.base_sync_blocked());
19627        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19628    }
19629
19630    #[cfg(unix)]
19631    #[tokio::test]
19632    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19633        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19634        runner.state.driver_exited = true;
19635        runner.state.save().unwrap();
19636        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19637            .await
19638            .unwrap();
19639        runner.state = RunState::load(&runner.state.id).unwrap();
19640        advance_base_fixture(&runner).await;
19641        runner.sync_to_base().await.unwrap();
19642        let a = runner
19643            .state
19644            .base_sync_recovery
19645            .authorizations
19646            .last()
19647            .unwrap();
19648        assert!(
19649            a.consumed
19650                && a.invalidated
19651                    .as_deref()
19652                    .unwrap()
19653                    .contains("fetched base changed")
19654        );
19655        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19656        assert_eq!(
19657            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19658            head
19659        );
19660        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19661            .await
19662            .unwrap();
19663        runner.state = RunState::load(&runner.state.id).unwrap();
19664        runner.sync_to_base().await.unwrap();
19665        assert!(!runner.state.base_sync_blocked());
19666        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19667    }
19668
19669    #[cfg(unix)]
19670    #[tokio::test]
19671    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19672        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19673        runner.state.authorize_base_sync(&task).unwrap();
19674        assert!(runner.state.consume_base_recovery(&head));
19675        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19676        runner.state.reserve_base_operation(&head, &tip);
19677        runner.state.save().unwrap();
19678        let scratch = runner.state.dir().join("base-sync");
19679        assert_eq!(
19680            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19681                .await
19682                .unwrap(),
19683            crate::rebase::Rebased::Applied
19684        );
19685        runner.state = RunState::load(&runner.state.id).unwrap();
19686        runner.sync_to_base().await.unwrap();
19687        assert!(
19688            runner
19689                .state
19690                .base_sync_recovery
19691                .operations
19692                .last()
19693                .unwrap()
19694                .finished
19695        );
19696        assert_eq!(runner.state.base_episode_used(), 1);
19697        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19698        assert!(!runner.state.base_sync_blocked());
19699    }
19700
19701    #[cfg(unix)]
19702    #[tokio::test]
19703    async fn base_recovery_crash_preserves_untracked_files() {
19704        for ignored in [false, true] {
19705            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19706            runner.state.authorize_base_sync(&task).unwrap();
19707            assert!(runner.state.consume_base_recovery(&head));
19708            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19709            runner.state.reserve_base_operation(&head, &tip);
19710            runner.state.save().unwrap();
19711            let scratch = runner.state.dir().join("base-sync");
19712            assert_eq!(
19713                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19714                    .await
19715                    .unwrap(),
19716                crate::rebase::Rebased::Applied
19717            );
19718            let repo = &runner.state.repo;
19719            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19720            assert_ne!(result, head);
19721            if ignored {
19722                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19723                    .await
19724                    .unwrap();
19725                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19726            }
19727            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19728            assert!(
19729                git::git_raw(repo, &["diff", "--quiet", &head])
19730                    .await
19731                    .unwrap()
19732                    .ok()
19733            );
19734            // Resume after the branch moved, before its checkout was reset.
19735            runner.state = RunState::load(&runner.state.id).unwrap();
19736            runner.sync_to_base().await.unwrap();
19737            assert!(runner.state.base_sync_blocked());
19738            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19739            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19740            assert_eq!(
19741                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19742                result
19743            );
19744            assert_eq!(
19745                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19746                "retained work\n"
19747            );
19748            assert!(
19749                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19750                    .await
19751                    .unwrap()
19752                    .ok()
19753            );
19754        }
19755    }
19756
19757    #[cfg(unix)]
19758    #[tokio::test]
19759    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19760        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19761        runner.state.authorize_base_sync(&task).unwrap();
19762        assert!(runner.state.consume_base_recovery(&head));
19763        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19764        runner.state.reserve_base_operation(&head, &tip);
19765        runner.state.save().unwrap();
19766        let scratch = runner.state.dir().join("base-sync");
19767        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19768            .await
19769            .unwrap();
19770        git::sync_to_head(&runner.state.repo).await.unwrap();
19771        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19772        git::git(&runner.state.repo, &["add", "foreign"])
19773            .await
19774            .unwrap();
19775        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19776            .await
19777            .unwrap();
19778        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19779        runner.state = RunState::load(&runner.state.id).unwrap();
19780        runner.sync_to_base().await.unwrap();
19781        assert!(runner.state.base_sync_blocked());
19782        assert!(
19783            !runner
19784                .state
19785                .base_sync_recovery
19786                .operations
19787                .last()
19788                .unwrap()
19789                .finished
19790        );
19791        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19792        assert_eq!(
19793            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19794            foreign_head
19795        );
19796    }
19797
19798    #[cfg(unix)]
19799    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19800    {
19801        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19802        fresh_base_interval_fixture(&mut runner);
19803        let repo = &runner.state.repo;
19804        git::git(repo, &["checkout", "main"]).await.unwrap();
19805        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19806        git::git(repo, &["add", "retained"]).await.unwrap();
19807        git::git(repo, &["commit", "-m", "upstream retained change"])
19808            .await
19809            .unwrap();
19810        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19811        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19812        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19813        let scratch = runner.state.dir().join("base-sync");
19814        assert!(matches!(
19815            git::rebase_start(repo, &scratch, "fix/retained", &tip)
19816                .await
19817                .unwrap(),
19818            git::RebaseStart::Conflicted(_)
19819        ));
19820        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
19821            unstarted: false,
19822            agent: "fixture".into(),
19823            paths: vec!["retained".into()],
19824            from: Some(head.clone()),
19825            onto: None,
19826            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
19827            index_outside: None,
19828            finished: false,
19829            error: None,
19830            launcher: None,
19831            infra: None,
19832            outage: None,
19833        });
19834        (tmp, runner, head, tip, scratch)
19835    }
19836
19837    #[cfg(unix)]
19838    #[tokio::test]
19839    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
19840        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19841        // A resource stop from before reservations existed, with resolved
19842        // contents left for the launcher's ordinary staging continuation.
19843        std::fs::write(
19844            scratch.join("retained"),
19845            "upstream and retained resolution\n",
19846        )
19847        .unwrap();
19848        runner.state.resource_block = Some(crate::run::ResourceBlock {
19849            node: "rebase".into(),
19850            kind: "repository coordination".into(),
19851            detail: "busy".into(),
19852            at: Timestamp::now(),
19853            cause: crate::run::ResourceBlockCause::Other,
19854        });
19855        runner.state.save().unwrap();
19856        // Advance the remote without moving either checkout participating
19857        // in the standing rebase.
19858        let newer = git::git(
19859            &runner.state.repo,
19860            &[
19861                "commit-tree",
19862                "main^{tree}",
19863                "-p",
19864                "main",
19865                "-m",
19866                "base advanced during wait",
19867            ],
19868        )
19869        .await
19870        .unwrap();
19871        git::git(
19872            &runner.state.repo,
19873            &[
19874                "push",
19875                "origin",
19876                &format!("{}:refs/heads/main", newer.trim()),
19877            ],
19878        )
19879        .await
19880        .unwrap();
19881        runner.state = RunState::load(&runner.state.id).unwrap();
19882        runner.state.resource_block = None;
19883        runner.sync_to_base().await.unwrap();
19884        assert!(!runner.state.base_sync_blocked());
19885        let op = &runner.state.base_sync_recovery.operations[0];
19886        assert_eq!(op.head, head);
19887        assert_eq!(op.tip, tip);
19888        assert!(op.finished);
19889        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19890        assert_eq!(runner.state.rebase_fixes.len(), 1);
19891        let latest = git::rev_parse(&runner.state.repo, "origin/main")
19892            .await
19893            .unwrap();
19894        assert_ne!(latest, tip);
19895        runner.state = RunState::load(&runner.state.id).unwrap();
19896        runner.sync_to_base().await.unwrap();
19897        assert!(!runner.state.base_sync_blocked());
19898        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
19899        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
19900        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19901    }
19902
19903    #[cfg(unix)]
19904    #[tokio::test]
19905    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
19906        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19907        runner.state.reserve_base_operation(&head, &tip);
19908        runner.state.save().unwrap();
19909        std::fs::write(
19910            scratch.join("retained"),
19911            "upstream and retained resolution\n",
19912        )
19913        .unwrap();
19914        git::git(&scratch, &["add", "retained"]).await.unwrap();
19915        git::git(
19916            &scratch,
19917            &["-c", "core.editor=true", "rebase", "--continue"],
19918        )
19919        .await
19920        .unwrap();
19921        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19922        assert!(
19923            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19924                .await
19925                .unwrap()
19926                .is_empty()
19927        );
19928        assert_eq!(
19929            crate::rebase::finish(
19930                &mut runner.state,
19931                &scratch,
19932                "fix/retained",
19933                &head,
19934                &tip,
19935                &["retained".into()],
19936                ""
19937            )
19938            .await
19939            .unwrap(),
19940            crate::rebase::Rebased::Applied
19941        );
19942        assert!(!scratch.exists());
19943        // Simulate losing the caller before finish_base_operation/save.
19944        runner.state = RunState::load(&runner.state.id).unwrap();
19945        let op = &runner.state.base_sync_recovery.operations[0];
19946        assert!(!op.finished);
19947        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
19948        runner.sync_to_base().await.unwrap();
19949        assert!(!runner.state.base_sync_blocked());
19950        assert!(runner.state.base_sync_recovery.operations[0].finished);
19951        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19952        assert_eq!(runner.state.rebase_fixes.len(), 1);
19953        let winner = runner.state.winner().unwrap().clone();
19954        let wait = runner.repository_wait();
19955        assert!(
19956            verify_current_head(&mut runner.state, &winner, &wait)
19957                .await
19958                .unwrap()
19959        );
19960        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19961    }
19962
19963    #[cfg(unix)]
19964    #[tokio::test]
19965    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
19966        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
19967            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19968            runner.state.reserve_base_operation(&head, &tip);
19969            runner.state.save().unwrap();
19970            std::fs::write(
19971                scratch.join("retained"),
19972                "upstream and retained resolution\n",
19973            )
19974            .unwrap();
19975            git::git(&scratch, &["add", "retained"]).await.unwrap();
19976            git::git(
19977                &scratch,
19978                &["-c", "core.editor=true", "rebase", "--continue"],
19979            )
19980            .await
19981            .unwrap();
19982            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19983            assert!(!git::rebase_in_progress(&scratch).await);
19984            assert!(
19985                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19986                    .await
19987                    .unwrap()
19988                    .is_empty()
19989            );
19990            match damage {
19991                Some("record") => {
19992                    let path =
19993                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
19994                            .await
19995                            .unwrap();
19996                    std::fs::write(scratch.join(path), "").unwrap();
19997                }
19998                Some("foreign") => {
19999                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20000                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20001                    git::git(&scratch, &["commit", "-m", "foreign work"])
20002                        .await
20003                        .unwrap();
20004                }
20005                Some("dirty") => {
20006                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20007                }
20008                _ => {}
20009            }
20010            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20011            // Crash immediately after Git continuation, before finish runs.
20012            runner.state = RunState::load(&runner.state.id).unwrap();
20013            assert!(
20014                runner.state.base_sync_recovery.operations[0]
20015                    .validated_head
20016                    .is_none()
20017            );
20018            runner.sync_to_base().await.unwrap();
20019            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20020            assert_eq!(runner.state.base_episode_used(), 1);
20021            assert_eq!(runner.state.rebase_fixes.len(), 1);
20022            assert_eq!(
20023                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20024                retained_head
20025            );
20026            if damage.is_some() {
20027                assert!(runner.state.base_sync_blocked());
20028                assert!(scratch.exists());
20029                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20030                assert!(
20031                    runner.state.base_sync_recovery.operations[0]
20032                        .validated_head
20033                        .is_none()
20034                );
20035            } else {
20036                assert!(!runner.state.base_sync_blocked());
20037                assert!(!scratch.exists());
20038                assert!(runner.state.base_sync_recovery.operations[0].finished);
20039                assert_eq!(
20040                    runner.state.base_sync_recovery.operations[0]
20041                        .validated_head
20042                        .as_deref(),
20043                    Some(result.as_str())
20044                );
20045                let winner = runner.state.winner().unwrap().clone();
20046                let wait = runner.repository_wait();
20047                assert!(
20048                    verify_current_head(&mut runner.state, &winner, &wait)
20049                        .await
20050                        .unwrap()
20051                );
20052                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20053                runner.state = RunState::load(&runner.state.id).unwrap();
20054                runner.sync_to_base().await.unwrap();
20055                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20056            }
20057        }
20058    }
20059
20060    #[cfg(unix)]
20061    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20062        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20063        // This is an ordinary gate stop, not an authorized base-budget recovery.
20064        runner.state.prep_complete = Some(true);
20065        runner.state.base_sync = None;
20066        runner.state.base_sync_recovery = Default::default();
20067        runner.state.config.graph.gate_fix_rounds = 1;
20068        let mut review = review_round(true, 0, 1, 1, false, true);
20069        review.head = head.clone();
20070        review.verified_head = Some(head.clone());
20071        runner.state.reviews = vec![review];
20072        runner.state.gate = vec![CommandOutcome {
20073            command: "old gate".into(),
20074            code: Some(1),
20075            output_tail: "old failure".into(),
20076            duration_ms: 0,
20077            resource_blocked: false,
20078            ..Default::default()
20079        }];
20080        runner.state.gate_head = Some(head.clone());
20081        runner.state.gate_ran = true;
20082        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20083            agent: "fixture".into(),
20084            failed: runner.state.gate.clone(),
20085            notes: "spent".into(),
20086            committed: false,
20087            error: None,
20088        }];
20089        runner.state.land_approval = Some(crate::run::LandApproval {
20090            question: "old approval".into(),
20091            head: head.clone(),
20092        });
20093        runner.state.status = RunStatus::Blocked;
20094        (tmp, runner, head)
20095    }
20096
20097    #[cfg(unix)]
20098    #[tokio::test]
20099    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20100        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20101        runner.sync_to_base().await.unwrap();
20102        let winner = runner.state.winner().unwrap().clone();
20103        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20104        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20105        assert_ne!(head, base);
20106        runner.state.config.verify.e2e = vec![format!(
20107            "git update-ref refs/remotes/origin/main {head} && false"
20108        )];
20109        let wait = repository_wait(&runner.state, None);
20110        assert!(
20111            !verify_current_head(&mut runner.state, &winner, &wait)
20112                .await
20113                .unwrap()
20114        );
20115        assert_eq!(
20116            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20117                .await
20118                .unwrap(),
20119            head
20120        );
20121        assert_eq!(
20122            runner
20123                .state
20124                .head_e2e
20125                .as_ref()
20126                .unwrap()
20127                .base_commit
20128                .as_deref(),
20129            Some(base.as_str())
20130        );
20131    }
20132
20133    #[cfg(unix)]
20134    #[tokio::test]
20135    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20136        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20137            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20138            let phases = tmp.path().join("phases");
20139            runner.state.config.verify.e2e = vec![format!(
20140                "echo e2e >> '{}'; {}",
20141                phases.display(),
20142                if e2e_ok {
20143                    "true"
20144                } else {
20145                    "echo new-e2e-failure; false"
20146                }
20147            )];
20148            runner.state.config.verify.gate = vec![format!(
20149                "echo gate >> '{}'; {}",
20150                phases.display(),
20151                if gate_ok {
20152                    "true"
20153                } else {
20154                    "echo new-gate-failure; false"
20155                }
20156            )];
20157            runner.state.save().unwrap();
20158            runner.state = RunState::load(&runner.state.id).unwrap();
20159            runner.sync_to_base().await.unwrap();
20160            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20161            assert_ne!(head, old);
20162            // Reentry after Git updated but before verification was invalidated.
20163            runner.state = RunState::load(&runner.state.id).unwrap();
20164            runner.execute_graph().await.unwrap();
20165            assert_eq!(runner.state.gate_fixes.len(), 1);
20166            assert_eq!(runner.state.reviews.len(), 1);
20167            assert_eq!(runner.state.reviews[0].head, old);
20168            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20169            assert_eq!(runner.state.verification_history.len(), 1);
20170            let history = &runner.state.verification_history[0];
20171            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20172            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20173            assert!(history.archived_at.is_some());
20174            assert_eq!(history.fixes_spent, Some(1));
20175            assert_eq!(history.gate[0].output_tail, "old failure");
20176            let archive_events: Vec<_> = runner
20177                .state
20178                .events
20179                .iter()
20180                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20181                .collect();
20182            assert_eq!(archive_events.len(), 1);
20183            assert!(archive_events[0].message.contains(&short(&old)));
20184            assert!(archive_events[0].message.contains(&short(&head)));
20185            assert!(
20186                archive_events[0]
20187                    .message
20188                    .contains("1 gate-fix round(s) already spent stay spent")
20189            );
20190            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20191            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20192            if e2e_ok {
20193                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20194                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20195            } else {
20196                assert!(!runner.state.gate_ran);
20197            }
20198            assert_eq!(
20199                runner.state.status,
20200                if e2e_ok && gate_ok {
20201                    RunStatus::Ready
20202                } else {
20203                    RunStatus::Blocked
20204                }
20205            );
20206            if !e2e_ok || !gate_ok {
20207                let cause = runner.state.verification_blocking_cause().unwrap();
20208                assert!(cause.contains(&head));
20209                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20210                // A later successful progress event must not become the cause.
20211                runner.state.event("land", "rebased successfully");
20212                let notice = crate::notices::run_ended(&runner.state).unwrap();
20213                assert!(!format!("{notice:?}").contains("rebased successfully"));
20214                assert!(runner.state.merge.is_none());
20215            }
20216            let before = std::fs::read_to_string(&phases).unwrap();
20217            runner.state.save().unwrap();
20218            runner.state = RunState::load(&runner.state.id).unwrap();
20219            runner.review_loop().await.unwrap();
20220            runner.gate().await.unwrap();
20221            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20222            assert_eq!(runner.state.verification_history.len(), 1);
20223            let history = &runner.state.verification_history[0];
20224            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20225            assert!(history.archived_at.is_some());
20226            assert_eq!(history.fixes_spent, Some(1));
20227        }
20228    }
20229
20230    #[cfg(unix)]
20231    #[tokio::test]
20232    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20233        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20234        let marker = tmp.path().join("gate-ran");
20235        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20236        runner.review_loop().await.unwrap();
20237        runner.gate().await.unwrap();
20238        assert_eq!(runner.state.status, RunStatus::Blocked);
20239        assert!(!marker.exists());
20240        assert!(runner.state.verification_history.is_empty());
20241        runner.state.gate_head = None;
20242        runner.gate().await.unwrap();
20243        assert!(marker.exists());
20244        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20245        assert_eq!(runner.state.verification_history.len(), 1);
20246        assert_eq!(runner.state.gate_fixes.len(), 1);
20247    }
20248
20249    #[cfg(unix)]
20250    #[tokio::test]
20251    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20252        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20253        runner.sync_to_base().await.unwrap();
20254        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20255        runner.state.reconcile_verification_head(&head);
20256        // Both crash-before-command and resource wait are unresolved evidence.
20257        for outcomes in [
20258            Vec::new(),
20259            vec![CommandOutcome {
20260                command: "true".into(),
20261                code: None,
20262                output_tail: "cache unavailable".into(),
20263                duration_ms: 0,
20264                resource_blocked: true,
20265                ..Default::default()
20266            }],
20267        ] {
20268            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20269                head.clone(),
20270                false,
20271                outcomes,
20272            ));
20273            runner.state.gate_ran = false;
20274            runner.state.gate.clear();
20275            runner.state.save().unwrap();
20276            runner.state = RunState::load(&runner.state.id).unwrap();
20277            runner.merge().await.unwrap();
20278            assert!(runner.state.merge.is_none());
20279            runner.review_loop().await.unwrap();
20280            runner.gate().await.unwrap();
20281            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20282            assert!(runner.state.gate_allows_progress());
20283            assert_eq!(runner.state.gate_fixes.len(), 1);
20284            assert!(runner.state.merge.is_none());
20285        }
20286        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20287        git::git(
20288            &runner.state.repo,
20289            &["commit", "--allow-empty", "-m", "external update"],
20290        )
20291        .await
20292        .unwrap();
20293        runner.merge().await.unwrap();
20294        assert!(runner.state.merge.is_none());
20295        assert_eq!(runner.state.status, RunStatus::Blocked);
20296    }
20297
20298    #[cfg(unix)]
20299    #[tokio::test]
20300    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20301        for waiting_on_gate in [false, true] {
20302            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20303            runner.sync_to_base().await.unwrap();
20304            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20305            runner.state.reconcile_verification_head(&head);
20306            if waiting_on_gate {
20307                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20308                    head.clone(),
20309                    true,
20310                    Vec::new(),
20311                ));
20312            }
20313            let cache = tmp.path().join("cache");
20314            runner.state.config.verify.e2e =
20315                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20316            runner.state.config.verify.gate = vec!["true".into()];
20317            runner.state.config.graph.timeout_resource_wait = 1;
20318            let owner =
20319                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20320            let guard =
20321                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20322                    crate::cache::AcquireOutcome::Acquired(g) => g,
20323                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20324                };
20325            runner.review_loop().await.unwrap();
20326            runner.gate().await.unwrap();
20327            assert!(!runner.state.gate_ran);
20328            assert_eq!(runner.state.gate_fixes.len(), 1);
20329            assert!(runner.state.resource_block.is_some());
20330            runner.merge().await.unwrap();
20331            assert!(runner.state.merge.is_none());
20332            drop(guard);
20333            runner.state = RunState::load(&runner.state.id).unwrap();
20334            // The driver clears the previous pass's resource stop on resume.
20335            runner.state.resource_block = None;
20336            runner.review_loop().await.unwrap();
20337            runner.gate().await.unwrap();
20338            assert!(runner.state.gate_allows_progress());
20339            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20340            assert_eq!(runner.state.gate_fixes.len(), 1);
20341        }
20342    }
20343
20344    #[cfg(unix)]
20345    #[tokio::test]
20346    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20347        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20348        runner.sync_to_base().await.unwrap();
20349        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20350        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20351        // Verification passes before pre_gate and fails on the mechanically changed head.
20352        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20353        runner.review_loop().await.unwrap();
20354        runner.gate().await.unwrap();
20355        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20356        assert_ne!(before, after);
20357        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20358        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20359        assert!(!runner.state.gate_allows_progress());
20360        runner.merge().await.unwrap();
20361        assert!(runner.state.merge.is_none());
20362        assert!(
20363            runner
20364                .state
20365                .verification_history
20366                .iter()
20367                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20368        );
20369
20370        // An incomplete review is still an independent hold on a changed head.
20371        runner.state.reviews[0].clean = false;
20372        runner.state.reviews[0].answered = 0;
20373        runner.state.config.verify.e2e = vec!["true".into()];
20374        runner.review_loop().await.unwrap();
20375        runner.gate().await.unwrap();
20376        runner.merge().await.unwrap();
20377        assert_eq!(runner.state.status, RunStatus::Blocked);
20378        assert!(runner.state.merge.is_none());
20379        assert!(
20380            runner
20381                .state
20382                .verification_blocking_cause()
20383                .unwrap()
20384                .contains("review blocked")
20385        );
20386    }
20387
20388    #[cfg(unix)]
20389    #[tokio::test]
20390    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20391        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20392        runner.state.gate_head = None;
20393        runner.state.config.verify.gate =
20394            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20395        runner.review_loop().await.unwrap();
20396        runner.gate().await.unwrap();
20397        assert_ne!(
20398            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20399            old
20400        );
20401        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20402        assert!(!runner.state.gate_allows_progress());
20403        assert_eq!(runner.state.status, RunStatus::Blocked);
20404        runner.merge().await.unwrap();
20405        assert!(runner.state.merge.is_none());
20406    }
20407
20408    #[cfg(unix)]
20409    #[tokio::test]
20410    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20411        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20412        let mut old_review = review_round(true, 0, 1, 1, false, true);
20413        old_review.head = head.clone();
20414        old_review.verified_head = Some(head.clone());
20415        runner.state.reviews = vec![old_review];
20416        runner.state.gate = vec![CommandOutcome {
20417            command: "old gate".into(),
20418            code: None,
20419            output_tail: "timed out after 2400s".into(),
20420            duration_ms: 2_400_000,
20421            resource_blocked: false,
20422            ..Default::default()
20423        }];
20424        runner.state.gate_ran = true;
20425        runner.state.gate_head = Some(head.clone());
20426        runner.state.land_approval = Some(crate::run::LandApproval {
20427            question: "old-head-approval".into(),
20428            head: head.clone(),
20429        });
20430        runner.state.authorize_base_sync(&task).unwrap();
20431        runner.sync_to_base().await.unwrap();
20432        assert!(!runner.state.base_sync_blocked());
20433        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20434        assert_ne!(head, fresh);
20435        assert_eq!(runner.state.reviews.len(), 1);
20436        assert!(!runner.state.gate_ran);
20437        let saved = &runner.state.base_sync_recovery.authorizations[0];
20438        assert_eq!(saved.reviews[0].head, head);
20439        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20440        assert!(saved.gate_ran);
20441        assert!(!saved.gate[0].ok());
20442        runner.review_loop().await.unwrap();
20443        runner.gate().await.unwrap();
20444        assert_eq!(runner.state.reviews[0].head, head);
20445        assert_eq!(
20446            runner.state.reviews[0].verified_head.as_deref(),
20447            Some(head.as_str())
20448        );
20449        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20450        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20451        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20452        assert!(runner.state.gate_ran);
20453        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20454        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20455        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20456        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20457        assert_eq!(
20458            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20459            "retained change"
20460        );
20461    }
20462
20463    #[cfg(unix)]
20464    #[tokio::test]
20465    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20466        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20467        let queue = crate::queue::Queue::open();
20468        let mut owner = queue.get(&task).unwrap();
20469        owner.release_operator("test-resume", None);
20470        queue.put(&mut owner).unwrap();
20471        let generation = owner.resumption.as_ref().unwrap().generation;
20472        runner.state.task_instruction = Some(owner.instruction.clone());
20473        runner.state.driver_exited = true;
20474        runner.state.save().unwrap();
20475        let home = crate::run::home();
20476        let _claim = queue.claim(&task).unwrap();
20477        owner.resumption.as_mut().unwrap().at =
20478            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20479        queue.put(&mut owner).unwrap();
20480        assert!(
20481            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20482                .await
20483                .is_err(),
20484            "an approval from before the stop grants nothing"
20485        );
20486        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20487        queue.put(&mut owner).unwrap();
20488        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20489            .await
20490            .unwrap();
20491        assert!(
20492            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20493                .await
20494                .is_err()
20495        );
20496        runner.state = RunState::load(&runner.state.id).unwrap();
20497        assert_eq!(
20498            runner.state.base_sync_recovery.authorizations[0].generation,
20499            Some(generation)
20500        );
20501        runner.sync_to_base().await.unwrap();
20502        let repo = runner.state.repo.clone();
20503        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20504        git::git(&repo, &["checkout", "main"]).await.unwrap();
20505        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20506        git::git(&repo, &["add", "."]).await.unwrap();
20507        git::git(&repo, &["commit", "-m", "move base again"])
20508            .await
20509            .unwrap();
20510        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20511        git::git(&repo, &["checkout", "fix/retained"])
20512            .await
20513            .unwrap();
20514        runner.sync_to_base().await.unwrap();
20515        assert!(!runner.state.base_sync_blocked());
20516        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20517        assert_eq!(runner.state.base_episode_used(), 2);
20518        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20519        assert_ne!(fresh, head);
20520        assert!(!runner.state.base_recovery_pending());
20521        // Even replaying the generation with a later timestamp grants nothing.
20522        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20523        queue.put(&mut owner).unwrap();
20524        assert!(
20525            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20526                .await
20527                .is_err()
20528        );
20529        runner.state = RunState::load(&runner.state.id).unwrap();
20530        runner.sync_to_base().await.unwrap();
20531        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20532        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20533        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20534    }
20535
20536    #[cfg(unix)]
20537    #[tokio::test]
20538    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20539        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20540        runner.state.base_sync = None;
20541        runner.state.status = RunStatus::Blocked;
20542        let mut second = runner.state.candidates[0].clone();
20543        second.label = 'B';
20544        runner.state.candidates.push(second);
20545        assert!(runner.state.votes.is_empty());
20546        assert!(runner.state.deliberation.is_empty());
20547        runner.deliberate().await.unwrap();
20548        runner.vote().await.unwrap();
20549        assert_eq!(runner.state.status, RunStatus::Blocked);
20550        assert!(runner.state.votes.is_empty());
20551        assert!(runner.state.deliberation.is_empty());
20552    }
20553
20554    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20555    /// reads nothing else off it.
20556    fn runner_at(status: RunStatus) -> Runner {
20557        let mut state = RunState::new(
20558            PathBuf::from("/nonexistent/repo"),
20559            "main".to_owned(),
20560            "deadbeef".to_owned(),
20561            "task".to_owned(),
20562            Config::default(),
20563        );
20564        // These fixtures test execution flow, independent of host disk capacity.
20565        state.config.disk.min_free_bytes = 0;
20566        // These fixtures share one home and save concurrently. Short clock
20567        // IDs can collide, making an ownership test read another test's run.
20568        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20569        state.id = format!(
20570            "20000101-000000-{:04x}",
20571            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20572        );
20573        state.status = status;
20574        Runner {
20575            state,
20576            roles: ResolvedRoles {
20577                implementers: Vec::new(),
20578                judges: Vec::new(),
20579                reviewers: Vec::new(),
20580                fixer: None,
20581                conductor: conductor(),
20582                implementer_roster: Vec::new(),
20583                judge_roster: Vec::new(),
20584                reviewer_roster: Vec::new(),
20585            },
20586            sem: Arc::new(Semaphore::new(1)),
20587            pause: Pause::new(),
20588            interrupt: Pause::new(),
20589        }
20590    }
20591
20592    #[tokio::test]
20593    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20594        crate::run::pin_test_home();
20595        let home = crate::run::home();
20596        let mut runner = runner_at(RunStatus::Ready);
20597        runner.state.driver_exited = true;
20598        runner.state.save().unwrap();
20599        let id = runner.state.id.clone();
20600        let path = runner.state.dir().join("run.json");
20601        let ids = ["R1-1-1".into()];
20602        let lease = crate::driver::maintenance(&home, &id).unwrap();
20603        for (guard, expected) in [
20604            (Some(lease), "currently being worked on"),
20605            (None, "ownership is being updated"),
20606        ] {
20607            let owner = if guard.is_none() {
20608                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20609            } else {
20610                None
20611            };
20612            let before = std::fs::read(&path).unwrap();
20613            let err = runner
20614                .fix_selected(&ids, "ownership conflict", false)
20615                .await
20616                .unwrap_err();
20617            assert!(format!("{err:#}").contains(expected), "{err:#}");
20618            assert_eq!(std::fs::read(&path).unwrap(), before);
20619            assert!(!runner.state.dir().join("fix.lock").exists());
20620            drop(owner);
20621            drop(guard);
20622        }
20623        let mut disk = RunState::load(&id).unwrap();
20624        disk.driver_exited = false;
20625        disk.driver_pid = Some(std::process::id());
20626        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20627        disk.save().unwrap();
20628        assert_eq!(
20629            disk.liveness_under(&home, false),
20630            crate::run::Liveness::Live
20631        );
20632        let before = std::fs::read(&path).unwrap();
20633        let err = runner
20634            .fix_selected(&ids, "live driver", false)
20635            .await
20636            .unwrap_err();
20637        assert!(
20638            err.to_string().contains("currently being worked on"),
20639            "{err:#}"
20640        );
20641        assert_eq!(std::fs::read(&path).unwrap(), before);
20642        assert!(!runner.state.dir().join("fix.lock").exists());
20643        disk.driver_exited = true;
20644        disk.driver_pid = None;
20645        disk.driver_started_at = None;
20646        disk.status = RunStatus::Reviewing;
20647        disk.save().unwrap();
20648        let before = std::fs::read(&path).unwrap();
20649        let err = runner
20650            .fix_selected(&ids, "stale state", false)
20651            .await
20652            .unwrap_err();
20653        assert!(
20654            err.to_string().contains("run changed since it was loaded"),
20655            "{err:#}"
20656        );
20657        assert_eq!(std::fs::read(&path).unwrap(), before);
20658        assert!(!runner.state.dir().join("fix.lock").exists());
20659        assert!(runner.state.operator_fixes.is_empty());
20660    }
20661
20662    #[tokio::test]
20663    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20664        use std::future::Future;
20665        use std::task::Poll;
20666
20667        crate::run::pin_test_home();
20668        let home = crate::run::home();
20669        let repo = tempfile::tempdir().unwrap();
20670        let mut runner = runner_at(RunStatus::Ready);
20671        runner.state.repo = repo.path().to_path_buf();
20672        runner.state.driver_exited = true;
20673        runner.state.candidates.push(Candidate {
20674            index: 0,
20675            label: 'A',
20676            agent: "mock".into(),
20677            branch: "magi/test/A".into(),
20678            worktree: repo.path().join("wt"),
20679            summary: String::new(),
20680            stat: String::new(),
20681            files: 0,
20682            commits: 0,
20683            empty: false,
20684            failed: None,
20685            verified_noop: None,
20686            duration_ms: 0,
20687            folded: false,
20688        });
20689        runner.state.tally = Some(Tally {
20690            first_choice: BTreeMap::from([('A', 1)]),
20691            borda: BTreeMap::new(),
20692            winner: 'A',
20693            rankings: 1,
20694            unanimous_initial: true,
20695            deliberated: false,
20696            changed_votes: 0,
20697            unanimous_final: true,
20698            tie_break: None,
20699            judges: 1,
20700            present: 1,
20701            quorum: 1,
20702            met_quorum: true,
20703            uncontested: None,
20704        });
20705        runner.state.save().unwrap();
20706        let id = runner.state.id.clone();
20707        let dir = runner.state.dir();
20708        let before = std::fs::read(dir.join("run.json")).unwrap();
20709        let ids = ["R1-1-1".into()];
20710        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20711        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20712            Poll::Pending => Poll::Ready(()),
20713            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20714        })
20715        .await;
20716        assert!(FixClaim::acquire(&dir).is_err());
20717        assert!(crate::driver::maintenance(&home, &id).is_err());
20718        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20719        drop(fix);
20720        assert!(FixClaim::acquire(&dir).is_ok());
20721        assert!(crate::driver::maintenance(&home, &id).is_ok());
20722        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20723    }
20724
20725    #[tokio::test]
20726    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20727        crate::run::pin_test_home();
20728        let temp = tempfile::tempdir().unwrap();
20729        let root = temp.path().canonicalize().unwrap();
20730        let repo = root.join("repo");
20731        std::fs::create_dir(&repo).unwrap();
20732        init_repo(&repo);
20733        git::git(&repo, &["config", "core.autocrlf", "false"])
20734            .await
20735            .unwrap();
20736        let mut runner = runner_at(RunStatus::Blocked);
20737        runner.state.repo = repo.clone();
20738        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20739        runner.state.config.agents = vec![conductor()];
20740        runner.state.config.graph.selected_implementer = Some("conductor".into());
20741        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20742        let (shell, command, setup_output) = if cfg!(windows) {
20743            (
20744                vec!["cmd".into(), "/C".into()],
20745                "echo ready>seat-ready",
20746                "ready\r\n",
20747            )
20748        } else {
20749            (
20750                vec!["sh".into(), "-c".into()],
20751                "printf ready > seat-ready",
20752                "ready",
20753            )
20754        };
20755        runner.state.config.verify.shell = Some(shell);
20756        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20757            run: Some(command.into()),
20758            ..Default::default()
20759        }];
20760        runner.state.save().unwrap();
20761        let path = runner.state.worktree_root().join("judge-1");
20762        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20763            .await
20764            .unwrap();
20765        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20766        git::git(&path, &["add", "."]).await.unwrap();
20767        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20768        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20769            .await
20770            .unwrap();
20771        git::git(&path, &["checkout", "--detach", &head])
20772            .await
20773            .unwrap();
20774        let evidence = crate::fold_evidence::snapshot(
20775            &runner.state,
20776            &crate::run::home().canonicalize().unwrap(),
20777            &head,
20778            64 * 1024 * 1024,
20779        )
20780        .await
20781        .unwrap();
20782        let mut contents = BTreeMap::new();
20783        contents.insert(
20784            repo.join("logs/HEAD"),
20785            format!("{head} {head} fixture\n").into_bytes(),
20786        );
20787        let record = serde_json::json!({
20788            "version":1, "run":runner.state.id, "source":path, "head":head,
20789            "evidence":evidence, "admin":{}, "admin_contents":contents,
20790            "history":{head.clone():evidence}, "phase":"evicted"
20791        });
20792        std::fs::write(
20793            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20794            serde_json::to_vec(&record).unwrap(),
20795        )
20796        .unwrap();
20797        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20798        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20799            .await
20800            .unwrap();
20801        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20802        assert!(
20803            !git::git_raw(&repo, &["cat-file", "-e", &head])
20804                .await
20805                .unwrap()
20806                .ok()
20807        );
20808        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20809        let error = resumed.execute().await.unwrap_err();
20810        assert!(
20811            error
20812                .to_string()
20813                .contains("selected implementation is held"),
20814            "{error:#}"
20815        );
20816        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
20817        assert_eq!(
20818            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
20819            setup_output
20820        );
20821        assert_eq!(
20822            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
20823            "unrelated seat"
20824        );
20825        let error = resumed.execute().await.unwrap_err();
20826        assert!(
20827            error
20828                .to_string()
20829                .contains("selected implementation is held"),
20830            "{error:#}"
20831        );
20832        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
20833        git::git(&path, &["add", "."]).await.unwrap();
20834        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
20835        let next = git::git(
20836            &path,
20837            &[
20838                "commit-tree",
20839                &next_tree,
20840                "-p",
20841                &head,
20842                "-m",
20843                "next review checkpoint",
20844            ],
20845        )
20846        .await
20847        .unwrap();
20848        git::git(&path, &["checkout", "--detach", &next])
20849            .await
20850            .unwrap();
20851        resumed.state.reviews.push(
20852            serde_json::from_value(serde_json::json!({
20853                "round":1, "head":next, "reviews":[]
20854            }))
20855            .unwrap(),
20856        );
20857        resumed.state.save().unwrap();
20858        let error = resumed.execute().await.unwrap_err();
20859        assert!(
20860            error
20861                .to_string()
20862                .contains("selected implementation is held"),
20863            "{error:#}"
20864        );
20865        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
20866    }
20867
20868    #[tokio::test]
20869    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
20870        crate::run::pin_test_home();
20871        let mut runner = runner_at(RunStatus::Gating);
20872        runner.state.save().unwrap();
20873        let id = runner.state.id.clone();
20874        let passes = runner.state.passes.len();
20875        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20876        let mut claiming = Box::pin(runner.claim_driver(None));
20877        std::future::poll_fn(|cx| {
20878            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
20879            std::task::Poll::Ready(())
20880        })
20881        .await;
20882        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
20883        drop(owner);
20884        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
20885            .await
20886            .unwrap()
20887            .unwrap();
20888        assert_eq!(execution.runner.state.passes.len(), passes + 1);
20889        assert!(execution.runner.state.resource_block.is_none());
20890        assert_eq!(
20891            execution.runner.state.liveness(false),
20892            crate::run::Liveness::Live
20893        );
20894        drop(execution);
20895        assert!(RunState::load(&id).unwrap().driver_exited);
20896    }
20897
20898    #[tokio::test]
20899    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
20900        crate::run::pin_test_home();
20901        let mut runner = runner_at(RunStatus::Gating);
20902        runner.state.save().unwrap();
20903        // run.json can commit, but the subsequent lease metadata write fails.
20904        // Cleanup must run after releasing the short ownership lock.
20905        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
20906        assert!(runner.claim_driver(None).await.is_err());
20907        assert!(runner.state.driver_exited);
20908        assert_eq!(runner.state.driver_pid, None);
20909        let disk = RunState::load(&runner.state.id).unwrap();
20910        assert!(disk.driver_exited);
20911        assert_eq!(disk.driver_pid, None);
20912        assert_eq!(disk.status, RunStatus::Gating);
20913    }
20914
20915    #[tokio::test]
20916    async fn an_early_graph_error_releases_its_driver() {
20917        crate::run::pin_test_home();
20918        let mut runner = runner_at(RunStatus::Blocked);
20919        runner.state.config.graph.selected_implementer = Some("selected".into());
20920        runner.state.save().unwrap();
20921        assert!(runner.execute().await.is_err());
20922        let disk = RunState::load(&runner.state.id).unwrap();
20923        assert!(disk.driver_exited);
20924        assert_eq!(disk.driver_pid, None);
20925        assert_eq!(disk.status, RunStatus::Blocked);
20926    }
20927
20928    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
20929        crate::run::MergeRepair {
20930            question: "repair-question".into(),
20931            head: "old-head".into(),
20932            pr: "https://github.com/o/r/pull/42".into(),
20933            reviews: vec![review_round(false, 1, 1, 1, false, true)],
20934            gate: vec![outcome(Some(0), false)],
20935            gate_head: Some("old-head".into()),
20936            gate_fixes: Vec::new(),
20937            pre_gate: Vec::new(),
20938            phase,
20939            failure: None,
20940        }
20941    }
20942
20943    #[tokio::test]
20944    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
20945        crate::run::pin_test_home();
20946        let mut runner = runner_at(RunStatus::Landing);
20947        runner.state.merge_repairs.push(merge_repair_request(
20948            crate::run::MergeRepairPhase::Requested,
20949        ));
20950        runner.state.save().unwrap();
20951        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
20952        assert!(
20953            runner
20954                .execute()
20955                .await
20956                .unwrap_err()
20957                .to_string()
20958                .contains("already running")
20959        );
20960        assert_eq!(
20961            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20962            crate::run::MergeRepairPhase::Requested
20963        );
20964        drop(claim);
20965        let mut disk = runner.state.clone();
20966        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
20967        disk.save().unwrap();
20968        assert!(
20969            runner
20970                .execute()
20971                .await
20972                .unwrap_err()
20973                .to_string()
20974                .contains("decision changed")
20975        );
20976        assert_eq!(
20977            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20978            crate::run::MergeRepairPhase::Complete
20979        );
20980    }
20981
20982    #[test]
20983    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
20984        crate::run::pin_test_home();
20985        let mut runner = runner_at(RunStatus::Landing);
20986        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
20987        runner.state.reviews = request.reviews.clone();
20988        runner.state.gate = request.gate.clone();
20989        runner.state.gate_ran = true;
20990        runner.state.land_approval = Some(crate::run::LandApproval {
20991            question: "old".into(),
20992            head: "old-head".into(),
20993        });
20994        runner.state.merge_repairs.push(request);
20995        runner.begin_merge_repair_review(0).unwrap();
20996        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
20997        assert!(!runner.state.gate_status().ok());
20998        assert!(runner.state.land_approval.is_none());
20999        let disk = RunState::load(&runner.state.id).unwrap();
21000        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21001        assert!(disk.merge_repairs[0].gate[0].ok());
21002        assert_eq!(
21003            disk.merge_repairs[0].phase,
21004            crate::run::MergeRepairPhase::Reviewing
21005        );
21006        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21007        assert!(disk.reviews.is_empty());
21008    }
21009
21010    #[tokio::test]
21011    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21012        crate::run::pin_test_home();
21013        for phase in [
21014            crate::run::MergeRepairPhase::Fixing,
21015            crate::run::MergeRepairPhase::Requested,
21016        ] {
21017            let mut runner = runner_at(RunStatus::Landing);
21018            runner.state.config.graph.land_rounds = 0;
21019            runner.state.merge_repairs.push(merge_repair_request(phase));
21020            runner.state.save().unwrap();
21021            assert!(!runner.repair_merge_review().await.unwrap());
21022            assert_eq!(runner.state.status, RunStatus::Blocked);
21023            assert_eq!(
21024                runner.state.merge_repairs[0].phase,
21025                crate::run::MergeRepairPhase::Failed
21026            );
21027            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21028            assert!(
21029                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21030                    "interrupted"
21031                } else {
21032                    "budget exhausted"
21033                })
21034            );
21035            assert!(runner.state.merge.is_none());
21036        }
21037    }
21038
21039    /// `park_here` folding in the reason `Pause::park_because` recorded -
21040    /// this is what lets an operator reading a run's events tell an
21041    /// interrupt-driven park from an ordinary shutdown park.
21042    #[test]
21043    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21044        crate::run::pin_test_home();
21045        let mut runner = runner_at(RunStatus::Implementing);
21046        let interrupt = Pause::new();
21047        runner.watch_interrupt(interrupt.clone());
21048
21049        interrupt.park_because("task a1b2 asked to run first");
21050
21051        assert!(runner.park_here().expect("park_here"));
21052        assert!(runner.state.parked);
21053        let last = runner.state.events.last().expect("a park event");
21054        assert_eq!(last.node, "park");
21055        assert!(
21056            last.message.contains("task a1b2 asked to run first"),
21057            "expected the interrupt reason in {:?}",
21058            last.message
21059        );
21060    }
21061
21062    /// The cause is stored on the pass when it parks, and the first cause a
21063    /// shared pause was given is the one that stays.
21064    #[test]
21065    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21066        crate::run::pin_test_home();
21067        let mut runner = runner_at(RunStatus::Implementing);
21068        runner.state.begin_pass();
21069        let shutdown = Pause::new();
21070        runner.on_pause(shutdown.clone());
21071        let upgrade = ParkCause::Upgrade {
21072            from: "0.121.0".to_owned(),
21073            to: Some("0.121.1".to_owned()),
21074        };
21075        shutdown.park_for(upgrade.clone());
21076        shutdown.park_for(ParkCause::Operator);
21077
21078        assert!(runner.park_here().expect("park_here"));
21079        assert_eq!(
21080            runner.state.passes[0].end,
21081            Some(crate::run::PassEnd::Parked { cause: upgrade })
21082        );
21083        let last = runner.state.events.last().expect("a park event");
21084        assert!(last.message.contains("0.121.0"), "{}", last.message);
21085    }
21086
21087    #[tokio::test]
21088    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21089        crate::run::pin_test_home();
21090        let mut runner = runner_at(RunStatus::Reviewing);
21091        runner.state.save().unwrap();
21092        let mut execution = runner.claim_driver(None).await.expect("first execution");
21093        assert_eq!(execution.runner.state.passes.len(), 1);
21094        execution
21095            .driver
21096            .finish(&mut execution.runner.state)
21097            .await
21098            .unwrap();
21099    }
21100
21101    #[tokio::test]
21102    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21103        crate::run::pin_test_home();
21104        let mut runner = runner_at(RunStatus::Reviewing);
21105        runner.state.config.agents = vec![conductor()];
21106        runner.state.config.graph.timeout_resource_wait = 0;
21107        runner.state.save().unwrap();
21108        let id = runner.state.id.clone();
21109        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21110        assert!(runner.claim_driver(None).await.is_err());
21111        drop(owner);
21112        drop(runner);
21113        let mut resumed = Runner::resume(&id).unwrap();
21114        assert_eq!(resumed.state.driver_claimed, Some(false));
21115        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21116        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21117        let mut execution = resumed
21118            .claim_driver(None)
21119            .await
21120            .expect("retry initial claim after reload");
21121        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21122        assert_eq!(execution.runner.state.passes.len(), 1);
21123        execution
21124            .driver
21125            .finish(&mut execution.runner.state)
21126            .await
21127            .unwrap();
21128    }
21129
21130    #[tokio::test]
21131    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21132        crate::run::pin_test_home();
21133        let mut runner = runner_at(RunStatus::Reviewing);
21134        runner.state.config.agents = vec![conductor()];
21135        runner.state.save().unwrap();
21136        let id = runner.state.id.clone();
21137        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21138        let mut resumed = Runner::resume(&id).unwrap();
21139        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21140        assert!(resumed.claim_driver(None).await.is_err());
21141        assert!(RunState::load(&id).unwrap().passes.is_empty());
21142        drop(lease);
21143        let mut execution = resumed.claim_driver(None).await.unwrap();
21144        execution
21145            .driver
21146            .finish(&mut execution.runner.state)
21147            .await
21148            .unwrap();
21149    }
21150
21151    #[tokio::test]
21152    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21153        crate::run::pin_test_home();
21154        let mut runner = runner_at(RunStatus::Reviewing);
21155        let state = &mut runner.state;
21156        state.config.agents = vec![conductor()];
21157        state.driver_claimed = None;
21158        state.driver_pid = Some(std::process::id());
21159        state.driver_started_at = None;
21160        state.begin_pass();
21161        state.save().unwrap();
21162        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21163        std::fs::write(
21164            state.dir().join("driver.json"),
21165            serde_json::to_vec(&serde_json::json!({
21166                "pid": state.driver_pid, "started_at": null,
21167                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21168            }))
21169            .unwrap(),
21170        )
21171        .unwrap();
21172        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21173        drop(lease);
21174        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21175        let mut resumed = Runner::resume(&state.id).unwrap();
21176        assert!(!resumed.state.driver_exited);
21177        let mut execution = resumed
21178            .claim_driver(None)
21179            .await
21180            .expect("lease proves previous execution ended");
21181        assert_eq!(execution.runner.state.passes.len(), 2);
21182        execution
21183            .driver
21184            .finish(&mut execution.runner.state)
21185            .await
21186            .unwrap();
21187    }
21188
21189    #[tokio::test]
21190    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21191        crate::run::pin_test_home();
21192        let mut runner = runner_at(RunStatus::Reviewing);
21193        let mut json = serde_json::to_value(&runner.state).unwrap();
21194        json.as_object_mut().unwrap().remove("driver_claimed");
21195        runner.state = serde_json::from_value(json).unwrap();
21196        assert_eq!(runner.state.driver_claimed, None);
21197        runner.state.save().unwrap();
21198        let mut execution = runner
21199            .claim_driver(None)
21200            .await
21201            .expect("the execution lease, not a missing marker, excludes a second driver");
21202        assert_eq!(execution.runner.state.passes.len(), 1);
21203        execution
21204            .driver
21205            .finish(&mut execution.runner.state)
21206            .await
21207            .unwrap();
21208    }
21209
21210    #[tokio::test]
21211    async fn driver_admission_refuses_a_proven_live_driver() {
21212        crate::run::pin_test_home();
21213        let mut runner = runner_at(RunStatus::Reviewing);
21214        let pid = std::process::id();
21215        runner.state.driver_pid = Some(pid);
21216        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21217        assert!(runner.state.driver_started_at.is_some());
21218        runner.state.save().unwrap();
21219        let error = runner
21220            .claim_driver(None)
21221            .await
21222            .err()
21223            .expect("a live driver must refuse");
21224        let message = error.to_string();
21225        assert!(
21226            message.starts_with("run already has a live driver: "),
21227            "{message}"
21228        );
21229        assert!(message.contains(&format!("pid={pid}")), "{message}");
21230        assert!(
21231            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21232            "{message}"
21233        );
21234        let saved = RunState::load(&runner.state.id).unwrap();
21235        assert_eq!(saved.driver_pid, Some(pid));
21236        assert_eq!(saved.status, RunStatus::Reviewing);
21237        assert!(saved.passes.is_empty());
21238    }
21239
21240    #[tokio::test]
21241    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21242        crate::run::pin_test_home();
21243        let home = crate::run::home();
21244        let mut runner = runner_at(RunStatus::Reviewing);
21245        runner.state.driver_exited = true;
21246        runner.state.driver_pid = None;
21247        runner.state.driver_started_at = None;
21248        runner.state.save().unwrap();
21249
21250        let queue = crate::queue::Queue::at(home.join("queue"));
21251        let mut task = crate::queue::Task::new(
21252            "task".into(),
21253            "task".into(),
21254            runner.state.repo.clone(),
21255            crate::queue::Source::Human,
21256        );
21257        task.runs.push(runner.state.id.clone());
21258        queue.put(&mut task).unwrap();
21259        let payload = serde_json::json!({
21260            "queue": home.join("queue"),
21261            "task": task.id,
21262            "opts": crate::daemon::Opts::default(),
21263            "standalone": false,
21264        });
21265        let (job, lease) =
21266            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21267
21268        let error = runner
21269            .claim_driver(None)
21270            .await
21271            .err()
21272            .expect("another active worker claim must refuse");
21273        let message = error.to_string();
21274        assert!(
21275            message.starts_with("run already has a live driver: worker claim"),
21276            "{message}"
21277        );
21278        assert!(message.contains(&job.id), "{message}");
21279        assert!(message.contains("status=running"), "{message}");
21280        assert!(message.contains("live.lock held"), "{message}");
21281
21282        drop(lease);
21283        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21284    }
21285
21286    #[test]
21287    fn parking_resource_halt_persists_the_pass_once() {
21288        crate::run::pin_test_home();
21289        let mut runner = runner_at(RunStatus::Reviewing);
21290        runner.state.begin_pass();
21291        runner.state.resource_block = Some(crate::run::ResourceBlock {
21292            node: "fix".into(),
21293            kind: "shared build cache".into(),
21294            detail: "cancelled".into(),
21295            at: Timestamp::now(),
21296            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21297        });
21298        let cause = ParkCause::Upgrade {
21299            from: "old".into(),
21300            to: Some("new".into()),
21301        };
21302        runner.pause.park_for(cause.clone());
21303        // Both direct fixer exits and graph resource boundaries must complete
21304        // parking, rather than returning a stale Reviewing record.
21305        runner.stop_for_resource().unwrap();
21306        assert!(runner.resource_halt().unwrap());
21307        assert!(runner.park_here().unwrap());
21308        let saved = RunState::load(&runner.state.id).unwrap();
21309        assert!(saved.parked);
21310        assert_eq!(saved.status, RunStatus::Reviewing);
21311        assert!(saved.passes[0].ended_at.is_some());
21312        assert_eq!(
21313            saved.passes[0].end,
21314            Some(crate::run::PassEnd::Parked {
21315                cause: cause.clone()
21316            })
21317        );
21318        assert_eq!(
21319            saved.resource_block.unwrap().cause,
21320            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21321        );
21322        assert_eq!(
21323            saved
21324                .events
21325                .iter()
21326                .filter(|event| event.node == "park")
21327                .count(),
21328            1
21329        );
21330    }
21331
21332    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21333    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21334    /// cleared) must not make a *different* run - one only watching its own,
21335    /// unshared interrupt `Pause` - see itself as parked. If a future change
21336    /// ever collapsed these back into one handle, the interrupt scheduler
21337    /// would park every run for the rest of the daemon's life, not just the
21338    /// one it meant to interrupt.
21339    #[test]
21340    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21341        crate::run::pin_test_home();
21342        let mut runner = runner_at(RunStatus::Implementing);
21343        let shutdown = Pause::new();
21344        runner.on_pause(shutdown.clone());
21345        let interrupt = Pause::new();
21346        runner.watch_interrupt(interrupt.clone());
21347
21348        // Nobody has asked for anything yet.
21349        assert!(!runner.park_here().expect("park_here"));
21350        assert!(!runner.state.parked);
21351
21352        // Only the interrupt handle fires; the shutdown handle stays clear.
21353        interrupt.park_because("test");
21354        assert!(!shutdown.parked());
21355        assert!(runner.park_here().expect("park_here"));
21356    }
21357
21358    /// The property every prior attempt at this feature failed to pin down:
21359    /// asking a run to park while one of its nodes has a real, in-flight
21360    /// async operation running (an agent call, in production) must not cut
21361    /// that operation short. `park_here` is only ever consulted *between*
21362    /// `execute`'s node calls - see its own doc - so nothing inside a node
21363    /// can observe a park request until the node itself returns. This proves
21364    /// that structurally, with real `tokio` concurrency and a channel
21365    /// handshake (never a sleep, which would only prove "usually", not
21366    /// "cannot"): the "node" below reports that it has genuinely started,
21367    /// and only then is the park requested; the node still has to be told to
21368    /// finish before `park_here` is ever called, exactly mirroring every
21369    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21370    /// in `execute`.
21371    #[tokio::test]
21372    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21373        crate::run::pin_test_home();
21374        let mut runner = runner_at(RunStatus::Implementing);
21375        let interrupt = Pause::new();
21376        runner.watch_interrupt(interrupt.clone());
21377
21378        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21379        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21380
21381        // Stands in for one node's in-flight agent call: it proves it has
21382        // genuinely started, then blocks - exactly as a spawned CLI process
21383        // does - until told to finish.
21384        let node = async move {
21385            started_tx.send(()).expect("send started");
21386            finish_rx.await.expect("recv finish");
21387            "node finished"
21388        };
21389
21390        let interrupter = async move {
21391            started_rx.await.expect("recv started");
21392            // The call is now genuinely in flight. Ask it to park.
21393            interrupt.park_because("higher-priority task waiting");
21394            // Nothing the node does can observe this yet - there is no
21395            // check inside it, by construction - so let the executor run
21396            // anything pending and then let the node finish on its own.
21397            tokio::task::yield_now().await;
21398            finish_tx.send(()).expect("send finish");
21399        };
21400
21401        let (node_result, ()) = tokio::join!(node, interrupter);
21402        assert_eq!(
21403            node_result, "node finished",
21404            "the in-flight call ran to completion"
21405        );
21406
21407        // Only now, at the boundary the real `execute` would check right
21408        // after this node, does the park take effect.
21409        assert!(runner.park_here().expect("park_here"));
21410        assert!(runner.state.parked);
21411    }
21412
21413    /// A run parked mid-competition carries every field it had accumulated
21414    /// through the exact same disk round-trip an ordinary resume uses -
21415    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21416    /// Nothing about parking for an interrupt is a special case of that path;
21417    /// this is what proves it rather than assuming it.
21418    #[test]
21419    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21420        crate::run::pin_test_home();
21421        let mut runner = runner_at(RunStatus::Judging);
21422        // `Runner::resume` re-resolves roles from the saved config, which
21423        // refuses an empty roster - give it the same minimal one `conductor`
21424        // itself uses.
21425        runner.state.config.agents = vec![conductor()];
21426        runner.state.candidates = vec![Candidate {
21427            index: 0,
21428            label: 'A',
21429            agent: "alpha".to_owned(),
21430            branch: "magi/x/A".to_owned(),
21431            worktree: PathBuf::from("/nonexistent/worktree"),
21432            summary: "did the thing".to_owned(),
21433            stat: "1 file changed".to_owned(),
21434            files: 1,
21435            commits: 1,
21436            empty: false,
21437            failed: None,
21438            verified_noop: None,
21439            duration_ms: 1234,
21440            folded: false,
21441        }];
21442        let run_id = runner.state.id.clone();
21443
21444        let interrupt = Pause::new();
21445        runner.watch_interrupt(interrupt.clone());
21446        interrupt.park_because("task c3d4 asked to run first");
21447        assert!(runner.park_here().expect("park_here"));
21448
21449        let resumed = Runner::resume(&run_id).expect("resume");
21450        assert_eq!(resumed.state.candidates.len(), 1);
21451        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21452        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21453        assert_eq!(resumed.state.status, runner.state.status);
21454        assert!(
21455            resumed.state.parked,
21456            "still parked until `execute` actually walks the graph again"
21457        );
21458        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21459    }
21460
21461    /// A fresh open question on `run`, stored and handed back for assertions.
21462    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21463        let mut q = ask::Question::new(
21464            run.to_owned(),
21465            "implement".to_owned(),
21466            "impl-A".to_owned(),
21467            "Which storage backend should the cache use?".to_owned(),
21468            String::new(),
21469            vec!["SQLite".to_owned(), "Redis".to_owned()],
21470        );
21471        store.put(&mut q).unwrap();
21472        q
21473    }
21474
21475    #[test]
21476    fn a_failed_runs_open_question_is_abandoned() {
21477        ask_test_home();
21478        let store = ask::Questions::open();
21479        let mut runner = runner_at(RunStatus::Failed);
21480        let run = runner.state.id.clone();
21481        let q = ask_open_question(&store, &run);
21482
21483        runner.settle_questions();
21484
21485        let back = store.get(&q.id).unwrap();
21486        assert!(
21487            !back.status.open(),
21488            "the seat that asked died with the run; nobody is left to read an answer"
21489        );
21490        assert!(
21491            back.detail.contains(&run) && back.detail.contains("failed"),
21492            "the reason names what the run became, not just that it is gone: {}",
21493            back.detail
21494        );
21495    }
21496
21497    #[test]
21498    fn a_merged_runs_open_question_is_abandoned_too() {
21499        ask_test_home();
21500        let store = ask::Questions::open();
21501        // A run that finishes cleanly still leaves nobody to read an answer -
21502        // this is not only a failure-path cleanup.
21503        for status in [RunStatus::Merged, RunStatus::Ready] {
21504            let mut runner = runner_at(status);
21505            let run = runner.state.id.clone();
21506            let q = ask_open_question(&store, &run);
21507
21508            runner.settle_questions();
21509
21510            let back = store.get(&q.id).unwrap();
21511            assert!(
21512                !back.status.open(),
21513                "{status:?} run's question must not outlive the run"
21514            );
21515        }
21516    }
21517
21518    #[test]
21519    fn a_still_resumable_runs_open_question_is_left_alone() {
21520        ask_test_home();
21521        let store = ask::Questions::open();
21522        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21523        // review round and the seat sessions are all still on disk — so a
21524        // question asked mid-round may yet get a real answer from a real
21525        // resume. Sweeping it here would be exactly the failure mode this
21526        // whole feature exists to avoid on the other side.
21527        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21528            let mut runner = runner_at(status);
21529            let run = runner.state.id.clone();
21530            let q = ask_open_question(&store, &run);
21531
21532            runner.settle_questions();
21533
21534            let back = store.get(&q.id).unwrap();
21535            assert!(
21536                back.status.open(),
21537                "{status:?} is still alive; the question must still be waiting"
21538            );
21539        }
21540    }
21541
21542    #[test]
21543    fn settle_questions_never_touches_an_already_answered_question() {
21544        ask_test_home();
21545        let store = ask::Questions::open();
21546        let mut runner = runner_at(RunStatus::Failed);
21547        let run = runner.state.id.clone();
21548        let mut q = ask_open_question(&store, &run);
21549        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21550            .unwrap();
21551        store.put(&mut q).unwrap();
21552
21553        // Called twice, the way a crash-recovered daemon reclaim and the
21554        // graph's own cleanup both can for the same run — `abandon_for_run`
21555        // only ever touches what is still open, so this must be inert both
21556        // times, not merely the second.
21557        runner.settle_questions();
21558        runner.settle_questions();
21559
21560        let back = store.get(&q.id).unwrap();
21561        assert_eq!(
21562            back.status,
21563            ask::QuestionStatus::Answered,
21564            "a real answer is a decision on record, never overwritten by a sweep"
21565        );
21566    }
21567
21568    #[tokio::test]
21569    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21570        let tmp = tempfile::tempdir().unwrap();
21571        let home = tmp.path().join("home");
21572        let repo = tmp.path().join("repo");
21573        std::fs::create_dir(&home).unwrap();
21574        std::fs::create_dir(&repo).unwrap();
21575        init_repo(&repo);
21576
21577        let mut config = Config::default();
21578        config.graph.worktree_root = Some(tmp.path().join("wt"));
21579        config.verify.build_cache = crate::config::BuildCache::Isolated;
21580        let mut state = RunState::new(
21581            repo.clone(),
21582            "main".into(),
21583            "base".into(),
21584            "fold fixture".into(),
21585            config,
21586        );
21587        let root = state.worktree_root();
21588        let mut outputs = Vec::new();
21589        for name in ["idle", "busy"] {
21590            let checkout = root.join(name);
21591            git::worktree_add_detached(&repo, &checkout, "main")
21592                .await
21593                .unwrap();
21594            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21595            let output = target.join("generated");
21596            std::fs::write(&output, name).unwrap();
21597            outputs.push((target, output));
21598        }
21599        let unknown = crate::build_target::root(&home)
21600            .join("00000000-0000-0000-0000-000000000000")
21601            .join("target");
21602        std::fs::create_dir_all(&unknown).unwrap();
21603        let unowned = unknown.join("generated");
21604        std::fs::write(&unowned, "keep").unwrap();
21605        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21606        let crate::cache::AcquireOutcome::Acquired(_lease) =
21607            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21608        else {
21609            panic!("fixture target must be free");
21610        };
21611
21612        state.save_under(&home).unwrap();
21613        fold_run(&mut state, true, &home).await.unwrap();
21614        assert!(!root.exists());
21615        assert!(!outputs[0].1.exists());
21616        assert!(outputs[1].1.is_file());
21617        assert!(unowned.is_file());
21618    }
21619
21620    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21621    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21622    /// without merging, whose winner is still the operator's answer to read.
21623    /// Nothing previously called `fold_run` itself with a real `tally`, so
21624    /// this is the first test to pin down the one distinction the whole
21625    /// automatic-fold feature depends on: the winner's worktree and branch
21626    /// must survive, everything else sharing the run's worktree bay - a
21627    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21628    /// second sweep treats every non-winner directory under the bay alike -
21629    /// must not.
21630    #[tokio::test]
21631    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21632        crate::run::pin_test_home();
21633        let tmp = tempfile::tempdir().expect("tempdir");
21634        let repo = tmp.path().join("repo");
21635        std::fs::create_dir_all(&repo).unwrap();
21636        init_repo(&repo);
21637
21638        let mut config = Config::default();
21639        config.graph.worktree_root = Some(tmp.path().join("wt"));
21640
21641        let mut state = RunState::new(
21642            repo.clone(),
21643            "main".to_owned(),
21644            "deadbeef".to_owned(),
21645            "task".to_owned(),
21646            config,
21647        );
21648        let root = state.worktree_root();
21649        let wt_a = root.join("cand-A");
21650        let wt_b = root.join("cand-B");
21651        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21652            .await
21653            .expect("worktree A");
21654        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21655            .await
21656            .expect("worktree B");
21657
21658        state.candidates = vec![
21659            Candidate {
21660                index: 0,
21661                label: 'A',
21662                agent: "alpha".to_owned(),
21663                branch: "magi/x/A".to_owned(),
21664                worktree: wt_a.clone(),
21665                summary: String::new(),
21666                stat: String::new(),
21667                files: 0,
21668                commits: 0,
21669                empty: false,
21670                failed: None,
21671                verified_noop: None,
21672                duration_ms: 0,
21673                folded: false,
21674            },
21675            Candidate {
21676                index: 1,
21677                label: 'B',
21678                agent: "beta".to_owned(),
21679                branch: "magi/x/B".to_owned(),
21680                worktree: wt_b.clone(),
21681                summary: String::new(),
21682                stat: String::new(),
21683                files: 0,
21684                commits: 0,
21685                empty: false,
21686                failed: None,
21687                verified_noop: None,
21688                duration_ms: 0,
21689                folded: false,
21690            },
21691        ];
21692        state.tally = Some(Tally {
21693            first_choice: BTreeMap::from([('A', 1)]),
21694            borda: BTreeMap::new(),
21695            winner: 'A',
21696            rankings: 1,
21697            unanimous_initial: true,
21698            deliberated: false,
21699            changed_votes: 0,
21700            unanimous_final: true,
21701            tie_break: None,
21702            judges: 1,
21703            present: 1,
21704            quorum: 1,
21705            met_quorum: true,
21706            uncontested: None,
21707        });
21708        state.status = RunStatus::Ready;
21709
21710        state.save_under(&crate::run::home()).unwrap();
21711        fold_run(&mut state, false, &crate::run::home())
21712            .await
21713            .expect("fold_run");
21714
21715        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21716        assert!(
21717            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21718            "the unmerged winner's branch survives"
21719        );
21720        assert!(
21721            !state.candidates[0].folded,
21722            "the winner is not marked folded"
21723        );
21724
21725        assert!(!wt_b.exists(), "the loser's worktree is removed");
21726        assert!(
21727            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21728            "the loser's branch is removed"
21729        );
21730        assert!(state.candidates[1].folded, "the loser is marked folded");
21731    }
21732
21733    #[tokio::test]
21734    #[cfg(unix)]
21735    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21736        use std::os::fd::AsRawFd as _;
21737        use std::time::Duration;
21738
21739        let tmp = tempfile::tempdir().unwrap();
21740        let repo = tmp.path().join("repo");
21741        std::fs::create_dir_all(&repo).unwrap();
21742        init_repo(&repo);
21743        let common = repo.join(".git");
21744        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21745        let home = tmp.path().join("home");
21746        let mut config = Config::default();
21747        config.coordination = crate::config::test_coordination();
21748        config.graph.worktree_root = Some(tmp.path().join("wt"));
21749        config.graph.timeout_resource_wait = 1;
21750        let mut state = RunState::new(
21751            repo.clone(),
21752            "main".into(),
21753            "deadbeef".into(),
21754            "task".into(),
21755            config,
21756        );
21757        let root = state.worktree_root();
21758        let candidate = root.join("cand-A");
21759        let reviewer = root.join("review-1");
21760        let branch = state.branch_for('A');
21761        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21762            .await
21763            .unwrap();
21764        git::worktree_add_detached(&repo, &reviewer, "main")
21765            .await
21766            .unwrap();
21767        git::acquire_worktree_config(&repo).await.unwrap();
21768        state.enabled_worktree_config = true;
21769        state.status = RunStatus::Ready;
21770        state.candidates.push(Candidate {
21771            index: 0,
21772            label: 'A',
21773            agent: "implement".into(),
21774            branch: branch.clone(),
21775            worktree: candidate.clone(),
21776            summary: String::new(),
21777            stat: String::new(),
21778            files: 0,
21779            commits: 0,
21780            empty: false,
21781            failed: None,
21782            verified_noop: None,
21783            duration_ms: 0,
21784            folded: false,
21785        });
21786        state.save_under(&home).unwrap();
21787        let config_before = std::fs::read(common.join("config")).unwrap();
21788        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21789            .await
21790            .unwrap();
21791        // A separate OS handle bypasses the launcher's local gate, exactly as
21792        // an external updater does, and must still prevent all folding work.
21793        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21794        assert_eq!(
21795            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21796            0
21797        );
21798        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21799        assert!(
21800            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21801                .await
21802                .is_err()
21803        );
21804        assert!(candidate.exists());
21805        assert!(reviewer.exists());
21806        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21807        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21808        assert_eq!(
21809            git::git(&repo, &["worktree", "list", "--porcelain"])
21810                .await
21811                .unwrap(),
21812            worktrees_before
21813        );
21814        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21815            .await
21816            .unwrap()
21817            .unwrap_err();
21818        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
21819        drop(fold);
21820        assert!(candidate.exists() && reviewer.exists());
21821        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
21822        assert_eq!(
21823            state.resource_block.as_ref().unwrap().kind,
21824            "repository coordination"
21825        );
21826        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21827        drop(external);
21828        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21829        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
21830            .await
21831            .unwrap()
21832            .unwrap();
21833        drop(fold);
21834        assert!(removed.contains(&branch));
21835        assert!(!root.exists());
21836        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
21837        assert!(state.candidates[0].folded);
21838        assert!(!state.enabled_worktree_config);
21839        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
21840        let enabled = git::git_raw(
21841            &repo,
21842            &["config", "--local", "--get", "extensions.worktreeConfig"],
21843        )
21844        .await
21845        .unwrap();
21846        assert!(!enabled.ok(), "the last config reference was released");
21847    }
21848
21849    /// A handover holds repository coordination and then asks for the
21850    /// predecessor's owner lock; an automatic fold already holds that lock. The
21851    /// fold asks for coordination once and gives way, so the handover's short
21852    /// retry succeeds - waiting for it would leave both waiting for each other.
21853    /// Nothing is changed or saved on the way out and the refusal is `live`;
21854    /// the explicit entry points (`magi fold`) still wait, bounded as before.
21855    #[tokio::test]
21856    #[cfg(unix)]
21857    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
21858        use std::os::fd::AsRawFd as _;
21859        use std::time::Duration;
21860
21861        let tmp = tempfile::tempdir().unwrap();
21862        let repo = tmp.path().join("repo");
21863        std::fs::create_dir_all(&repo).unwrap();
21864        init_repo(&repo);
21865        let common = repo.join(".git");
21866        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21867        let home = tmp.path().join("home");
21868        let mut config = Config::default();
21869        config.coordination = crate::config::test_coordination();
21870        config.graph.worktree_root = Some(tmp.path().join("wt"));
21871        config.graph.timeout_resource_wait = 60;
21872        let mut state = RunState::new(
21873            repo.clone(),
21874            "main".into(),
21875            "deadbeef".into(),
21876            "task".into(),
21877            config,
21878        );
21879        let candidate = state.worktree_root().join("cand-A");
21880        let branch = state.branch_for('A');
21881        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21882            .await
21883            .unwrap();
21884        state.status = RunStatus::Ready;
21885        state.driver_exited = true;
21886        state.candidates.push(Candidate {
21887            index: 0,
21888            label: 'A',
21889            agent: "implement".into(),
21890            branch: branch.clone(),
21891            worktree: candidate.clone(),
21892            summary: String::new(),
21893            stat: String::new(),
21894            files: 0,
21895            commits: 0,
21896            empty: false,
21897            failed: None,
21898            verified_noop: None,
21899            duration_ms: 0,
21900            folded: false,
21901        });
21902        state.save_under(&home).unwrap();
21903        let id = state.id.clone();
21904        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
21905
21906        // A separate OS handle bypasses the launcher's local gate, exactly as
21907        // another process holding coordination does.
21908        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21909        assert_eq!(
21910            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21911            0
21912        );
21913        let error = tokio::time::timeout(
21914            Duration::from_secs(10),
21915            fold_run_when(&mut state, &home, &|_| Ok(true)),
21916        )
21917        .await
21918        .expect("the automatic fold does not wait out the 60 s resource wait")
21919        .unwrap_err();
21920        assert!(
21921            matches!(
21922                error.downcast_ref::<FoldRefusal>(),
21923                Some(FoldRefusal::Live(_))
21924            ),
21925            "{error:#}"
21926        );
21927        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
21928        // It gave way: both locks it held are free, nothing was removed and
21929        // nothing was saved (no resource block recorded on the record either).
21930        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
21931        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
21932        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
21933        assert_eq!(
21934            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
21935            record
21936        );
21937
21938        // The explicit entry point was asked for by a person and still waits.
21939        assert!(
21940            tokio::time::timeout(
21941                Duration::from_millis(300),
21942                fold_run(&mut state, true, &home)
21943            )
21944            .await
21945            .is_err(),
21946            "an explicit fold keeps waiting for coordination"
21947        );
21948        assert!(candidate.exists());
21949
21950        drop(external);
21951        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
21952            .await
21953            .unwrap();
21954        assert!(removed.contains(&branch));
21955        assert!(!candidate.exists());
21956    }
21957
21958    /// A branch handed to a later run is that run's (and its pull request's):
21959    /// folding the run that released it must not delete it.
21960    #[tokio::test]
21961    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
21962        let tmp = tempfile::tempdir().expect("tempdir");
21963        let repo = tmp.path().join("repo");
21964        std::fs::create_dir_all(&repo).unwrap();
21965        init_repo(&repo);
21966        let home = tmp.path().join("home");
21967
21968        let mut config = Config::default();
21969        config.graph.worktree_root = Some(tmp.path().join("wt"));
21970        let mut state = RunState::new(
21971            repo.clone(),
21972            "main".to_owned(),
21973            "deadbeef".to_owned(),
21974            "task".to_owned(),
21975            config,
21976        );
21977        // The worktree is already gone (released); the branch survives.
21978        git::git(&repo, &["branch", "magi/x/A", "main"])
21979            .await
21980            .expect("branch");
21981        state.candidates = vec![Candidate {
21982            index: 0,
21983            label: 'A',
21984            agent: "alpha".to_owned(),
21985            branch: "magi/x/A".to_owned(),
21986            worktree: state.worktree_root().join("cand-A"),
21987            summary: String::new(),
21988            stat: String::new(),
21989            files: 0,
21990            commits: 0,
21991            empty: false,
21992            failed: None,
21993            verified_noop: None,
21994            duration_ms: 0,
21995            folded: true,
21996        }];
21997        state.released_to = Some("20260901-000000-new1".to_owned());
21998        state.released_branches = vec!["magi/x/A".to_owned()];
21999
22000        state.save_under(&home).unwrap();
22001        fold_run(&mut state, true, &home).await.expect("fold_run");
22002        state.status = RunStatus::Merged;
22003        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22004        state.merge = Some(crate::run::MergeOutcome {
22005            mode: MergeMode::Pr,
22006            ok: true,
22007            detail: "confirmed merged".into(),
22008            empty: false,
22009        });
22010        state.save_under(&home).unwrap();
22011        fold_run(&mut state, true, &home)
22012            .await
22013            .expect("merged fold");
22014
22015        assert!(
22016            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22017            "the handed-over branch survives a fold"
22018        );
22019    }
22020
22021    /// A winner with nothing ahead of the base is caught before `gh` is ever
22022    /// asked for a pull request, and the message carries what the task's
22023    /// references resolved to.
22024    #[tokio::test]
22025    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22026        let tmp = tempfile::tempdir().expect("tempdir");
22027        let repo = tmp.path().join("repo");
22028        std::fs::create_dir_all(&repo).unwrap();
22029        init_repo(&repo);
22030        let run = |args: &[&str]| {
22031            let out = std::process::Command::new("git")
22032                .quiet()
22033                .args(args)
22034                .current_dir(&repo)
22035                .output()
22036                .expect("spawn git");
22037            assert!(out.status.success(), "git {args:?}");
22038        };
22039        run(&["branch", "magi/x/A"]);
22040        run(&["checkout", "-q", "-b", "magi/x/B"]);
22041        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22042        run(&["add", "-A"]);
22043        run(&["commit", "-q", "-m", "work"]);
22044        run(&["checkout", "-q", "main"]);
22045
22046        // A pull request is compared against the remote's base, so the
22047        // fixture needs one. Before it exists nothing can be read, and the
22048        // answer must be "not empty".
22049        let probe = RunState::new(
22050            repo.clone(),
22051            "main".to_owned(),
22052            "deadbeef".to_owned(),
22053            "task".to_owned(),
22054            Config::default(),
22055        );
22056        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22057        let bare = tmp.path().join("origin.git");
22058        let out = std::process::Command::new("git")
22059            .quiet()
22060            .args(["init", "-q", "--bare"])
22061            .arg(&bare)
22062            .output()
22063            .expect("spawn git");
22064        assert!(out.status.success(), "git init --bare");
22065        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22066        run(&["push", "-q", "origin", "main"]);
22067
22068        let mut state = RunState::new(
22069            repo.clone(),
22070            "main".to_owned(),
22071            "deadbeef".to_owned(),
22072            "task".to_owned(),
22073            Config::default(),
22074        );
22075        state.seeds = vec![refs::Seed {
22076            token: "magi/27b2/A".to_owned(),
22077            kind: refs::SeedKind::Unresolved,
22078            sha: String::new(),
22079            branch: true,
22080            detail: "no branch or commit named magi/27b2/A".to_owned(),
22081        }];
22082
22083        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22084        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22085        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22086        let detail = empty_candidate_detail(&state, "main");
22087        assert!(detail.starts_with("empty candidate"), "{detail}");
22088        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22089        assert!(detail.contains("--start-from"), "{detail}");
22090    }
22091
22092    /// `status == Ready` used to be read as "this is the harmless
22093    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22094    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22095    /// run's PR was closed without merging — and reentering `merge` with
22096    /// `mode` still `Pr` does not know the difference, so it pushed and
22097    /// opened a second pull request. `mode == Local` reproduces the same
22098    /// blind spot without a network call: reentry must not attempt another
22099    /// git merge once this node has already recorded an outcome.
22100    #[tokio::test]
22101    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22102        let tmp = tempfile::tempdir().expect("tempdir");
22103        let repo = tmp.path().join("repo");
22104        std::fs::create_dir_all(&repo).unwrap();
22105        init_repo(&repo);
22106
22107        let mut config = Config::default();
22108        config.merge.mode = MergeMode::Local;
22109
22110        let mut state = RunState::new(
22111            repo.clone(),
22112            "main".to_owned(),
22113            "deadbeef".to_owned(),
22114            "task".to_owned(),
22115            config,
22116        );
22117        state.candidates = vec![Candidate {
22118            index: 0,
22119            label: 'A',
22120            agent: "alpha".to_owned(),
22121            branch: "does-not-exist".to_owned(),
22122            worktree: repo.clone(),
22123            summary: String::new(),
22124            stat: String::new(),
22125            files: 0,
22126            commits: 0,
22127            empty: false,
22128            failed: None,
22129            verified_noop: None,
22130            duration_ms: 0,
22131            folded: false,
22132        }];
22133        state.tally = Some(Tally {
22134            first_choice: BTreeMap::from([('A', 1)]),
22135            borda: BTreeMap::new(),
22136            winner: 'A',
22137            rankings: 1,
22138            unanimous_initial: true,
22139            deliberated: false,
22140            changed_votes: 0,
22141            unanimous_final: true,
22142            tie_break: None,
22143            judges: 0,
22144            present: 0,
22145            quorum: 0,
22146            met_quorum: true,
22147            uncontested: Some("only candidate A produced a change".to_owned()),
22148        });
22149        state.reviews = vec![ReviewRound {
22150            round: 1,
22151            head: "deadbeef".to_owned(),
22152            verified_head: None,
22153            verified_at: None,
22154            reviews: Vec::new(),
22155            e2e: Vec::new(),
22156            fix: None,
22157            blocking: 0,
22158            answered: 0,
22159            expected: 0,
22160            clean: true,
22161            verify_retried: false,
22162            e2e_deferred: false,
22163            e2e_defer_reason: None,
22164            progressed: false,
22165            vote_split: false,
22166            reconsideration: Vec::new(),
22167            verdict: None,
22168        }];
22169        state.gate = vec![CommandOutcome {
22170            command: "test".to_owned(),
22171            code: Some(0),
22172            output_tail: String::new(),
22173            duration_ms: 0,
22174            resource_blocked: false,
22175            ..Default::default()
22176        }];
22177        state.gate_ran = true;
22178        // Reached its conclusion already — e.g. `land` closing the PR without
22179        // merging it, which (like the honest `MergeMode::None` path) leaves
22180        // `status` at `Ready`. The recorded outcome is what actually marks
22181        // this node done.
22182        state.status = RunStatus::Ready;
22183        state.merge = Some(MergeOutcome {
22184            mode: MergeMode::Local,
22185            ok: false,
22186            detail: "already concluded".to_owned(),
22187            empty: false,
22188        });
22189
22190        let mut runner = Runner {
22191            state,
22192            roles: ResolvedRoles {
22193                implementers: Vec::new(),
22194                judges: Vec::new(),
22195                reviewers: Vec::new(),
22196                fixer: None,
22197                conductor: conductor(),
22198                implementer_roster: Vec::new(),
22199                judge_roster: Vec::new(),
22200                reviewer_roster: Vec::new(),
22201            },
22202            sem: Arc::new(Semaphore::new(1)),
22203            pause: Pause::new(),
22204            interrupt: Pause::new(),
22205        };
22206
22207        runner.merge().await.expect("merge");
22208
22209        assert_eq!(
22210            runner.state.status,
22211            RunStatus::Ready,
22212            "a concluded run's status must not change on reentry"
22213        );
22214        assert_eq!(
22215            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22216            Some("already concluded"),
22217            "merge must not run again once the node already recorded an outcome"
22218        );
22219    }
22220
22221    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22222    /// when its last attempt was resource-blocked (the shared build cache
22223    /// could not be acquired or confirmed fresh in time - see
22224    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22225    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22226    /// a run merge a tree the gate never actually checked - exactly the case
22227    /// a contended cache produces on every retry until it clears. `merge`
22228    /// must refuse until `gate` has actually recorded an attempt.
22229    #[tokio::test]
22230    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22231        let tmp = tempfile::tempdir().expect("tempdir");
22232        let repo = tmp.path().join("repo");
22233        std::fs::create_dir_all(&repo).unwrap();
22234        init_repo(&repo);
22235
22236        let mut config = Config::default();
22237        config.merge.mode = MergeMode::Local;
22238
22239        let mut state = RunState::new(
22240            repo.clone(),
22241            "main".to_owned(),
22242            "deadbeef".to_owned(),
22243            "task".to_owned(),
22244            config,
22245        );
22246        state.candidates = vec![Candidate {
22247            index: 0,
22248            label: 'A',
22249            agent: "alpha".to_owned(),
22250            branch: "does-not-exist".to_owned(),
22251            worktree: repo.clone(),
22252            summary: String::new(),
22253            stat: String::new(),
22254            files: 0,
22255            commits: 0,
22256            empty: false,
22257            failed: None,
22258            verified_noop: None,
22259            duration_ms: 0,
22260            folded: false,
22261        }];
22262        state.tally = Some(Tally {
22263            first_choice: BTreeMap::from([('A', 1)]),
22264            borda: BTreeMap::new(),
22265            winner: 'A',
22266            rankings: 1,
22267            unanimous_initial: true,
22268            deliberated: false,
22269            changed_votes: 0,
22270            unanimous_final: true,
22271            tie_break: None,
22272            judges: 0,
22273            present: 0,
22274            quorum: 0,
22275            met_quorum: true,
22276            uncontested: Some("only candidate A produced a change".to_owned()),
22277        });
22278        state.reviews = vec![ReviewRound {
22279            round: 1,
22280            head: "deadbeef".to_owned(),
22281            verified_head: None,
22282            verified_at: None,
22283            reviews: Vec::new(),
22284            e2e: Vec::new(),
22285            fix: None,
22286            blocking: 0,
22287            answered: 0,
22288            expected: 0,
22289            clean: true,
22290            verify_retried: false,
22291            e2e_deferred: false,
22292            e2e_defer_reason: None,
22293            progressed: false,
22294            vote_split: false,
22295            reconsideration: Vec::new(),
22296            verdict: None,
22297        }];
22298        // The point: `gate` has not recorded anything yet.
22299        state.gate = Vec::new();
22300        state.gate_ran = false;
22301        state.status = RunStatus::Gating;
22302
22303        let mut runner = Runner {
22304            state,
22305            roles: ResolvedRoles {
22306                implementers: Vec::new(),
22307                judges: Vec::new(),
22308                reviewers: Vec::new(),
22309                fixer: None,
22310                conductor: conductor(),
22311                implementer_roster: Vec::new(),
22312                judge_roster: Vec::new(),
22313                reviewer_roster: Vec::new(),
22314            },
22315            sem: Arc::new(Semaphore::new(1)),
22316            pause: Pause::new(),
22317            interrupt: Pause::new(),
22318        };
22319
22320        runner.merge().await.expect("merge");
22321
22322        assert!(
22323            runner.state.merge.is_none(),
22324            "an empty gate must never be read as a passing one: {:?}",
22325            runner.state.merge
22326        );
22327    }
22328
22329    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22330    /// commands configured and `merge.mode` is `none` (a review-only run).
22331    /// `gate` must still record a real attempt — zero commands, vacuously
22332    /// passed — rather than leaving `state.gate` empty in a way `merge`
22333    /// cannot tell apart from "never ran"; otherwise the run reaches
22334    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22335    #[tokio::test]
22336    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22337        let tmp = tempfile::tempdir().expect("tempdir");
22338        let repo = tmp.path().join("repo");
22339        std::fs::create_dir_all(&repo).unwrap();
22340        init_repo(&repo);
22341
22342        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22343        let config = Config::default();
22344
22345        let mut state = RunState::new(
22346            repo.clone(),
22347            "main".to_owned(),
22348            "deadbeef".to_owned(),
22349            "task".to_owned(),
22350            config,
22351        );
22352        state.candidates = vec![Candidate {
22353            index: 0,
22354            label: 'A',
22355            agent: "alpha".to_owned(),
22356            branch: "does-not-exist".to_owned(),
22357            worktree: repo.clone(),
22358            summary: String::new(),
22359            stat: String::new(),
22360            files: 0,
22361            commits: 0,
22362            empty: false,
22363            failed: None,
22364            verified_noop: None,
22365            duration_ms: 0,
22366            folded: false,
22367        }];
22368        state.tally = Some(Tally {
22369            first_choice: BTreeMap::from([('A', 1)]),
22370            borda: BTreeMap::new(),
22371            winner: 'A',
22372            rankings: 1,
22373            unanimous_initial: true,
22374            deliberated: false,
22375            changed_votes: 0,
22376            unanimous_final: true,
22377            tie_break: None,
22378            judges: 0,
22379            present: 0,
22380            quorum: 0,
22381            met_quorum: true,
22382            uncontested: Some("only candidate A produced a change".to_owned()),
22383        });
22384        state.reviews = vec![ReviewRound {
22385            round: 1,
22386            head: "deadbeef".to_owned(),
22387            verified_head: None,
22388            verified_at: None,
22389            reviews: Vec::new(),
22390            e2e: Vec::new(),
22391            fix: None,
22392            blocking: 0,
22393            answered: 0,
22394            expected: 0,
22395            clean: true,
22396            verify_retried: false,
22397            e2e_deferred: false,
22398            e2e_defer_reason: None,
22399            progressed: false,
22400            vote_split: false,
22401            reconsideration: Vec::new(),
22402            verdict: None,
22403        }];
22404
22405        let mut runner = Runner {
22406            state,
22407            roles: ResolvedRoles {
22408                implementers: Vec::new(),
22409                judges: Vec::new(),
22410                reviewers: Vec::new(),
22411                fixer: None,
22412                conductor: conductor(),
22413                implementer_roster: Vec::new(),
22414                judge_roster: Vec::new(),
22415                reviewer_roster: Vec::new(),
22416            },
22417            sem: Arc::new(Semaphore::new(1)),
22418            pause: Pause::new(),
22419            interrupt: Pause::new(),
22420        };
22421
22422        runner.gate().await.expect("gate");
22423        assert!(
22424            runner.state.gate_ran,
22425            "zero configured commands is still a real attempt, not an unrun gate"
22426        );
22427        assert!(runner.state.gate.is_empty());
22428        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22429        assert_ne!(
22430            runner.state.status,
22431            RunStatus::Blocked,
22432            "a gate with nothing to check must not read as failed"
22433        );
22434
22435        runner.merge().await.expect("merge");
22436        assert_eq!(
22437            runner.state.status,
22438            RunStatus::Ready,
22439            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22440        );
22441    }
22442
22443    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22444    /// `verify.gate` (so the e2e leg and the final gate never build against
22445    /// different directories). With zero `verify.gate` commands but a
22446    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22447    /// that lease before discovering it had nothing to run - so a repo with
22448    /// no gate commands could come back `resource_blocked` (and therefore
22449    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22450    /// cache, exactly the contention this run's own zero commands could
22451    /// never have touched. `gate` must recognise there is nothing to check
22452    /// before it ever asks for the lease.
22453    #[tokio::test]
22454    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22455        crate::run::pin_test_home();
22456        let home = crate::run::home();
22457
22458        let tmp = tempfile::tempdir().expect("tempdir");
22459        let repo = tmp.path().join("repo");
22460        std::fs::create_dir_all(&repo).unwrap();
22461        init_repo(&repo);
22462        // Unique to this test, so holding its lease cannot collide with
22463        // another test sharing the same process-wide `home`.
22464        let cache_dir = tmp.path().join("target");
22465
22466        let mut config = Config::default();
22467        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22468        // `verify.gate` stays empty (the default). Any accidental cache
22469        // acquisition must report contention immediately, regardless of how
22470        // long unrelated Git subprocesses take under parallel test load.
22471        config.graph.timeout_verify = Some(2);
22472        config.graph.timeout_resource_wait = 0;
22473
22474        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22475        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22476            .expect("no io error acquiring directly")
22477        {
22478            crate::cache::AcquireOutcome::Acquired(g) => g,
22479            crate::cache::AcquireOutcome::Busy(b) => {
22480                panic!("expected the direct acquire to win the lease first: {b:?}")
22481            }
22482        };
22483
22484        let mut state = RunState::new(
22485            repo.clone(),
22486            "main".to_owned(),
22487            "deadbeef".to_owned(),
22488            "task".to_owned(),
22489            config,
22490        );
22491        state.candidates = vec![Candidate {
22492            index: 0,
22493            label: 'A',
22494            agent: "alpha".to_owned(),
22495            branch: "does-not-exist".to_owned(),
22496            worktree: repo.clone(),
22497            summary: String::new(),
22498            stat: String::new(),
22499            files: 0,
22500            commits: 0,
22501            empty: false,
22502            failed: None,
22503            verified_noop: None,
22504            duration_ms: 0,
22505            folded: false,
22506        }];
22507        state.tally = Some(Tally {
22508            first_choice: BTreeMap::from([('A', 1)]),
22509            borda: BTreeMap::new(),
22510            winner: 'A',
22511            rankings: 1,
22512            unanimous_initial: true,
22513            deliberated: false,
22514            changed_votes: 0,
22515            unanimous_final: true,
22516            tie_break: None,
22517            judges: 0,
22518            present: 0,
22519            quorum: 0,
22520            met_quorum: true,
22521            uncontested: Some("only candidate A produced a change".to_owned()),
22522        });
22523        state.reviews = vec![ReviewRound {
22524            round: 1,
22525            head: "deadbeef".to_owned(),
22526            verified_head: None,
22527            verified_at: None,
22528            reviews: Vec::new(),
22529            e2e: Vec::new(),
22530            fix: None,
22531            blocking: 0,
22532            answered: 0,
22533            expected: 0,
22534            clean: true,
22535            verify_retried: false,
22536            e2e_deferred: false,
22537            e2e_defer_reason: None,
22538            progressed: false,
22539            vote_split: false,
22540            reconsideration: Vec::new(),
22541            verdict: None,
22542        }];
22543
22544        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22545        state.reviews[0].e2e = vec![CommandOutcome {
22546            command: state.config.verify.e2e[0].clone(),
22547            code: Some(0),
22548            output_tail: String::new(),
22549            duration_ms: 0,
22550            resource_blocked: false,
22551            ..Default::default()
22552        }];
22553        let mut runner = Runner {
22554            state,
22555            roles: ResolvedRoles {
22556                implementers: Vec::new(),
22557                judges: Vec::new(),
22558                reviewers: Vec::new(),
22559                fixer: None,
22560                conductor: conductor(),
22561                implementer_roster: Vec::new(),
22562                judge_roster: Vec::new(),
22563                reviewer_roster: Vec::new(),
22564            },
22565            sem: Arc::new(Semaphore::new(1)),
22566            pause: Pause::new(),
22567            interrupt: Pause::new(),
22568        };
22569
22570        runner.gate().await.expect("gate");
22571        assert!(runner.state.resource_block.is_none());
22572        assert!(
22573            !runner
22574                .state
22575                .events
22576                .iter()
22577                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22578            "a gate with nothing to run must never request the held cache lease"
22579        );
22580        assert!(
22581            runner.state.gate_ran,
22582            "zero commands is still a real, immediate attempt"
22583        );
22584        assert!(runner.state.gate.is_empty());
22585        assert_ne!(
22586            runner.state.status,
22587            RunStatus::Blocked,
22588            "must not read as resource-blocked on a lease it never asked for"
22589        );
22590    }
22591
22592    /// A separate process carries a live worker's environment throughout all
22593    /// verification entry points; the parallel harness never changes its env.
22594    #[cfg(unix)]
22595    #[tokio::test]
22596    async fn verification_is_standalone_inside_a_live_worker() {
22597        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22598        if std::env::var_os(CHILD).is_none() {
22599            let home = tempfile::tempdir().unwrap();
22600            let generation = crate::worker::pin_current(home.path()).unwrap();
22601            let output = std::process::Command::new(std::env::current_exe().unwrap())
22602                .args([
22603                    "--exact",
22604                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22605                    "--nocapture",
22606                ])
22607                .env(CHILD, "1")
22608                .env("MAGI_HOME", home.path())
22609                .env("MAGI_WORKER_HOME", home.path())
22610                .env("MAGI_WORKER_ID", "abcdef")
22611                .env("MAGI_WORKER_GENERATION", &generation.id)
22612                .env("MAGI_WORKER_EXE", &generation.executable)
22613                .env("MAGI_RUN", "verification-parent")
22614                .env("MAGI_NODE", "gate")
22615                .env("MAGI_SEAT", "worker-fixture")
22616                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22617                .env("MAGI_NO_AUTOUPDATE", "0")
22618                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22619                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22620                .env(
22621                    "VERIFY_EXPECT_TOOLCHAIN",
22622                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22623                )
22624                .env(
22625                    "VERIFY_EXPECT_CACHE",
22626                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22627                )
22628                .output()
22629                .unwrap();
22630            assert!(
22631                output.status.success()
22632                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22633                "{}\n{}",
22634                String::from_utf8_lossy(&output.stdout),
22635                String::from_utf8_lossy(&output.stderr)
22636            );
22637            return;
22638        }
22639        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22640        let home = crate::run::home();
22641        let directory = home.join("workers/jobs/abcdef");
22642        std::fs::create_dir_all(&directory).unwrap();
22643        let job = crate::worker::Job {
22644            id: "abcdef".into(),
22645            sequence: 1,
22646            kind: "task".into(),
22647            key: "task:verification".into(),
22648            payload: serde_json::json!({}),
22649            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22650            version: Some(env!("CARGO_PKG_VERSION").into()),
22651            status: crate::worker::Status::Running,
22652            result: None,
22653            pid: Some(std::process::id()),
22654            created_at: 0,
22655            finished_at: None,
22656        };
22657        std::fs::write(
22658            directory.join("job.json"),
22659            serde_json::to_vec(&job).unwrap(),
22660        )
22661        .unwrap();
22662        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22663        let assert_worker = || {
22664            assert_eq!(
22665                crate::worker::current_job(&home).unwrap().unwrap().id,
22666                job.id
22667            );
22668            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22669            assert_eq!(
22670                crate::worker::helper_executable(&home).unwrap(),
22671                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22672            );
22673            assert!(
22674                crate::updater::Checker::new(&crate::config::Update {
22675                    mode: crate::config::UpdateMode::Notify,
22676                    interval: None,
22677                    auto_restart: false,
22678                })
22679                .is_none(),
22680                "the driver remains pinned, even while tests are standalone"
22681            );
22682        };
22683        assert_worker();
22684        let repo = home.join("repo");
22685        std::fs::create_dir_all(&repo).unwrap();
22686        init_repo(&repo);
22687        // Keep storage, seat/control context, containment and tool lookup.
22688        // No inherited values (or credentials) are printed on success.
22689        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22690            test -z "${MAGI_WORKER_GENERATION+x}" &&
22691            test -z "${MAGI_WORKER_HOME+x}" &&
22692            test -z "${MAGI_WORKER_EXE+x}" &&
22693            test "$MAGI_HOME/repo" -ef . &&
22694            test "$MAGI_RUN" = verification-parent &&
22695            test "$MAGI_NODE" = gate &&
22696            test "$MAGI_SEAT" = worker-fixture &&
22697            test -n "$MAGI_PROCESS_OWNER" &&
22698            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22699            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22700            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22701            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22702        // Negative control: an ordinary child inherits the contamination.
22703        assert!(
22704            !std::process::Command::new("sh")
22705                .args(["-c", probe])
22706                .current_dir(&repo)
22707                .status()
22708                .unwrap()
22709                .success()
22710        );
22711        let unrelated_home = tempfile::tempdir().unwrap();
22712        assert!(
22713            crate::worker::current_job(unrelated_home.path()).is_err(),
22714            "an inherited worker id cannot be resolved in a unit fixture's home"
22715        );
22716        let mut runner = runner_at(RunStatus::Gating);
22717        runner.state.repo = repo.clone();
22718        runner.state.config.disk.min_free_bytes = 0;
22719        runner.state.config.coordination = crate::config::test_coordination();
22720        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22721        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22722        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22723        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22724        let winner = Candidate {
22725            index: 0,
22726            label: 'A',
22727            agent: "fixture".into(),
22728            branch: "main".into(),
22729            worktree: repo.clone(),
22730            summary: String::new(),
22731            stat: String::new(),
22732            files: 0,
22733            commits: 0,
22734            empty: false,
22735            failed: None,
22736            verified_noop: None,
22737            duration_ms: 0,
22738            folded: false,
22739        };
22740        let (e2e, retried, pids) = run_e2e_with_retry(
22741            &mut runner.state,
22742            &["sh".into(), "-c".into()],
22743            &[format!("{probe} && printf initial")],
22744            &repo,
22745            Duration::from_secs(10),
22746            "initial",
22747            None,
22748        )
22749        .await;
22750        assert!(!retried && pids.is_empty());
22751        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22752        assert_eq!(e2e[0].output_tail, "initial");
22753        let gate = runner.run_gate(&winner).await.unwrap();
22754        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22755        // An interrupted repair must recheck e2e from saved state. Landing
22756        // reuses that state and must run both pre-gate and gate again.
22757        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22758            git::rev_parse(&repo, "HEAD").await.unwrap(),
22759            false,
22760            Vec::new(),
22761        ));
22762        runner.state.save().unwrap();
22763        let mut resumed = RunState::load(&runner.state.id).unwrap();
22764        let wait = crate::repo_lock::WaitPolicy::default();
22765        assert!(matches!(
22766            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22767                .await
22768                .unwrap(),
22769            GateFix::Retry
22770        ));
22771        let saved = RunState::load(&resumed.id).unwrap();
22772        let repair = saved.gate_repair_e2e.unwrap();
22773        assert!(repair.passed);
22774        assert_eq!(repair.outcomes.len(), 1);
22775        assert!(repair.outcomes[0].ok());
22776        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22777            .await
22778            .unwrap();
22779        assert_eq!(landing.len(), 1);
22780        assert!(landing[0].ok(), "{landing:?}");
22781        assert_eq!(
22782            std::fs::read_to_string(repo.join("phases")).unwrap(),
22783            "pre\ngate\ne2e\npre\ngate\n"
22784        );
22785        assert_worker();
22786    }
22787
22788    #[cfg(unix)]
22789    #[tokio::test]
22790    async fn verification_keeps_the_panic_and_the_full_output() {
22791        crate::run::pin_test_home();
22792        let tmp = tempfile::tempdir().unwrap();
22793        let mut config = Config::default();
22794        config.disk.min_free_bytes = 0;
22795        let mut state = RunState::new(
22796            tmp.path().to_owned(),
22797            "main".into(),
22798            "base".into(),
22799            "verification evidence".into(),
22800            config,
22801        );
22802        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22803                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22804                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22805        let mut names = Vec::new();
22806        for _ in 0..2 {
22807            let (outcomes, _) = run_commands(
22808                &mut state,
22809                "gate",
22810                "gate",
22811                0,
22812                &["sh".into(), "-c".into()],
22813                &[script.into()],
22814                tmp.path(),
22815                Duration::from_secs(60),
22816            )
22817            .await;
22818            let tail = &outcomes[0].output_tail;
22819            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
22820            assert!(tail.contains("boom assertion"));
22821            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
22822            let line = tail.lines().next().unwrap();
22823            names.push(line.to_owned());
22824        }
22825        assert_ne!(names[0], names[1], "the second run must not overwrite");
22826        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
22827        assert!(full.len() > 500_000 && full.contains("boom assertion"));
22828        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
22829
22830        // Storage failures are evidence too; preserve the command's verdict.
22831        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
22832        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
22833        let (outcomes, _) = run_commands(
22834            &mut state,
22835            "gate",
22836            "gate",
22837            0,
22838            &["sh".into(), "-c".into()],
22839            &["echo failure-output; exit 7".into()],
22840            tmp.path(),
22841            Duration::from_secs(10),
22842        )
22843        .await;
22844        assert_eq!(outcomes[0].code, Some(7));
22845        assert!(state.events.iter().any(|e| {
22846            e.node == "gate" && e.message.contains("could not save the full gate output:")
22847        }));
22848    }
22849
22850    #[cfg(unix)]
22851    #[tokio::test]
22852    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
22853        crate::run::pin_test_home();
22854        let tmp = tempfile::tempdir().unwrap();
22855        let mut config = Config::default();
22856        config.disk.min_free_bytes = 0;
22857        let mut state = RunState::new(
22858            tmp.path().to_owned(),
22859            "main".into(),
22860            "base".into(),
22861            "verification evidence".into(),
22862            config,
22863        );
22864        let (outcomes, pids) = run_commands(
22865            &mut state,
22866            "gate",
22867            "gate",
22868            1,
22869            &["sh".into(), "-c".into()],
22870            &[
22871                "printf before-timeout; exec sleep 30".into(),
22872                "kill -TERM $$".into(),
22873                "exit 7".into(),
22874                "printf success".into(),
22875            ],
22876            tmp.path(),
22877            Duration::from_secs(1),
22878        )
22879        .await;
22880        wait_for_timed_out_children_to_die(&pids).await;
22881        assert_eq!(
22882            pids.len(),
22883            1,
22884            "unleased timeout retains its death-check PID"
22885        );
22886        assert_eq!(outcomes.len(), 4);
22887        assert_eq!(outcomes[0].code, None);
22888        assert!(outcomes[0].output_tail.contains("before-timeout"));
22889        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
22890        assert_eq!(outcomes[1].code, None);
22891        assert!(outcomes[1].output_tail.contains("command terminated:"));
22892        assert!(!outcomes[1].output_tail.contains("timed out"));
22893        assert_eq!(outcomes[2].code, Some(7));
22894        assert!(!outcomes[2].output_tail.contains("timed out"));
22895        assert_eq!(outcomes[3].code, Some(0));
22896        assert_eq!(outcomes[3].output_tail, "success");
22897        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
22898    }
22899
22900    /// The addendum's second gap: a `verify.gate` command running for real
22901    /// wall-clock time had nothing at all to show for it in `active` before
22902    /// `run_commands` learned to record it — a run could sit in `Gating` for
22903    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
22904    /// what was actually happening. Proven with a genuinely still-running
22905    /// command, not just a before/after check on the final state: a poller
22906    /// task reads the same `run.json` `gate()` is writing, the same way the
22907    /// phone or `magi show` would, while the shell command is still blocked
22908    /// on its own release marker.
22909    #[tokio::test]
22910    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
22911        crate::run::pin_test_home();
22912
22913        let tmp = tempfile::tempdir().expect("tempdir");
22914        let repo = tmp.path().join("repo");
22915        std::fs::create_dir_all(&repo).unwrap();
22916        init_repo(&repo);
22917
22918        let mut config = Config::default();
22919        config.disk.min_free_bytes = 0;
22920        config.verify.gate = vec![
22921            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
22922             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
22923                .to_owned(),
22924        ];
22925
22926        let mut state = RunState::new(
22927            repo.clone(),
22928            "main".to_owned(),
22929            "deadbeef".to_owned(),
22930            "task".to_owned(),
22931            config,
22932        );
22933        let run_id = state.id.clone();
22934        state.candidates = vec![Candidate {
22935            index: 0,
22936            label: 'A',
22937            agent: "alpha".to_owned(),
22938            branch: "does-not-exist".to_owned(),
22939            worktree: repo.clone(),
22940            summary: String::new(),
22941            stat: String::new(),
22942            files: 0,
22943            commits: 0,
22944            empty: false,
22945            failed: None,
22946            verified_noop: None,
22947            duration_ms: 0,
22948            folded: false,
22949        }];
22950        state.tally = Some(Tally {
22951            first_choice: BTreeMap::from([('A', 1)]),
22952            borda: BTreeMap::new(),
22953            winner: 'A',
22954            rankings: 1,
22955            unanimous_initial: true,
22956            deliberated: false,
22957            changed_votes: 0,
22958            unanimous_final: true,
22959            tie_break: None,
22960            judges: 0,
22961            present: 0,
22962            quorum: 0,
22963            met_quorum: true,
22964            uncontested: Some("only candidate A produced a change".to_owned()),
22965        });
22966        state.reviews = vec![ReviewRound {
22967            round: 1,
22968            head: "deadbeef".to_owned(),
22969            verified_head: None,
22970            verified_at: None,
22971            reviews: Vec::new(),
22972            e2e: Vec::new(),
22973            fix: None,
22974            blocking: 0,
22975            answered: 0,
22976            expected: 0,
22977            clean: true,
22978            verify_retried: false,
22979            e2e_deferred: false,
22980            e2e_defer_reason: None,
22981            progressed: false,
22982            vote_split: false,
22983            reconsideration: Vec::new(),
22984            verdict: None,
22985        }];
22986
22987        let mut runner = Runner {
22988            state,
22989            roles: ResolvedRoles {
22990                implementers: Vec::new(),
22991                judges: Vec::new(),
22992                reviewers: Vec::new(),
22993                fixer: None,
22994                conductor: conductor(),
22995                implementer_roster: Vec::new(),
22996                judge_roster: Vec::new(),
22997                reviewer_roster: Vec::new(),
22998            },
22999            sem: Arc::new(Semaphore::new(1)),
23000            pause: Pause::new(),
23001            interrupt: Pause::new(),
23002        };
23003
23004        let started_marker = repo.join("started.marker");
23005        let release_marker = repo.join("release.marker");
23006        let observe = async {
23007            loop {
23008                if started_marker.exists()
23009                    && let Ok(s) = crate::run::RunState::load(&run_id)
23010                    && let Some(a) = s.active.get("gate")
23011                {
23012                    std::fs::write(&release_marker, b"go").expect("release marker");
23013                    break a.clone();
23014                }
23015                tokio::time::sleep(Duration::from_millis(50)).await;
23016            }
23017        };
23018        let captured = {
23019            let gate = runner.gate();
23020            tokio::pin!(gate);
23021            let captured = tokio::select! {
23022                observed = observe => observed,
23023                result = &mut gate => panic!(
23024                    "gate exited before its in-flight entry was observed: {result:?}"
23025                ),
23026            };
23027            gate.await.expect("gate");
23028            captured
23029        };
23030
23031        assert_eq!(captured.task.as_deref(), Some("gate"));
23032        assert_eq!(captured.node, "gate");
23033        assert_eq!(captured.index, Some(1));
23034        assert_eq!(captured.total, Some(1));
23035        assert!(
23036            captured
23037                .command
23038                .as_deref()
23039                .is_some_and(|c| c.contains("started.marker")),
23040            "{captured:?}"
23041        );
23042
23043        assert!(
23044            runner.state.active.is_empty(),
23045            "the entry must be cleared once the command actually finished: {:?}",
23046            runner.state.active
23047        );
23048        assert!(runner.state.gate_ran);
23049        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23050    }
23051
23052    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23053    /// record for `land`; one with only a Minor, or no reject, leaves none.
23054    #[tokio::test]
23055    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23056        use crate::verdict::{Finding, ReviewVote, Severity};
23057        crate::run::pin_test_home();
23058        let tmp = tempfile::tempdir().expect("tempdir");
23059        let repo = tmp.path().join("repo");
23060        std::fs::create_dir_all(&repo).unwrap();
23061        init_repo(&repo);
23062
23063        for (severity, vote, expect) in [
23064            (Severity::Major, ReviewVote::Reject, true),
23065            (Severity::Minor, ReviewVote::Reject, false),
23066            (Severity::Major, ReviewVote::Approve, false),
23067        ] {
23068            let mut round = review_round(false, 1, 1, 1, false, true);
23069            round.reviews = vec![ReviewRecord {
23070                reviewer: 1,
23071                agent: "alpha".to_owned(),
23072                summary: String::new(),
23073                findings: vec![Finding {
23074                    id: "R1-1-1".to_owned(),
23075                    severity,
23076                    file: None,
23077                    line: None,
23078                    title: "t".to_owned(),
23079                    detail: String::new(),
23080                }],
23081                vote: Some(vote),
23082                failed: None,
23083                duration_ms: 0,
23084                attempts: 0,
23085            }];
23086            let mut state = RunState::new(
23087                repo.clone(),
23088                "main".to_owned(),
23089                "deadbeef".to_owned(),
23090                "task".to_owned(),
23091                Config::default(),
23092            );
23093            state.reviews = vec![round];
23094            let mut runner = Runner {
23095                state,
23096                roles: ResolvedRoles {
23097                    implementers: Vec::new(),
23098                    judges: Vec::new(),
23099                    reviewers: Vec::new(),
23100                    fixer: None,
23101                    conductor: conductor(),
23102                    implementer_roster: Vec::new(),
23103                    judge_roster: Vec::new(),
23104                    reviewer_roster: Vec::new(),
23105                },
23106                sem: Arc::new(Semaphore::new(1)),
23107                pause: Pause::new(),
23108                interrupt: Pause::new(),
23109            };
23110            let shell = runner.state.config.shell();
23111            runner
23112                .stop_reviewing("round budget spent", &shell, &repo)
23113                .await
23114                .expect("stop_reviewing");
23115            assert_eq!(runner.state.status, RunStatus::Gating);
23116            assert_eq!(
23117                runner.state.contested_handoff.is_some(),
23118                expect,
23119                "{severity:?} + {vote:?}"
23120            );
23121        }
23122    }
23123
23124    /// The shape the incident this whole fix responds to actually had: the
23125    /// round budget spent, the last round's own e2e blocked on the shared
23126    /// build cache (held here by a live pid — this test process — exactly
23127    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23128    /// without forking a process). `stop_reviewing` must retry it — not
23129    /// silently leave the round looking untouched (the catch-up-only half of
23130    /// the bug), and not read the contention as a red `e2e` and block the
23131    /// run on it (the other half). Called directly, the same way
23132    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23133    /// above exercises `gate`, so this never needs a real cargo build to
23134    /// reach: the lease is never released, so `with_cache_lease` never gets
23135    /// past acquiring it into anything that would need a real workspace.
23136    #[tokio::test]
23137    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23138        crate::run::pin_test_home();
23139        let home = crate::run::home();
23140
23141        let tmp = tempfile::tempdir().expect("tempdir");
23142        let repo = tmp.path().join("repo");
23143        std::fs::create_dir_all(&repo).unwrap();
23144        init_repo(&repo);
23145        let head = crate::git::rev_parse(&repo, "HEAD")
23146            .await
23147            .expect("rev-parse");
23148        // Unique to this test, so holding its lease cannot collide with
23149        // another test sharing the same process-wide `home`.
23150        let cache_dir = tmp.path().join("target");
23151
23152        let mut config = Config::default();
23153        config.verify.e2e = vec![format!(
23154            "CARGO_TARGET_DIR='{}' test -f README.md",
23155            cache_dir.display()
23156        )];
23157        config.graph.review_rounds = 1;
23158        // Bounded so a regression that does start waiting fails the test in
23159        // seconds, not hangs it.
23160        config.graph.timeout_verify = Some(2);
23161        config.graph.timeout_resource_wait = 2;
23162
23163        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23164        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23165            .expect("no io error acquiring directly")
23166        {
23167            crate::cache::AcquireOutcome::Acquired(g) => g,
23168            crate::cache::AcquireOutcome::Busy(b) => {
23169                panic!("expected the direct acquire to win the lease first: {b:?}")
23170            }
23171        };
23172
23173        let mut state = RunState::new(
23174            repo.clone(),
23175            "main".to_owned(),
23176            head.clone(),
23177            "task".to_owned(),
23178            config,
23179        );
23180        state.candidates = vec![Candidate {
23181            index: 0,
23182            label: 'A',
23183            agent: "alpha".to_owned(),
23184            branch: "does-not-exist".to_owned(),
23185            worktree: repo.clone(),
23186            summary: String::new(),
23187            stat: String::new(),
23188            files: 0,
23189            commits: 0,
23190            empty: false,
23191            failed: None,
23192            verified_noop: None,
23193            duration_ms: 0,
23194            folded: false,
23195        }];
23196        state.tally = Some(Tally {
23197            first_choice: BTreeMap::from([('A', 1)]),
23198            borda: BTreeMap::new(),
23199            winner: 'A',
23200            rankings: 1,
23201            unanimous_initial: true,
23202            deliberated: false,
23203            changed_votes: 0,
23204            unanimous_final: true,
23205            tie_break: None,
23206            judges: 0,
23207            present: 0,
23208            quorum: 0,
23209            met_quorum: true,
23210            uncontested: Some("only candidate A produced a change".to_owned()),
23211        });
23212        // The round budget's last round, deferred: `needs_catchup_run`'s
23213        // other trigger. `stop_reviewing`'s retry machinery must treat this
23214        // exactly like a resource-blocked attempt once it actually runs.
23215        state.reviews = vec![ReviewRound {
23216            round: 1,
23217            head: head.clone(),
23218            verified_head: None,
23219            verified_at: None,
23220            reviews: Vec::new(),
23221            e2e: Vec::new(),
23222            fix: None,
23223            blocking: 1,
23224            answered: 1,
23225            expected: 1,
23226            clean: false,
23227            verify_retried: false,
23228            e2e_deferred: true,
23229            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23230            progressed: false,
23231            vote_split: false,
23232            reconsideration: Vec::new(),
23233            verdict: None,
23234        }];
23235
23236        let mut runner = Runner {
23237            state,
23238            roles: ResolvedRoles {
23239                implementers: Vec::new(),
23240                judges: Vec::new(),
23241                reviewers: Vec::new(),
23242                fixer: None,
23243                conductor: conductor(),
23244                implementer_roster: Vec::new(),
23245                judge_roster: Vec::new(),
23246                reviewer_roster: Vec::new(),
23247            },
23248            sem: Arc::new(Semaphore::new(1)),
23249            pause: Pause::new(),
23250            interrupt: Pause::new(),
23251        };
23252
23253        let shell = runner.state.config.shell();
23254        runner
23255            .stop_reviewing("round budget spent", &shell, &repo)
23256            .await
23257            .expect("stop_reviewing");
23258
23259        let last = runner.state.reviews.last().expect("round record");
23260        assert_eq!(
23261            last.e2e_status(),
23262            E2eStatus::ResourceBlocked,
23263            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23264             failed: {last:?}"
23265        );
23266        assert_eq!(
23267            last.verified_head.as_deref(),
23268            Some(head.as_str()),
23269            "which commit this attempt targeted is known even though nothing finished checking \
23270             it"
23271        );
23272        let first_attempt_at = last
23273            .verified_at
23274            .expect("when this attempt ran is known too");
23275        assert_ne!(
23276            runner.state.status,
23277            RunStatus::Blocked,
23278            "contention is evidence about the machine, not the patch — it must not settle the \
23279             run as blocked: {:?}",
23280            runner.state.status
23281        );
23282        assert!(
23283            !runner
23284                .state
23285                .events
23286                .iter()
23287                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23288            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23289            runner.state.events
23290        );
23291
23292        // The cache is still held: a later reentry must retry the same
23293        // round's verification again — not leave it looking exactly as
23294        // untouched as the first blocked attempt, which is indistinguishable
23295        // from never having tried again at all.
23296        runner
23297            .stop_reviewing("round budget spent", &shell, &repo)
23298            .await
23299            .expect("stop_reviewing retry");
23300        assert_eq!(
23301            runner.state.reviews.len(),
23302            1,
23303            "no new round was started: {:?}",
23304            runner.state.reviews
23305        );
23306        let last = runner.state.reviews.last().expect("round record");
23307        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23308        assert!(
23309            last.verified_at.expect("still known") > first_attempt_at,
23310            "a second reentry must be a fresh attempt, not a stale copy of the first"
23311        );
23312        assert_ne!(runner.state.status, RunStatus::Blocked);
23313
23314        held.release();
23315    }
23316
23317    #[cfg(unix)]
23318    #[tokio::test]
23319    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23320        ask_test_home();
23321        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23322            let tmp = tempfile::tempdir().unwrap();
23323            let repo = tmp.path().join("repo");
23324            std::fs::create_dir(&repo).unwrap();
23325            init_repo(&repo);
23326            let run_git = |args: &[&str]| {
23327                let out = std::process::Command::new("git")
23328                    .args(args)
23329                    .current_dir(&repo)
23330                    .output()
23331                    .unwrap();
23332                assert!(
23333                    out.status.success(),
23334                    "{args:?}: {}",
23335                    String::from_utf8_lossy(&out.stderr)
23336                );
23337            };
23338            let origin = tmp.path().join("origin.git");
23339            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23340            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23341            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23342            run_git(&["add", "spec.rs"]);
23343            run_git(&["commit", "-m", "initial spec"]);
23344            run_git(&["push", "origin", "main"]);
23345            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23346            run_git(&["checkout", "-b", "fix/review"]);
23347            std::fs::write(
23348                repo.join("check.rs"),
23349                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23350            )
23351            .unwrap();
23352            run_git(&["add", "check.rs"]);
23353            run_git(&["commit", "-m", "use spec"]);
23354            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23355            run_git(&["checkout", "main"]);
23356            std::fs::write(
23357                repo.join("spec.rs"),
23358                "struct AgentSpec { max_turn_secs: u64 }\n",
23359            )
23360            .unwrap();
23361            run_git(&["add", "spec.rs"]);
23362            run_git(&["commit", "-m", "extend spec"]);
23363            run_git(&["push", "origin", "main"]);
23364            run_git(&["checkout", "fix/review"]);
23365
23366            let mut runner = runner_at(RunStatus::Reviewing);
23367            runner.state.repo = repo.clone();
23368            runner.state.base_commit = base;
23369            runner.state.pr_head = Some("fix/review".into());
23370            runner.state.config.graph.review_rounds = max_rounds;
23371            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23372            runner.state.config.graph.sessions = false;
23373            runner.state.config.disk.min_free_bytes = 0;
23374            runner.state.config.verify.e2e =
23375                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23376            runner.state.candidates = vec![Candidate {
23377                index: 0,
23378                label: 'A',
23379                agent: "fixture".into(),
23380                branch: "fix/review".into(),
23381                worktree: repo.clone(),
23382                summary: String::new(),
23383                stat: String::new(),
23384                files: 1,
23385                commits: 1,
23386                empty: false,
23387                failed: None,
23388                verified_noop: None,
23389                duration_ms: 0,
23390                folded: false,
23391            }];
23392            runner.state.tally = Some(Tally {
23393                first_choice: BTreeMap::new(),
23394                borda: BTreeMap::new(),
23395                winner: 'A',
23396                rankings: 0,
23397                unanimous_initial: true,
23398                deliberated: false,
23399                changed_votes: 0,
23400                unanimous_final: true,
23401                tie_break: None,
23402                judges: 0,
23403                present: 0,
23404                quorum: 0,
23405                met_quorum: true,
23406                uncontested: Some("review-only".into()),
23407            });
23408            let mut last = review_round(false, 0, 1, 1, false, false);
23409            last.head = reviewed.clone();
23410            last.e2e_deferred = true;
23411            last.e2e[0].resource_blocked = true;
23412            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23413            if max_rounds == 1 {
23414                last.e2e.clear();
23415            }
23416            runner.state.reviews = vec![last];
23417            let calls = tmp.path().join("fix-calls");
23418            let mut fixer = spec("repair");
23419            fixer
23420                .env
23421                .insert("FIX_CALLS".into(), calls.display().to_string());
23422            fixer.command = vec!["sh".into(), "-c".into(), r#"
23423                echo fix >> "$FIX_CALLS"
23424                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23425                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23426                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23427                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23428            "#.into()];
23429            let mut reviewer = spec("reviewer");
23430            reviewer.command = vec![
23431                "sh".into(),
23432                "-c".into(),
23433                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23434                    .into(),
23435            ];
23436            runner.roles.fixer = Some(vec![fixer]);
23437            runner.roles.reviewers = vec![reviewer];
23438
23439            runner.sync_to_base().await.unwrap();
23440            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23441            assert_ne!(rebased, reviewed);
23442            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23443            if reentry {
23444                // Simulate a crash after catch-up evidence was saved but before
23445                // dispatching the fixer. No dedicated pending-repair field exists.
23446                let shell = runner.state.config.shell();
23447                runner
23448                    .stop_unresolved_review("deferred verification", &shell, &repo)
23449                    .await
23450                    .unwrap();
23451                assert!(runner.catchup_repairable());
23452                assert!(!calls.exists());
23453                runner.state = RunState::load(&runner.state.id).unwrap();
23454                assert!(runner.catchup_repairable());
23455            }
23456            runner.review_loop().await.unwrap();
23457            let first = &runner.state.reviews[0];
23458            assert_eq!(first.head, reviewed);
23459            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23460            assert!(
23461                first.verify_retried,
23462                "a reproduced build failure gets exactly one retry: {:?}",
23463                first.e2e
23464            );
23465            assert!(first.e2e[0].output_tail.contains("E0063"));
23466            assert!(!runner.catchup_repairable());
23467            if max_rounds == 2 {
23468                assert_eq!(
23469                    runner.state.status,
23470                    RunStatus::Gating,
23471                    "{}",
23472                    crate::report::run(&runner.state)
23473                );
23474                assert_eq!(runner.state.reviews.len(), 2);
23475                assert!(first.fix.as_ref().unwrap().committed);
23476                assert!(runner.state.reviews[1].clean);
23477                assert_eq!(
23478                    runner
23479                        .state
23480                        .reviews
23481                        .iter()
23482                        .filter(|r| r.fix.is_some())
23483                        .count(),
23484                    1
23485                );
23486                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23487                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23488            } else {
23489                assert_eq!(runner.state.status, RunStatus::Blocked);
23490                assert!(first.fix.is_none());
23491                assert!(!calls.exists());
23492                let recovery = crate::recovery::assess(
23493                    "prior",
23494                    Some(&runner.state),
23495                    &runner.landing_base(),
23496                    crate::recovery::Relation::Diverged,
23497                );
23498                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23499                let reasons = recovery.reasons.join("\n");
23500                assert!(
23501                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23502                    "{reasons}"
23503                );
23504                assert!(
23505                    reasons.contains("base sync to")
23506                        && reasons.contains("additional review is required"),
23507                    "{reasons}"
23508                );
23509            }
23510        }
23511    }
23512
23513    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23514    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23515    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23516    /// own top-of-function fast path (`review_conclusion`) correctly reads
23517    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23518    /// own `for` range is empty once the round budget is spent, so
23519    /// `review_loop` must retry the check itself rather than silently doing
23520    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23521    /// above exercises directly, but through `review_loop`'s own entry point
23522    /// this time, proving the wiring between the two rather than just the
23523    /// retry logic in isolation.
23524    #[tokio::test]
23525    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23526        crate::run::pin_test_home();
23527        let home = crate::run::home();
23528
23529        let tmp = tempfile::tempdir().expect("tempdir");
23530        let repo = tmp.path().join("repo");
23531        std::fs::create_dir_all(&repo).unwrap();
23532        init_repo(&repo);
23533        let head = crate::git::rev_parse(&repo, "HEAD")
23534            .await
23535            .expect("rev-parse");
23536        let cache_dir = tmp.path().join("target");
23537
23538        let mut config = Config::default();
23539        config.verify.e2e = vec![format!(
23540            "CARGO_TARGET_DIR='{}' test -f README.md",
23541            cache_dir.display()
23542        )];
23543        config.graph.review_rounds = 1;
23544        config.graph.timeout_verify = Some(2);
23545        config.graph.timeout_resource_wait = 2;
23546
23547        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23548        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23549            .expect("no io error acquiring directly")
23550        {
23551            crate::cache::AcquireOutcome::Acquired(g) => g,
23552            crate::cache::AcquireOutcome::Busy(b) => {
23553                panic!("expected the direct acquire to win the lease first: {b:?}")
23554            }
23555        };
23556
23557        let mut state = RunState::new(
23558            repo.clone(),
23559            "main".to_owned(),
23560            head.clone(),
23561            "task".to_owned(),
23562            config,
23563        );
23564        state.candidates = vec![Candidate {
23565            index: 0,
23566            label: 'A',
23567            agent: "alpha".to_owned(),
23568            branch: "does-not-exist".to_owned(),
23569            worktree: repo.clone(),
23570            summary: String::new(),
23571            stat: String::new(),
23572            files: 0,
23573            commits: 0,
23574            empty: false,
23575            failed: None,
23576            verified_noop: None,
23577            duration_ms: 0,
23578            folded: false,
23579        }];
23580        state.tally = Some(Tally {
23581            first_choice: BTreeMap::from([('A', 1)]),
23582            borda: BTreeMap::new(),
23583            winner: 'A',
23584            rankings: 1,
23585            unanimous_initial: true,
23586            deliberated: false,
23587            changed_votes: 0,
23588            unanimous_final: true,
23589            tie_break: None,
23590            judges: 0,
23591            present: 0,
23592            quorum: 0,
23593            met_quorum: true,
23594            uncontested: Some("only candidate A produced a change".to_owned()),
23595        });
23596        // The exact shape a prior process's `stop_reviewing` would have left
23597        // on disk: the round budget's last round, a real attempt already
23598        // made and already resource-blocked.
23599        state.reviews = vec![ReviewRound {
23600            round: 1,
23601            head: head.clone(),
23602            verified_head: Some(head.clone()),
23603            verified_at: Some(jiff::Timestamp::now()),
23604            reviews: Vec::new(),
23605            e2e: vec![CommandOutcome {
23606                command: format!(
23607                    "CARGO_TARGET_DIR='{}' test -f README.md",
23608                    cache_dir.display()
23609                ),
23610                code: None,
23611                output_tail: "waiting for the shared build cache".to_owned(),
23612                duration_ms: 0,
23613                resource_blocked: true,
23614                ..Default::default()
23615            }],
23616            fix: None,
23617            blocking: 1,
23618            answered: 1,
23619            expected: 1,
23620            clean: false,
23621            verify_retried: false,
23622            e2e_deferred: false,
23623            e2e_defer_reason: None,
23624            progressed: false,
23625            vote_split: false,
23626            reconsideration: Vec::new(),
23627            verdict: None,
23628        }];
23629
23630        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23631        let mut runner = Runner {
23632            state,
23633            roles: ResolvedRoles {
23634                implementers: Vec::new(),
23635                judges: Vec::new(),
23636                reviewers: Vec::new(),
23637                fixer: None,
23638                conductor: conductor(),
23639                implementer_roster: Vec::new(),
23640                judge_roster: Vec::new(),
23641                reviewer_roster: Vec::new(),
23642            },
23643            sem: Arc::new(Semaphore::new(1)),
23644            pause: Pause::new(),
23645            interrupt: Pause::new(),
23646        };
23647
23648        // The lease is still held throughout, so this reentry's own retry is
23649        // also contended — proving `review_loop` actually tried again (not
23650        // that it happened to succeed) is what the timestamp comparison
23651        // below is for.
23652        runner.review_loop().await.expect("review_loop");
23653
23654        assert_eq!(
23655            runner.state.reviews.len(),
23656            1,
23657            "no new round was started on top of the unresolved one: {:?}",
23658            runner.state.reviews
23659        );
23660        let last = &runner.state.reviews[0];
23661        assert_eq!(
23662            last.e2e_status(),
23663            E2eStatus::ResourceBlocked,
23664            "still contended: {last:?}"
23665        );
23666        assert!(
23667            last.verified_at.expect("still known") > first_attempt_at,
23668            "review_loop must have actually retried the check, not left it exactly as found"
23669        );
23670        assert_ne!(
23671            runner.state.status,
23672            RunStatus::Blocked,
23673            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23674            runner.state.status
23675        );
23676
23677        held.release();
23678    }
23679
23680    #[tokio::test]
23681    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23682        crate::run::pin_test_home();
23683        for status in [RunStatus::Blocked, RunStatus::Gating] {
23684            let mut runner = runner_at(status);
23685            runner.state.config.graph.land = true;
23686            runner.state.gate_ran = true;
23687            runner.state.merge = Some(MergeOutcome {
23688                mode: MergeMode::Pr,
23689                ok: false,
23690                detail: "the fixer produced no commit".into(),
23691                empty: false,
23692            });
23693            let url = "https://example.invalid/o/r/pull/1";
23694            runner.state.pr = Some(crate::run::PrRecord {
23695                url: url.into(),
23696                number: 1,
23697                state: "open".into(),
23698                checks: "red".into(),
23699                round: 1,
23700                rounds: 1,
23701                red_at_merge: Vec::new(),
23702            });
23703            runner.state.save().unwrap();
23704            // The nonexistent repository makes observation fail before a forge
23705            // command can run. We still must reach land, rather than silently
23706            // return from the graph with its old gate and merge records.
23707            runner.execute_graph().await.unwrap();
23708            assert_eq!(runner.state.status, RunStatus::Blocked);
23709            assert!(runner.state.land_sync_pending);
23710            assert!(runner.state.events.iter().any(|event|
23711                event.node == "land" && event.message == format!("watching {url}")));
23712            assert_eq!(
23713                runner.state.merge.as_ref().unwrap().detail,
23714                "the fixer produced no commit"
23715            );
23716        }
23717    }
23718
23719    #[tokio::test]
23720    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23721        crate::run::pin_test_home();
23722        let tmp = tempfile::tempdir().expect("tempdir");
23723        let repo = tmp.path().join("repo");
23724        std::fs::create_dir_all(&repo).unwrap();
23725        init_repo(&repo);
23726
23727        let mut config = Config::default();
23728        config.merge.mode = MergeMode::Pr;
23729        config.graph.land = true;
23730        config.graph.land_approval = false;
23731
23732        let mut state = RunState::new(
23733            repo.clone(),
23734            "main".to_owned(),
23735            "deadbeef".to_owned(),
23736            "task".to_owned(),
23737            config,
23738        );
23739        state.candidates = vec![Candidate {
23740            index: 0,
23741            label: 'A',
23742            agent: "alpha".to_owned(),
23743            branch: "does-not-exist".to_owned(),
23744            worktree: repo.clone(),
23745            summary: String::new(),
23746            stat: String::new(),
23747            files: 0,
23748            commits: 0,
23749            empty: false,
23750            failed: None,
23751            verified_noop: None,
23752            duration_ms: 0,
23753            folded: false,
23754        }];
23755        state.tally = Some(Tally {
23756            first_choice: BTreeMap::from([('A', 1)]),
23757            borda: BTreeMap::new(),
23758            winner: 'A',
23759            rankings: 1,
23760            unanimous_initial: true,
23761            deliberated: false,
23762            changed_votes: 0,
23763            unanimous_final: true,
23764            tie_break: None,
23765            judges: 0,
23766            present: 0,
23767            quorum: 0,
23768            met_quorum: true,
23769            uncontested: Some("only candidate A produced a change".to_owned()),
23770        });
23771        state.reviews = vec![ReviewRound {
23772            round: 1,
23773            head: "deadbeef".to_owned(),
23774            verified_head: None,
23775            verified_at: None,
23776            reviews: Vec::new(),
23777            e2e: Vec::new(),
23778            fix: None,
23779            blocking: 0,
23780            answered: 0,
23781            expected: 0,
23782            clean: true,
23783            verify_retried: false,
23784            e2e_deferred: false,
23785            e2e_defer_reason: None,
23786            progressed: false,
23787            vote_split: false,
23788            reconsideration: Vec::new(),
23789            verdict: None,
23790        }];
23791        state.gate = vec![CommandOutcome {
23792            command: "test".to_owned(),
23793            code: Some(0),
23794            output_tail: String::new(),
23795            duration_ms: 0,
23796            resource_blocked: false,
23797            ..Default::default()
23798        }];
23799        state.gate_ran = true;
23800        // A first pass through `merge` already pushed and opened this pull
23801        // request; `status` is `Landing` because a previous call into `land`
23802        // parked or was interrupted before it reached a terminal outcome.
23803        state.status = RunStatus::Landing;
23804        state.merge = Some(MergeOutcome {
23805            mode: MergeMode::Pr,
23806            ok: true,
23807            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23808            empty: false,
23809        });
23810
23811        // The Landing-resume shortcut calls `run_land` directly rather than
23812        // through `merge`, which is exactly the call site that used to skip
23813        // `settle_questions` - see the fixture below.
23814        ask_test_home();
23815        // A real resume loads a persisted run; driver ownership is checked
23816        // against that record before the Landing shortcut is entered.
23817        state.save().expect("save landing run");
23818        let store = ask::Questions::open();
23819        let q = ask_open_question(&store, &state.id);
23820
23821        let mut runner = Runner {
23822            state,
23823            roles: ResolvedRoles {
23824                implementers: Vec::new(),
23825                judges: Vec::new(),
23826                reviewers: Vec::new(),
23827                fixer: None,
23828                conductor: conductor(),
23829                implementer_roster: Vec::new(),
23830                judge_roster: Vec::new(),
23831                reviewer_roster: Vec::new(),
23832            },
23833            sem: Arc::new(Semaphore::new(1)),
23834            pause: Pause::new(),
23835            interrupt: Pause::new(),
23836        };
23837
23838        // `execute`, not `merge` directly: the Landing-resume shortcut lives
23839        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
23840        // exactly because `review_loop` would otherwise clobber the marker
23841        // first.
23842        runner.execute().await.expect("execute");
23843
23844        assert_eq!(
23845            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
23846            Some("https://example.invalid/x/y/pull/1"),
23847            "reentry must not push again or open a second pull request over the \
23848             one `land` is already watching"
23849        );
23850        assert_ne!(
23851            runner.state.status,
23852            RunStatus::Landing,
23853            "land could not actually reach the fake pull request, so it must \
23854             have given up rather than left the run silently parked forever"
23855        );
23856        // `land` could not reach the fake pull request, so it gave up into
23857        // `Blocked` - still resumable, so the question must not have been
23858        // swept just because this branch now also calls `settle_questions`.
23859        assert_eq!(runner.state.status, RunStatus::Blocked);
23860        assert!(
23861            store.get(&q.id).unwrap().status.open(),
23862            "Blocked is still alive; settle_questions must have been a no-op here"
23863        );
23864    }
23865
23866    fn state_with_round(round: ReviewRound) -> RunState {
23867        let mut s = RunState::new(
23868            PathBuf::from("/repo"),
23869            "main".to_owned(),
23870            "abc1234".to_owned(),
23871            "add retries".to_owned(),
23872            Config::default(),
23873        );
23874        s.reviews = vec![round];
23875        s
23876    }
23877
23878    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
23879        crate::verdict::Finding {
23880            id: id.to_owned(),
23881            severity,
23882            file: None,
23883            line: None,
23884            title: title.to_owned(),
23885            detail: String::new(),
23886        }
23887    }
23888
23889    #[test]
23890    fn pr_body_names_open_findings_and_declined_ones() {
23891        let round = ReviewRound {
23892            round: 2,
23893            head: "deadbee".to_owned(),
23894            verified_head: None,
23895            verified_at: None,
23896            reviews: vec![ReviewRecord {
23897                attempts: 0,
23898                reviewer: 1,
23899                agent: "alpha".to_owned(),
23900                summary: String::new(),
23901                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
23902                vote: None,
23903                failed: None,
23904                duration_ms: 0,
23905            }],
23906            e2e: vec![CommandOutcome {
23907                command: "cargo test".to_owned(),
23908                code: Some(0),
23909                output_tail: String::new(),
23910                duration_ms: 0,
23911                resource_blocked: false,
23912                ..Default::default()
23913            }],
23914            verify_retried: false,
23915            e2e_deferred: false,
23916            e2e_defer_reason: None,
23917            fix: Some(FixRecord {
23918                agent: "alpha".to_owned(),
23919                addressed: Vec::new(),
23920                rejected: vec![crate::verdict::Rejection {
23921                    id: "R1-1-1".to_owned(),
23922                    why: "not reachable from any caller".to_owned(),
23923                }],
23924                notes: String::new(),
23925                committed: true,
23926                failed: None,
23927                duration_ms: 0,
23928                continuation: None,
23929            }),
23930            blocking: 0,
23931            answered: 1,
23932            expected: 1,
23933            clean: false,
23934            progressed: true,
23935            vote_split: false,
23936            reconsideration: Vec::new(),
23937            verdict: None,
23938        };
23939        let state = state_with_round(round);
23940        let body = pr_message(&state, 'A').body;
23941
23942        assert!(body.contains("add retries"), "the task must still be there");
23943        assert!(body.contains("R2-1-1"), "{body}");
23944        assert!(!body.contains("unused import"), "{body}");
23945        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
23946        assert!(
23947            !body.contains("not reachable from any caller"),
23948            "the reason it was declined: {body}"
23949        );
23950    }
23951
23952    #[test]
23953    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
23954        let round = ReviewRound {
23955            round: 1,
23956            head: "deadbee".to_owned(),
23957            verified_head: None,
23958            verified_at: None,
23959            reviews: vec![ReviewRecord {
23960                attempts: 0,
23961                reviewer: 1,
23962                agent: "alpha".to_owned(),
23963                summary: String::new(),
23964                findings: Vec::new(),
23965                vote: None,
23966                failed: None,
23967                duration_ms: 0,
23968            }],
23969            e2e: Vec::new(),
23970            verify_retried: false,
23971            e2e_deferred: false,
23972            e2e_defer_reason: None,
23973            fix: None,
23974            blocking: 0,
23975            answered: 1,
23976            expected: 1,
23977            clean: true,
23978            progressed: false,
23979            vote_split: false,
23980            reconsideration: Vec::new(),
23981            verdict: None,
23982        };
23983        let state = state_with_round(round);
23984        let body = pr_message(&state, 'A').body;
23985        assert!(!body.contains("Open review findings"), "{body}");
23986        assert!(!body.contains("Declined"), "{body}");
23987    }
23988
23989    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
23990        let mut state = RunState::new(
23991            PathBuf::from("/repo"),
23992            "main".to_owned(),
23993            "abc1234".to_owned(),
23994            instruction.to_owned(),
23995            Config::default(),
23996        );
23997        // These fixtures test execution flow, independent of host disk capacity.
23998        state.config.disk.min_free_bytes = 0;
23999        state.candidates.push(Candidate {
24000            index: 0,
24001            label: 'A',
24002            agent: "alpha".to_owned(),
24003            branch: "magi/x/A".to_owned(),
24004            worktree: PathBuf::from("/wt"),
24005            summary: summary.to_owned(),
24006            stat: String::new(),
24007            files: 1,
24008            commits: 1,
24009            empty: false,
24010            failed: None,
24011            verified_noop: None,
24012            folded: false,
24013            duration_ms: 0,
24014        });
24015        state
24016    }
24017
24018    fn review_state(subjects: &[&str]) -> RunState {
24019        let mut state = state_with_summary(
24020            "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",
24021            "",
24022        );
24023        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24024        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24025        state
24026    }
24027
24028    /// A branch rebased onto a main that moved past the recorded
24029    /// `base_commit` is titled from its own first commit, never main's.
24030    #[tokio::test]
24031    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24032        ask_test_home();
24033        let tmp = tempfile::tempdir().unwrap();
24034        let repo = tmp.path().join("repo");
24035        std::fs::create_dir_all(&repo).unwrap();
24036        init_repo(&repo);
24037        let origin = tmp.path().join("origin.git");
24038        let g = |dir: &Path, args: &[&str]| {
24039            let out = std::process::Command::new("git")
24040                .args(args)
24041                .current_dir(dir)
24042                .quiet()
24043                .output()
24044                .expect("spawn git");
24045            assert!(
24046                out.status.success(),
24047                "git {args:?}: {}",
24048                String::from_utf8_lossy(&out.stderr)
24049            );
24050        };
24051        g(
24052            tmp.path(),
24053            &[
24054                "clone",
24055                "--bare",
24056                "-q",
24057                repo.to_str().unwrap(),
24058                origin.to_str().unwrap(),
24059            ],
24060        );
24061        g(
24062            &repo,
24063            &["remote", "add", "origin", origin.to_str().unwrap()],
24064        );
24065        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24066
24067        // Main moves on; the branch is built on top of the new main.
24068        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24069        g(&repo, &["add", "-A"]);
24070        g(
24071            &repo,
24072            &["commit", "-q", "-m", "chore(deps): update a crate"],
24073        );
24074        g(&repo, &["push", "-q", "origin", "main"]);
24075        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24076        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24077        g(&repo, &["add", "-A"]);
24078        g(
24079            &repo,
24080            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24081        );
24082        g(&repo, &["checkout", "-q", "main"]);
24083
24084        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24085        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24086        // Without a readable tracking ref the recorded base's merge base is used.
24087        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24088        assert_eq!(fallback, c1);
24089
24090        let mut state = review_state(&[
24091            "chore(deps): update a crate",
24092            "fix(daemon): apply a chosen action",
24093        ]);
24094        state.repo = repo.clone();
24095        state.base_branch = "main".to_owned();
24096        state.base_commit = c1;
24097        refresh_reviewed_commits(&mut state, "feat/own").await;
24098        assert_eq!(
24099            state.reviewed_commits,
24100            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24101        );
24102        assert_eq!(
24103            review_title(&state).as_deref(),
24104            Some("fix(daemon): apply a chosen action")
24105        );
24106        assert_eq!(
24107            leaked_subjects(&state, "feat/own").await,
24108            Some(vec!["chore(deps): update a crate".to_owned()])
24109        );
24110        // A stale tracking ref is still used when the fetch fails, but the
24111        // leak list is withheld.
24112        state.config.merge.remote = "nowhere".to_owned();
24113        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24114    }
24115
24116    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24117    /// with `origin/main` one commit behind it, and a summarizing agent that
24118    /// prints whatever `reply` holds.
24119    struct SummaryFixture {
24120        _tmp: tempfile::TempDir,
24121        repo: PathBuf,
24122        reply: PathBuf,
24123        runner: Runner,
24124    }
24125
24126    fn summary_fixture() -> SummaryFixture {
24127        ask_test_home();
24128        let tmp = tempfile::tempdir().unwrap();
24129        let repo = tmp.path().join("repo");
24130        std::fs::create_dir_all(&repo).unwrap();
24131        init_repo(&repo);
24132        let origin = tmp.path().join("origin.git");
24133        let g = |args: &[&str]| {
24134            let out = std::process::Command::new("git")
24135                .args(args)
24136                .current_dir(&repo)
24137                .quiet()
24138                .output()
24139                .expect("spawn git");
24140            assert!(
24141                out.status.success(),
24142                "git {args:?}: {}",
24143                String::from_utf8_lossy(&out.stderr)
24144            );
24145        };
24146        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24147        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24148        g(&["push", "-q", "origin", "main"]);
24149        g(&["checkout", "-q", "-b", "feat/own"]);
24150        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24151        g(&["add", "-A"]);
24152        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24153        let reply = tmp.path().join("reply.txt");
24154        std::fs::write(
24155            &reply,
24156            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24157        )
24158        .unwrap();
24159        let mut runner = runner_at(RunStatus::Gating);
24160        let mut state = review_state(&["feat(own): add the own file"]);
24161        state.repo = repo.clone();
24162        state.base_branch = "main".to_owned();
24163        state.candidates[0].branch = "feat/own".to_owned();
24164        state.candidates[0].worktree = repo.clone();
24165        let mut author = spec("alpha");
24166        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24167        author
24168            .env
24169            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24170        state.config.agents = vec![author];
24171        runner.state = state;
24172        SummaryFixture {
24173            _tmp: tmp,
24174            repo,
24175            reply,
24176            runner,
24177        }
24178    }
24179
24180    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24181        let winner = f.runner.state.candidates[0].clone();
24182        f.runner
24183            .guarded_pr_message(&winner, None, true)
24184            .await
24185            .unwrap()
24186            .expect("an English description never parks")
24187    }
24188
24189    fn clean_round_with_minor_findings() -> ReviewRound {
24190        let mut round = passing_round(2, None);
24191        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24192        round.reviews = vec![ReviewRecord {
24193            attempts: 0,
24194            reviewer: 1,
24195            agent: "alpha".into(),
24196            summary: "内部レビュー".into(),
24197            findings: vec![
24198                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24199                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24200            ],
24201            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24202            failed: None,
24203            duration_ms: 0,
24204        }];
24205        round
24206    }
24207
24208    #[tokio::test]
24209    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24210        for review_only in [false, true] {
24211            let mut f = summary_fixture();
24212            if !review_only {
24213                f.runner.state.candidates[0].agent = "alpha".into();
24214            }
24215            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24216            assert!(f.runner.state.reviews[0].clean);
24217            assert!(f.runner.state.reviews[0].fix.is_none());
24218            assert!(f.runner.state.open_findings().is_empty());
24219            assert_eq!(
24220                crate::pr_outcome::required_finding_ids(&f.runner.state),
24221                ["R2-1-1", "R2-1-2"]
24222            );
24223            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24224            let evidence = crate::pr_outcome::summary_evidence(
24225                &f.runner.state,
24226                crate::pr_outcome::FinalHead::At(&head),
24227            );
24228            assert!(
24229                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24230            );
24231            // The ordinary reply omits both IDs: no cached description is adopted.
24232            let omitted = posted(&mut f).await;
24233            assert!(omitted.body.contains("No description"));
24234            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24235            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24236            assert!(f.runner.state.change_summary.is_none());
24237            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();
24238            let described = posted(&mut f).await;
24239            assert!(described.body.contains("improve documentation for callers"));
24240            assert!(described.body.contains("remaining edge case"));
24241            assert!(described.body.contains("## Open review findings"));
24242            assert!(!described.body.contains("未修正"));
24243        }
24244    }
24245
24246    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24247        let mut f = summary_fixture();
24248        if !review_only {
24249            f.runner.state.candidates[0].agent = "alpha".into();
24250        }
24251        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24252        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24253        fixed
24254            .fix
24255            .as_mut()
24256            .unwrap()
24257            .rejected
24258            .push(crate::verdict::Rejection {
24259                id: "R1-1-1".into(),
24260                why: "呼び出されないコードのため辞退".into(),
24261            });
24262        let mut clean = clean_round_with_minor_findings();
24263        clean.verified_head = Some(head.clone());
24264        f.runner.state.reviews = vec![fixed, clean];
24265        ok_gate(&mut f.runner.state, Some(&head));
24266        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24267        f.runner.state.config.agents.push(scripted("beta", reply));
24268        f.runner.state.config.roles.language_judge =
24269            Some(crate::config::AgentChoice::One("beta".into()));
24270        f
24271    }
24272
24273    #[tokio::test]
24274    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24275        for review_only in [false, true] {
24276            let mut f = rewrite_fixture_with_findings(review_only,
24277                "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;
24278            let m = posted(&mut f).await;
24279            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24280            let expected =
24281                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24282            assert!(m.body.contains(&expected));
24283            assert!(m.body.contains("## Review rounds"));
24284            assert!(
24285                m.body
24286                    .contains("Gate (`verify.gate`): passed on the final commit")
24287            );
24288            assert!(
24289                m.body
24290                    .contains("Tests (`verify.e2e`): passed on the final commit")
24291            );
24292            let c = f.runner.state.change_summary.as_ref().unwrap();
24293            assert!(
24294                m.body
24295                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24296            );
24297            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24298            assert!(crate::pr_outcome::covers_required_findings(
24299                &f.runner.state,
24300                &m.body
24301            ));
24302            assert!(m.body.contains("documentation remains incomplete"));
24303            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24304            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24305            assert!(f.runner.state.github_text.is_none());
24306        }
24307    }
24308
24309    #[tokio::test]
24310    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24311        for review_only in [false, true] {
24312            for reply in [
24313                "TITLE: fix: public description\nA short English description.",
24314                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24315            ] {
24316                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24317                let winner = f.runner.state.candidates[0].clone();
24318                let posted = f
24319                    .runner
24320                    .guarded_pr_message(&winner, None, true)
24321                    .await
24322                    .unwrap();
24323                assert!(posted.is_none());
24324                assert!(f.runner.state.parked);
24325                let withheld = f.runner.state.github_text.as_ref().unwrap();
24326                assert!(
24327                    withheld.rewrite.is_none(),
24328                    "an incomplete rewrite must not be selectable"
24329                );
24330                let q = ask::Questions::open()
24331                    .get(withheld.question.as_ref().unwrap())
24332                    .unwrap();
24333                assert!(
24334                    !q.choices
24335                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24336                );
24337                assert!(
24338                    q.detail.contains("R1-1-1")
24339                        && q.detail.contains("R2-1-1")
24340                        && q.detail.contains("R2-1-2")
24341                );
24342            }
24343        }
24344    }
24345
24346    #[tokio::test]
24347    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24348        for review_only in [false, true] {
24349            let mut f = summary_fixture();
24350            if !review_only {
24351                f.runner.state.candidates[0].agent = "alpha".into();
24352            }
24353            f.runner.state.instruction = "内部タスクの説明".into();
24354            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24355            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24356            f.runner.state.reviews = vec![
24357                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24358                round_with_notes(2, Some("二回目の内部修正報告です。")),
24359                passing_round(3, Some(&head)),
24360            ];
24361            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24362            ok_gate(&mut f.runner.state, Some(&head));
24363            let captured = f.repo.join("public-prompt.txt");
24364            let author = &mut f.runner.state.config.agents[0];
24365            author.command = vec![
24366                "sh".into(),
24367                "-c".into(),
24368                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24369            ];
24370            author.env.insert(
24371                "PROMPT_FILE".into(),
24372                captured.to_string_lossy().into_owned(),
24373            );
24374            let m = posted(&mut f).await;
24375            assert!(m.body.contains("Adds `own.txt`"));
24376            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24377            assert!(m.body.contains("R1-1-1"));
24378            assert!(
24379                m.body
24380                    .contains("Gate (`verify.gate`): passed on the final commit")
24381            );
24382            assert!(
24383                m.body
24384                    .contains("Tests (`verify.e2e`): passed on the final commit")
24385            );
24386            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24387            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24388            let prompt = std::fs::read_to_string(captured).unwrap();
24389            assert!(prompt.contains(&format!(
24390                "git diff {} {head}",
24391                f.runner.state.change_summary.as_ref().unwrap().base
24392            )));
24393            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24394            assert_eq!(
24395                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24396                "二回目の内部修正報告です。"
24397            );
24398        }
24399    }
24400
24401    #[tokio::test]
24402    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24403        for review_only in [false, true] {
24404            let mut f = summary_fixture();
24405            if !review_only {
24406                f.runner.state.candidates[0].agent = "alpha".into();
24407            }
24408            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24409            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24410            std::fs::write(&f.reply, "no usable description").unwrap();
24411            let failed = posted(&mut f).await;
24412            assert!(
24413                failed
24414                    .body
24415                    .contains("No description of what this change does could be generated")
24416            );
24417            assert!(failed.body.is_ascii());
24418            assert!(f.runner.state.github_text.is_none());
24419            assert!(f.runner.state.change_summary.is_none());
24420            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24421            let evidence = crate::pr_outcome::summary_evidence(
24422                &f.runner.state,
24423                crate::pr_outcome::FinalHead::At(&head),
24424            );
24425            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24426            assert!(
24427                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24428                    .exists()
24429            );
24430            f.runner.state =
24431                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24432            std::fs::write(
24433                &f.reply,
24434                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24435            )
24436            .unwrap();
24437            let retried = posted(&mut f).await;
24438            assert!(retried.body.contains("Adds the committed own file."));
24439            assert_eq!(
24440                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24441                "日本語の修正報告"
24442            );
24443        }
24444    }
24445
24446    #[tokio::test]
24447    async fn same_head_verification_and_findings_invalidate_public_prose() {
24448        let mut f = summary_fixture();
24449        posted(&mut f).await;
24450        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24451        let original = f
24452            .runner
24453            .state
24454            .change_summary
24455            .as_ref()
24456            .unwrap()
24457            .evidence
24458            .clone();
24459        ok_gate(&mut f.runner.state, Some(&head));
24460        std::fs::write(
24461            &f.reply,
24462            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24463        )
24464        .unwrap();
24465        let verified = posted(&mut f).await;
24466        assert!(verified.body.contains("now verified"));
24467        assert_ne!(
24468            f.runner.state.change_summary.as_ref().unwrap().evidence,
24469            original
24470        );
24471        let mut round = round_with_notes(1, Some("内部報告"));
24472        round.reviews.push(ReviewRecord {
24473            attempts: 0,
24474            reviewer: 1,
24475            agent: "alpha".into(),
24476            summary: "内部レビュー".into(),
24477            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24478            vote: None,
24479            failed: None,
24480            duration_ms: 0,
24481        });
24482        round
24483            .fix
24484            .as_mut()
24485            .unwrap()
24486            .rejected
24487            .push(crate::verdict::Rejection {
24488                id: "R1-1-1".into(),
24489                why: "呼び出し元から到達できない".into(),
24490            });
24491        f.runner.state.reviews = vec![round];
24492        // A description omitting the required ID is unusable, even with a title.
24493        let omitted = posted(&mut f).await;
24494        assert!(omitted.body.contains("No description"));
24495        assert!(omitted.body.contains("R1-1-1"));
24496        assert!(!omitted.body.contains("到達"));
24497        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();
24498        let described = posted(&mut f).await;
24499        assert!(described.body.contains("unreachable from callers"));
24500        assert!(described.body.contains("R1-1-1"));
24501        assert!(!described.body.contains("到達"));
24502        let evidence = f
24503            .runner
24504            .state
24505            .change_summary
24506            .as_ref()
24507            .unwrap()
24508            .evidence
24509            .clone();
24510        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24511        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24512        assert!(posted(&mut f).await.body.contains("rationale updated"));
24513        assert_ne!(
24514            f.runner.state.change_summary.as_ref().unwrap().evidence,
24515            evidence
24516        );
24517        // Old serialized summaries have no evidence fingerprint and must regenerate.
24518        f.runner
24519            .state
24520            .change_summary
24521            .as_mut()
24522            .unwrap()
24523            .evidence
24524            .clear();
24525        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24526        assert!(posted(&mut f).await.body.contains("current specification"));
24527    }
24528
24529    #[tokio::test]
24530    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24531        let mut f = summary_fixture();
24532        let m = posted(&mut f).await;
24533        assert_eq!(m.title, "feat(own): add the own file");
24534        assert!(
24535            m.body
24536                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24537            "{}",
24538            m.body
24539        );
24540        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24541        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24542        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24543        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24544        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24545        let kept = f.runner.state.change_summary.as_ref().unwrap();
24546        assert_eq!(
24547            (kept.head.as_str(), kept.base.as_str()),
24548            (head.as_str(), base.as_str())
24549        );
24550        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24551    }
24552
24553    #[tokio::test]
24554    async fn review_only_summary_receives_the_configured_github_language() {
24555        let mut f = summary_fixture();
24556        f.runner.state.config.graph.github_language = "ja".into();
24557        let captured = f.repo.join("summary-prompt.txt");
24558        let author = &mut f.runner.state.config.agents[0];
24559        author.command = vec![
24560            "sh".into(),
24561            "-c".into(),
24562            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24563        ];
24564        author.env.insert(
24565            "PROMPT_FILE".into(),
24566            captured.to_string_lossy().into_owned(),
24567        );
24568        std::fs::write(
24569            &f.reply,
24570            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24571        )
24572        .unwrap();
24573        let m = posted(&mut f).await;
24574        let prompt = std::fs::read_to_string(captured).unwrap();
24575        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24576        assert!(!prompt.contains("in English"));
24577        assert_eq!(m.title, "feat(own): ファイルを追加");
24578        assert!(m.body.contains("own.txt を追加します。"));
24579    }
24580
24581    #[tokio::test]
24582    async fn review_fixes_come_after_the_whole_change_summary() {
24583        let mut f = summary_fixture();
24584        f.runner.state.reviews = vec![
24585            round_with_notes(1, Some("handled the PATH case")),
24586            round_with_notes(2, None),
24587        ];
24588        let m = posted(&mut f).await;
24589        let summary = m.body.find("## Summary").expect("summary");
24590        let fixes = m.body.find("## Review rounds").expect("review rounds");
24591        assert!(summary < fixes, "{}", m.body);
24592        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24593        assert!(m.body.contains("## Final verification"), "{}", m.body);
24594    }
24595
24596    #[tokio::test]
24597    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24598        let mut f = summary_fixture();
24599        let first = posted(&mut f).await;
24600        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24601        // The same head reuses the record: a different reply is not read.
24602        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24603        let again = posted(&mut f).await;
24604        assert_eq!((again.title, again.body), (first.title, first.body));
24605
24606        let g = |args: &[&str]| {
24607            let out = std::process::Command::new("git")
24608                .args(args)
24609                .current_dir(&f.repo)
24610                .quiet()
24611                .output()
24612                .expect("spawn git");
24613            assert!(out.status.success(), "git {args:?}");
24614        };
24615        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24616        g(&["add", "-A"]);
24617        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24618        let second = posted(&mut f).await;
24619        let kept = f.runner.state.change_summary.clone().unwrap();
24620        assert_ne!(kept.head, first_head);
24621        assert!(second.body.contains("Not read yet."), "{}", second.body);
24622        assert!(!second.body.contains("so the first summary is read"));
24623        assert_eq!(second.title, "feat(own): other");
24624    }
24625
24626    #[tokio::test]
24627    async fn an_unavailable_summary_is_stated_and_never_invented() {
24628        let mut f = summary_fixture();
24629        std::fs::write(&f.reply, "no title line here").unwrap();
24630        let m = posted(&mut f).await;
24631        assert!(
24632            m.body
24633                .contains("No description of what this change does could be generated"),
24634            "{}",
24635            m.body
24636        );
24637        assert!(m.body.contains("internal reports remain in local records"));
24638        assert!(f.runner.state.change_summary.is_none());
24639        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24640        // A preview asks nobody and claims nothing.
24641        let winner = f.runner.state.candidates[0].clone();
24642        let preview = f
24643            .runner
24644            .guarded_pr_message(&winner, None, false)
24645            .await
24646            .unwrap()
24647            .unwrap();
24648        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24649    }
24650
24651    #[test]
24652    fn pr_message_review_single_commit_uses_its_subject() {
24653        let state = review_state(&["feat(nats): per-role user"]);
24654        let m = pr_message(&state, 'A');
24655        assert_eq!(m.title, "feat(nats): per-role user");
24656        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24657        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24658    }
24659
24660    #[test]
24661    fn pr_message_review_multi_commit_takes_the_oldest() {
24662        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24663        let m = pr_message(&state, 'A');
24664        assert_eq!(m.title, "feat: the change");
24665        for s in ["feat: the change", "fix: typo", "fix: again"] {
24666            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24667        }
24668    }
24669
24670    #[test]
24671    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24672        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24673            let mut state = review_state(&[first, "fix: later fixup"]);
24674            state.candidates[0].branch = "機能/ログイン".to_owned();
24675            let m = pr_message(&state, 'A');
24676            assert!(
24677                m.title.starts_with("chore: land candidate A of run"),
24678                "{}",
24679                m.title
24680            );
24681        }
24682    }
24683
24684    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24685        BranchFacts {
24686            commits: commits
24687                .iter()
24688                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24689                .collect(),
24690            stat: stat.to_owned(),
24691        }
24692    }
24693
24694    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24695        let mut r = review_round(true, 0, 1, 1, true, true);
24696        r.round = round;
24697        r.fix = notes.map(|n| FixRecord {
24698            agent: "fixer".to_owned(),
24699            addressed: Vec::new(),
24700            rejected: Vec::new(),
24701            notes: n.to_owned(),
24702            committed: true,
24703            failed: None,
24704            duration_ms: 0,
24705            continuation: None,
24706        });
24707        r
24708    }
24709
24710    #[test]
24711    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24712        let state = review_state(&["ignored"]);
24713        let f = facts(
24714            &[
24715                (
24716                    "fix(login): resolve PATH on macOS",
24717                    "Login shells skip rc files.",
24718                ),
24719                ("fix: address review", ""),
24720            ],
24721            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24722        );
24723        let m = pr_message_with(&state, 'A', Some(&f));
24724        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
24725        assert!(
24726            m.body
24727                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
24728            "{}",
24729            m.body
24730        );
24731        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
24732        assert!(m.body.contains("## Diff stat"), "{}", m.body);
24733        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
24734        for banned in [
24735            "Review the work already",
24736            "no task statement",
24737            "Original task",
24738        ] {
24739            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24740        }
24741        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24742    }
24743
24744    #[test]
24745    fn pr_message_review_truncates_a_huge_first_commit_body() {
24746        let state = review_state(&["ignored"]);
24747        let f = facts(
24748            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24749            "s",
24750        );
24751        let m = pr_message_with(&state, 'A', Some(&f));
24752        assert!(m.body.len() < 30_000, "{}", m.body.len());
24753        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24754        assert!(
24755            m.body.contains("- ... 1 more commit(s)"),
24756            "{}",
24757            m.body.len()
24758        );
24759        assert!(m.body.ends_with("magi:candidate-a\n"));
24760    }
24761
24762    #[test]
24763    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24764        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24765        assert_eq!(m.title, "feat: x");
24766        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24767        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24768        assert!(!m.body.contains("no task statement"), "{}", m.body);
24769    }
24770
24771    #[test]
24772    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24773        let mut state = review_state(&["日本語の件名"]);
24774        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24775        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24776        state.candidates[0].branch = "機能/ログイン".to_owned();
24777        assert!(
24778            pr_message(&state, 'A')
24779                .title
24780                .starts_with("chore: land candidate A")
24781        );
24782    }
24783
24784    #[test]
24785    fn pr_message_review_fixes_survive_a_clean_final_round() {
24786        let mut state = review_state(&["feat: x"]);
24787        state.reviews = vec![
24788            round_with_notes(1, Some("handled the PATH case")),
24789            round_with_notes(2, None),
24790        ];
24791        let body = pr_message(&state, 'A').body;
24792        assert!(
24793            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24794            "{body}"
24795        );
24796        assert!(body.contains("### Round 1"), "{body}");
24797
24798        state.reviews = vec![
24799            round_with_notes(1, Some("first fix")),
24800            round_with_notes(2, Some("")),
24801            round_with_notes(3, Some("second fix")),
24802            round_with_notes(4, None),
24803        ];
24804        let body = pr_message(&state, 'A').body;
24805        assert!(
24806            body.contains("### Round 1") && !body.contains("first fix"),
24807            "{body}"
24808        );
24809        assert!(
24810            body.contains("### Round 3") && !body.contains("second fix"),
24811            "{body}"
24812        );
24813        assert!(body.contains("### Round 2"), "{body}");
24814    }
24815
24816    const FINAL: &str = "abcdef1234567890";
24817
24818    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
24819        let mut r = round_with_notes(round, None);
24820        r.verified_head = verified.map(str::to_owned);
24821        r
24822    }
24823
24824    fn ok_gate(state: &mut RunState, head: Option<&str>) {
24825        state.gate = vec![CommandOutcome {
24826            command: "gate".to_owned(),
24827            code: Some(0),
24828            output_tail: String::new(),
24829            duration_ms: 0,
24830            resource_blocked: false,
24831            ..Default::default()
24832        }];
24833        state.gate_ran = true;
24834        state.gate_head = head.map(str::to_owned);
24835    }
24836
24837    fn body_at(state: &RunState) -> String {
24838        pr_message_raw(
24839            state,
24840            'A',
24841            None,
24842            crate::pr_outcome::FinalHead::At(FINAL),
24843            ChangeNote::NotAsked,
24844        )
24845        .body
24846    }
24847
24848    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
24849
24850    #[test]
24851    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
24852        let mut state = review_state(&["feat: x"]);
24853        state.reviews = vec![
24854            round_with_notes(1, Some(SANDBOXED)),
24855            passing_round(2, Some(FINAL)),
24856        ];
24857        ok_gate(&mut state, Some(FINAL));
24858        let body = body_at(&state);
24859        assert!(!body.contains("Handled the PATH case."), "{body}");
24860        assert!(!body.contains("could not commit"), "{body}");
24861        assert!(!body.contains("could not run"), "{body}");
24862        assert!(
24863            body.contains("The fix is committed on the branch"),
24864            "{body}"
24865        );
24866        assert!(!body.contains("sandbox"), "{body}");
24867        assert!(
24868            body.contains("Tests (`verify.e2e`): passed on the final commit"),
24869            "{body}"
24870        );
24871        assert!(
24872            body.contains("Gate (`verify.gate`): passed on the final commit"),
24873            "{body}"
24874        );
24875        // The raw report is untouched in the record.
24876        assert!(
24877            state.reviews[0]
24878                .fix
24879                .as_ref()
24880                .unwrap()
24881                .notes
24882                .contains("could not commit")
24883        );
24884    }
24885
24886    #[test]
24887    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
24888        let mut state = review_state(&["feat: x"]);
24889        let mut r1 = round_with_notes(1, Some(SANDBOXED));
24890        r1.fix.as_mut().unwrap().committed = false;
24891        let mut r2 = passing_round(2, Some(FINAL));
24892        r2.e2e[0].code = Some(1);
24893        state.reviews = vec![r1, r2];
24894        let body = body_at(&state);
24895        assert!(!body.contains("could not commit"), "{body}");
24896        assert!(!body.contains("could not run"), "{body}");
24897        assert!(body.contains("This round produced no commit"), "{body}");
24898        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
24899        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
24900        assert!(!body.contains("passed"), "{body}");
24901    }
24902
24903    #[test]
24904    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
24905        let mut state = review_state(&["feat: x"]);
24906        state.reviews = vec![
24907            round_with_notes(1, Some(SANDBOXED)),
24908            passing_round(2, Some("0123456789abcdef")),
24909        ];
24910        ok_gate(&mut state, Some("0123456789abcdef"));
24911        let body = body_at(&state);
24912        assert!(!body.contains("HTTP tests could not run"), "{body}");
24913        // The commit claim is still settled by the structured record.
24914        assert!(!body.contains("could not commit"), "{body}");
24915        assert!(
24916            body.contains("passed on an earlier commit (`0123456`)"),
24917            "{body}"
24918        );
24919        assert!(!body.contains("passed on the final commit"), "{body}");
24920
24921        // A gate recorded before `gate_head` existed is "not recorded".
24922        ok_gate(&mut state, None);
24923        let body = body_at(&state);
24924        assert!(
24925            body.contains("passed on a commit that was not recorded"),
24926            "{body}"
24927        );
24928    }
24929
24930    #[test]
24931    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
24932        let state = state_with_summary(
24933            "add retries to the client",
24934            "TITLE: feat: retries\n\nDid it.",
24935        );
24936        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
24937        assert_eq!(m.title, "feat: retries");
24938        assert!(
24939            m.body.contains("<summary>Original task</summary>"),
24940            "{}",
24941            m.body
24942        );
24943        assert!(!m.body.contains("Commits under review"), "{}", m.body);
24944        assert!(
24945            m.body
24946                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
24947            "{}",
24948            m.body
24949        );
24950    }
24951
24952    #[test]
24953    fn pr_message_review_bounds_a_long_english_subject() {
24954        let long = format!("feat: {}", "word ".repeat(100));
24955        let m = pr_message(&review_state(&[&long]), 'A');
24956        assert!(m.title.starts_with("feat: word"), "{}", m.title);
24957        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24958    }
24959
24960    #[test]
24961    fn pr_message_implementation_run_is_unchanged_by_review_support() {
24962        let state = state_with_summary("add retries\n\ndetails", "- did some things");
24963        let m = pr_message(&state, 'A');
24964        assert_eq!(m.title, "add retries");
24965        assert!(m.body.contains("<summary>Original task</summary>"));
24966        assert!(!m.body.contains("Commits under review"));
24967        assert_eq!(landing_subject_source(&state), state.instruction);
24968    }
24969
24970    #[test]
24971    fn review_run_squash_subject_is_the_change_not_the_prompt() {
24972        let state = review_state(&["feat: the change", "fix: typo"]);
24973        let source = landing_subject_source(&state);
24974        assert_eq!(land::merge_subject("", &source), "feat: the change");
24975        assert_eq!(
24976            land::merge_subject("magi: candidate A (uncommitted work)", &source),
24977            "feat: the change"
24978        );
24979        // An operator's rename still wins.
24980        assert_eq!(
24981            land::merge_subject("feat: renamed by hand", &source),
24982            "feat: renamed by hand"
24983        );
24984        let blank = review_state(&["日本語"]);
24985        assert!(
24986            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
24987        );
24988    }
24989
24990    #[test]
24991    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
24992        let state = review_state(&["feat: the change"]);
24993        let source = landing_subject_source(&state);
24994        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
24995        assert_eq!(
24996            land::merge_subject(landing_title(&state, old), &source),
24997            "feat: the change"
24998        );
24999        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25000        let task = state_with_summary("add retries", "");
25001        assert_eq!(landing_title(&task, old), old);
25002    }
25003
25004    #[test]
25005    fn pr_message_describes_the_change_not_the_task() {
25006        let state = state_with_summary(
25007            "今回やってほしいこと: results projector を直す",
25008            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25009        );
25010        let m = pr_message(&state, 'A');
25011        assert_eq!(m.title, "fix(web): batch the runs list reads");
25012        assert!(
25013            m.body.starts_with("## Summary\n\n- reads run.json once"),
25014            "{}",
25015            m.body
25016        );
25017        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25018        let task_at = m.body.find("今回やってほしいこと").unwrap();
25019        let details_at = m.body.find("<details>").unwrap();
25020        assert!(
25021            details_at < task_at,
25022            "the task lives inside <details>: {}",
25023            m.body
25024        );
25025        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25026        assert!(m.body.contains("magi:candidate-a"));
25027    }
25028
25029    #[test]
25030    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25031        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25032        let m = pr_message(&state, 'A');
25033        assert_eq!(m.title, "add retries");
25034        assert!(
25035            m.body.contains("## Summary\n\n- did some things"),
25036            "{}",
25037            m.body
25038        );
25039
25040        let none = RunState::new(
25041            PathBuf::from("/repo"),
25042            "main".to_owned(),
25043            "abc1234".to_owned(),
25044            "add retries".to_owned(),
25045            Config::default(),
25046        );
25047        let m = pr_message(&none, 'A');
25048        assert_eq!(m.title, "add retries");
25049        assert!(!m.body.contains("## Summary"), "{}", m.body);
25050    }
25051
25052    #[test]
25053    fn pr_message_refuses_the_candidate_commit_subject() {
25054        for bad in [
25055            "TITLE: magi: candidate A (uncommitted work)",
25056            "TITLE: chore: stuff (uncommitted work)",
25057            "TITLE:   ",
25058        ] {
25059            let state = state_with_summary("add retries", bad);
25060            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25061        }
25062    }
25063
25064    #[test]
25065    fn pr_message_bounds_a_very_long_task_and_title() {
25066        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25067        let state = state_with_summary(&long, "- nothing");
25068        let m = pr_message(&state, 'A');
25069        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25070        assert!(!m.title.contains('\n'));
25071
25072        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25073        let m = pr_message(&state, 'A');
25074        assert!(m.title.starts_with("feat: "));
25075        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25076        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25077    }
25078
25079    fn long_title_of(instruction: &str) -> String {
25080        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25081    }
25082
25083    #[test]
25084    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25085        let first = "Make the landing path keep a readable title for long tasks";
25086        let line = format!(
25087            "{first}. {}",
25088            "And then keep going with more words ".repeat(20)
25089        );
25090        let t = long_title_of(&line);
25091        assert_eq!(t, first);
25092        assert!(!t.starts_with("chore: land"));
25093    }
25094
25095    #[test]
25096    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25097        let line = "word ".repeat(200);
25098        let t = long_title_of(&line);
25099        assert!(t.ends_with("word..."), "{t}");
25100        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25101    }
25102
25103    #[test]
25104    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25105        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25106            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25107        }
25108    }
25109
25110    #[test]
25111    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25112        let mut state = state_with_summary("再試行を追加する", "- nothing");
25113        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25114        state.config.graph.github_language = "ja".into();
25115        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25116    }
25117
25118    #[test]
25119    fn pr_message_title_limit_is_exact() {
25120        let at = "a".repeat(PR_TITLE_MAX);
25121        assert_eq!(long_title_of(&at), at);
25122        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25123        assert!(over.ends_with("..."), "{over}");
25124        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25125    }
25126
25127    #[test]
25128    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25129        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25130        let t = long_title_of(&line);
25131        assert!(t.ends_with("..."), "{t}");
25132        assert!(t.is_ascii(), "{t}");
25133    }
25134
25135    #[test]
25136    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25137        let line = format!(
25138            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25139            "plus more filler words ".repeat(20)
25140        );
25141        let t = long_title_of(&line);
25142        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25143    }
25144
25145    #[test]
25146    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25147        let line = format!("\n\n# {}", "title words ".repeat(40));
25148        let state = state_with_summary(&line, "- nothing");
25149        let m = pr_message(&state, 'A');
25150        assert!(m.title.starts_with("title words"), "{}", m.title);
25151        assert_eq!(
25152            land::merge_subject(&m.title, &landing_subject_source(&state)),
25153            m.title
25154        );
25155        // An operator's rename wins untouched.
25156        assert_eq!(
25157            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25158            "feat: renamed by hand"
25159        );
25160    }
25161
25162    #[tokio::test]
25163    async fn github_text_rewrite_is_bounded_and_falls_back() {
25164        crate::run::pin_test_home();
25165        for (reply, accepted) in [
25166            (
25167                "TITLE: fix: retries\nAdd retries for failed requests.",
25168                true,
25169            ),
25170            (
25171                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25172                false,
25173            ),
25174            (
25175                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25176                true,
25177            ),
25178            (
25179                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25180                true,
25181            ),
25182            (
25183                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25184                true,
25185            ),
25186            (
25187                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25188                false,
25189            ),
25190            ("TITLE: fix: retries\n", false),
25191        ] {
25192            let dir = tempfile::tempdir().unwrap();
25193            let mut runner = runner_at(RunStatus::Gating);
25194            runner.state = state_with_summary(
25195                "add retries",
25196                "TITLE: fix: retries\n日本語の説明を書きます。",
25197            );
25198            runner.state.repo = dir.path().to_owned();
25199            runner.state.candidates[0].worktree = dir.path().to_owned();
25200            let mut author = spec("alpha");
25201            author.command = vec![
25202                "sh".into(),
25203                "-c".into(),
25204                "printf '%s' \"$REWRITE_REPLY\"".into(),
25205            ];
25206            author.env.insert("REWRITE_REPLY".into(), reply.into());
25207            runner.state.config.agents = vec![author];
25208            seed_public_summary(&mut runner);
25209            let winner = runner.state.candidates[0].clone();
25210            let first = runner
25211                .guarded_pr_message(&winner, None, true)
25212                .await
25213                .unwrap();
25214            let message = if accepted {
25215                first.expect("a passing rewrite never asks")
25216            } else {
25217                // Withheld: the run parks on a question and posts nothing yet.
25218                assert!(first.is_none());
25219                assert!(runner.state.parked);
25220                let store = ask::Questions::open();
25221                let asked: Vec<_> = store
25222                    .list()
25223                    .into_iter()
25224                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25225                    .collect();
25226                assert_eq!(asked.len(), 1);
25227                assert!(!asked[0].detail.contains("secret"));
25228                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25229                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25230                assert_eq!(
25231                    asked[0]
25232                        .choices
25233                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25234                    rewrite.is_some()
25235                );
25236                // Silence: the question lapses and the neutral text is used,
25237                // without a second rewrite call or a second question.
25238                store
25239                    .update(&asked[0].id, |q| {
25240                        q.abandon("test");
25241                        Ok(())
25242                    })
25243                    .unwrap();
25244                let again = runner
25245                    .guarded_pr_message(&winner, None, true)
25246                    .await
25247                    .unwrap()
25248                    .expect("an abandoned question falls back");
25249                let n = store
25250                    .list()
25251                    .into_iter()
25252                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25253                    .count();
25254                assert_eq!(n, 1, "asked once per rejected text");
25255                again
25256            };
25257            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25258            assert!(!message.body.contains("secret"));
25259            assert!(!message.body.contains("prefix"));
25260            assert!(!message.title.contains("secret"));
25261            assert_eq!(
25262                message.body.contains("Add retries for failed requests."),
25263                accepted
25264            );
25265            assert_eq!(
25266                runner.state.seats["github-text-rewrite"].turns, 1,
25267                "only one rewrite invocation"
25268            );
25269            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25270            if accepted {
25271                assert!(runner.state.github_text.is_none());
25272                assert!(!runner.state.parked);
25273                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25274                assert!(message.body.contains("## Final verification"));
25275                assert!(message.body.contains("Evidence: final diff"));
25276                assert!(
25277                    message
25278                        .body
25279                        .contains(&format!("magi:run/{}", runner.state.id))
25280                );
25281            }
25282            if !accepted {
25283                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25284                assert!(
25285                    message
25286                        .body
25287                        .contains(&format!("magi:run/{}", runner.state.id))
25288                );
25289            }
25290        }
25291    }
25292
25293    fn scripted(id: &str, reply: &str) -> AgentSpec {
25294        let mut a = spec(id);
25295        a.command = vec![
25296            "sh".into(),
25297            "-c".into(),
25298            "printf '%s' \"$REWRITE_REPLY\"".into(),
25299        ];
25300        a.env.insert("REWRITE_REPLY".into(), reply.into());
25301        a
25302    }
25303
25304    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25305    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25306
25307    /// Gate tests inject generated public output, not internal reports.
25308    fn seed_public_summary(runner: &mut Runner) {
25309        let repo = &runner.state.repo;
25310        let g = |args: &[&str]| {
25311            let out = std::process::Command::new("git")
25312                .args(args)
25313                .current_dir(repo)
25314                .quiet()
25315                .output()
25316                .unwrap();
25317            assert!(out.status.success(), "git {args:?}");
25318            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25319        };
25320        g(&["init", "-q", "-b", "main"]);
25321        g(&[
25322            "-c",
25323            "user.name=Test",
25324            "-c",
25325            "user.email=test@example.invalid",
25326            "commit",
25327            "-q",
25328            "--allow-empty",
25329            "-m",
25330            "feat: fixture",
25331        ]);
25332        let head = g(&["rev-parse", "HEAD"]);
25333        g(&["update-ref", "refs/remotes/origin/main", &head]);
25334        let evidence = crate::pr_outcome::summary_evidence(
25335            &runner.state,
25336            crate::pr_outcome::FinalHead::At(&head),
25337        );
25338        let generated = &runner.state.candidates[0].summary;
25339        runner.state.change_summary = Some(crate::run::ChangeSummary {
25340            base: head.clone(),
25341            head,
25342            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25343            title: summary_title(generated).unwrap(),
25344            body: summary_without_title(generated),
25345        });
25346    }
25347
25348    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25349        let mut runner = runner_at(RunStatus::Gating);
25350        runner.state = state_with_summary("add retries", JA_SUMMARY);
25351        if review_only {
25352            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25353        }
25354        runner.state.repo = dir.to_owned();
25355        runner.state.candidates[0].worktree = dir.to_owned();
25356        runner.state.config.agents = agents;
25357        seed_public_summary(&mut runner);
25358        runner
25359    }
25360
25361    fn gate_questions(runner: &Runner) -> usize {
25362        ask::Questions::open()
25363            .list()
25364            .into_iter()
25365            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25366            .count()
25367    }
25368
25369    #[tokio::test]
25370    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25371        crate::run::pin_test_home();
25372        let dir = tempfile::tempdir().unwrap();
25373        let mut runner = rewrite_runner(
25374            dir.path(),
25375            true,
25376            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25377        );
25378        runner.state.config.roles.language_judge =
25379            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25380        let winner = runner.state.candidates[0].clone();
25381        let msg = runner
25382            .guarded_pr_message(&winner, None, true)
25383            .await
25384            .unwrap()
25385            .expect("an English rewrite posts without asking");
25386        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25387        assert!(msg.body.contains("<details>kept</details>"));
25388        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25389        assert_eq!(gate_questions(&runner), 0);
25390        assert!(runner.state.github_text.is_none());
25391        assert!(!runner.state.seats.contains_key("impl-A"));
25392        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25393    }
25394
25395    #[tokio::test]
25396    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25397        crate::run::pin_test_home();
25398        let dir = tempfile::tempdir().unwrap();
25399        let mut runner = rewrite_runner(
25400            dir.path(),
25401            false,
25402            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25403        );
25404        runner.state.config.roles.language_judge =
25405            Some(crate::config::AgentChoice::One("beta".into()));
25406        runner.state.seats.insert(
25407            "impl-A".into(),
25408            SeatState::new("impl-A", "alpha", runner.state.seed),
25409        );
25410        let winner = runner.state.candidates[0].clone();
25411        let msg = runner
25412            .guarded_pr_message(&winner, None, true)
25413            .await
25414            .unwrap()
25415            .expect("rewritten");
25416        assert!(msg.body.contains("<details>kept</details>"));
25417        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25418        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25419        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25420    }
25421
25422    #[tokio::test]
25423    async fn rewrite_reuses_a_resumable_implementer_session() {
25424        crate::run::pin_test_home();
25425        let dir = tempfile::tempdir().unwrap();
25426        let mut runner = rewrite_runner(
25427            dir.path(),
25428            false,
25429            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25430        );
25431        runner.state.config.roles.language_judge =
25432            Some(crate::config::AgentChoice::One("beta".into()));
25433        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25434        seat.turns = 1;
25435        runner.state.seats.insert("impl-A".into(), seat);
25436        let winner = runner.state.candidates[0].clone();
25437        runner
25438            .guarded_pr_message(&winner, None, true)
25439            .await
25440            .unwrap()
25441            .expect("rewritten");
25442        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25443        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25444    }
25445
25446    #[tokio::test]
25447    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25448        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25449        // session, was out of quota, and nothing else was asked.
25450        crate::run::pin_test_home();
25451        let dir = tempfile::tempdir().unwrap();
25452        let mut exhausted = spec("alpha");
25453        exhausted.command = vec!["false".into()];
25454        let mut runner = rewrite_runner(
25455            dir.path(),
25456            false,
25457            vec![exhausted, scripted("beta", EN_REWRITE)],
25458        );
25459        // The implementer's own agent is in the role too: it is not asked twice.
25460        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25461            "alpha".into(),
25462            "beta".into(),
25463        ]));
25464        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25465        seat.turns = 1;
25466        runner.state.seats.insert("impl-A".into(), seat);
25467        let winner = runner.state.candidates[0].clone();
25468        let msg = runner
25469            .guarded_pr_message(&winner, None, true)
25470            .await
25471            .unwrap()
25472            .expect("the role rewrites after the implementer fails");
25473        assert!(msg.body.contains("`src/net.rs`"));
25474        assert_eq!(
25475            runner.state.seats["impl-A"].turns, 2,
25476            "the implementer was tried once"
25477        );
25478        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25479        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25480    }
25481
25482    #[tokio::test]
25483    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25484        crate::run::pin_test_home();
25485        let dir = tempfile::tempdir().unwrap();
25486        let mut broken = spec("bad");
25487        broken.command = vec!["false".into()];
25488        let mut runner = rewrite_runner(
25489            dir.path(),
25490            true,
25491            vec![
25492                broken,
25493                scripted("noformat", "Add retries."),
25494                scripted("good", EN_REWRITE),
25495            ],
25496        );
25497        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25498            "bad".into(),
25499            "noformat".into(),
25500            "good".into(),
25501        ]));
25502        let winner = runner.state.candidates[0].clone();
25503        let msg = runner
25504            .guarded_pr_message(&winner, None, true)
25505            .await
25506            .unwrap()
25507            .expect("the third agent rewrites");
25508        assert!(msg.body.contains("`src/net.rs`"));
25509        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25510        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25511    }
25512
25513    #[tokio::test]
25514    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25515        crate::run::pin_test_home();
25516        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25517        for (agents, role, saved) in [
25518            (
25519                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25520                Some("beta"),
25521                true,
25522            ),
25523            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25524            (Vec::new(), None, false),
25525        ] {
25526            let dir = tempfile::tempdir().unwrap();
25527            let mut runner = rewrite_runner(dir.path(), true, agents);
25528            runner.state.config.roles.language_judge =
25529                role.map(|r| crate::config::AgentChoice::One(r.into()));
25530            let winner = runner.state.candidates[0].clone();
25531            let first = runner
25532                .guarded_pr_message(&winner, None, true)
25533                .await
25534                .unwrap();
25535            assert!(first.is_none(), "withheld text parks the run");
25536            assert!(runner.state.parked);
25537            assert_eq!(gate_questions(&runner), 1);
25538            let g = runner.state.github_text.as_ref().unwrap();
25539            assert_eq!(g.rewrite.is_some(), saved);
25540            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25541        }
25542    }
25543
25544    #[tokio::test]
25545    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25546        crate::run::pin_test_home();
25547        let dir = tempfile::tempdir().unwrap();
25548        let mut runner = runner_at(RunStatus::Gating);
25549        runner.state =
25550            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25551        runner.state.repo = dir.path().to_owned();
25552        runner.state.candidates[0].worktree = dir.path().to_owned();
25553        let mut author = spec("alpha");
25554        author.command = vec![
25555            "sh".into(),
25556            "-c".into(),
25557            "printf '%s' \"$REWRITE_REPLY\"".into(),
25558        ];
25559        author.env.insert(
25560            "REWRITE_REPLY".into(),
25561            format!(
25562                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25563                "English sentence. ".repeat(600)
25564            ),
25565        );
25566        runner.state.config.agents = vec![author];
25567        seed_public_summary(&mut runner);
25568        let winner = runner.state.candidates[0].clone();
25569        assert!(
25570            runner
25571                .guarded_pr_message(&winner, None, true)
25572                .await
25573                .unwrap()
25574                .is_none()
25575        );
25576        let record = runner.state.github_text.clone().unwrap();
25577        let rewrite = record.rewrite.clone().unwrap();
25578        assert_eq!(rewrite.failed, ["body-language"]);
25579        assert!(
25580            rewrite
25581                .body
25582                .ends_with(&format!("magi:run/{}", runner.state.id))
25583        );
25584        let store = ask::Questions::open();
25585        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25586        assert!(
25587            q.choices
25588                .contains(&crate::github_text::USE_REWRITE.to_owned())
25589        );
25590        for label in [
25591            "ORIGINAL",
25592            "FALLBACK",
25593            "REWRITE",
25594            "Rules still failed: body-language",
25595            "truncated",
25596        ] {
25597            assert!(q.detail.contains(label), "{label}");
25598        }
25599        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25600            &runner.state,
25601            &crate::github_text::artifact_name(&record.fingerprint),
25602        ))
25603        .unwrap();
25604        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25605        // Restart from serialized state, then retry after a bad owner title.
25606        runner.state =
25607            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25608        store
25609            .update(&q.id, |q| {
25610                q.say("まだ日本語")?;
25611                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25612            })
25613            .unwrap();
25614        assert!(
25615            runner
25616                .guarded_pr_message(&winner, None, true)
25617                .await
25618                .unwrap()
25619                .is_none()
25620        );
25621        let retry = runner.state.github_text.as_ref().unwrap();
25622        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25623        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25624        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25625        assert!(
25626            q.posting_comparison
25627                .as_ref()
25628                .unwrap()
25629                .matches_detail(&q.detail)
25630        );
25631        store
25632            .update(&q.id, |q| {
25633                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25634            })
25635            .unwrap();
25636        let message = runner
25637            .guarded_pr_message(&winner, None, true)
25638            .await
25639            .unwrap()
25640            .unwrap();
25641        assert_eq!(message.title, rewrite.title);
25642        assert_eq!(message.body, rewrite.body);
25643        assert_eq!(
25644            runner.state.github_text.as_ref().unwrap().choice,
25645            Some(GithubTextChoice::Rewrite)
25646        );
25647        let again = runner
25648            .guarded_pr_message(&winner, None, true)
25649            .await
25650            .unwrap()
25651            .unwrap();
25652        assert_eq!(again.title, message.title);
25653        assert_eq!(again.body, message.body);
25654        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25655        assert!(
25656            !runner
25657                .state
25658                .events
25659                .iter()
25660                .any(|e| e.message.contains(&rewrite.title)
25661                    || e.message.contains("English sentence."))
25662        );
25663    }
25664
25665    #[tokio::test]
25666    async fn historical_posting_reply_never_expires_into_fallback() {
25667        crate::run::pin_test_home();
25668        let dir = tempfile::tempdir().unwrap();
25669        let mut runner = runner_at(RunStatus::Gating);
25670        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25671        runner.state.repo = dir.path().to_owned();
25672        runner.state.candidates[0].worktree = dir.path().to_owned();
25673        seed_public_summary(&mut runner);
25674        let winner = runner.state.candidates[0].clone();
25675        assert!(
25676            runner
25677                .guarded_pr_message(&winner, None, true)
25678                .await
25679                .unwrap()
25680                .is_none()
25681        );
25682        let id = runner
25683            .state
25684            .github_text
25685            .as_ref()
25686            .unwrap()
25687            .question
25688            .clone()
25689            .unwrap();
25690        let store = ask::Questions::open();
25691        let mut q = store.get(&id).unwrap();
25692        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25693        q.answer(ask::Answer::Choice(
25694            crate::github_text::POST_ORIGINAL.into(),
25695        ))
25696        .unwrap();
25697        q.answer_delivered = true;
25698        store.put(&mut q).unwrap();
25699        let source = std::fs::read(store.path_of(&id)).unwrap();
25700        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25701        std::fs::create_dir_all(&migration).unwrap();
25702        std::fs::write(
25703            migration.join("state.json"),
25704            serde_json::to_vec(&serde_json::json!({
25705                "schema": 1, "sources": [id], "pending": [id]
25706            }))
25707            .unwrap(),
25708        )
25709        .unwrap();
25710        for _ in 0..2 {
25711            assert!(
25712                runner
25713                    .guarded_pr_message(&winner, None, true)
25714                    .await
25715                    .unwrap()
25716                    .is_none()
25717            );
25718            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25719            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25720        }
25721        let home = crate::run::home();
25722        crate::task_chat::sweep(
25723            &crate::queue::Queue::at(home.join("queue")),
25724            &crate::talk::Talks::at(home.join("talks")),
25725            &store,
25726            &home,
25727        );
25728        let outbox = crate::task_inquiry::Outbox::at(&home);
25729        outbox
25730            .update_decision(&id, |d| {
25731                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
25732                d.source_answer_at = q.answered_at;
25733                Ok(true)
25734            })
25735            .unwrap();
25736        outbox
25737            .settle(
25738                &id,
25739                "owner-chat",
25740                "Owner confirms no publication remains necessary",
25741                None,
25742            )
25743            .unwrap();
25744        assert!(
25745            runner
25746                .guarded_pr_message(&winner, None, true)
25747                .await
25748                .unwrap()
25749                .is_none()
25750        );
25751        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25752        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25753    }
25754
25755    #[tokio::test]
25756    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25757        crate::run::pin_test_home();
25758        let dir = tempfile::tempdir().unwrap();
25759        let mut runner = runner_at(RunStatus::Gating);
25760        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25761        runner.state.repo = dir.path().to_owned();
25762        runner.state.candidates[0].worktree = dir.path().to_owned();
25763        seed_public_summary(&mut runner);
25764        let winner = runner.state.candidates[0].clone();
25765        assert!(
25766            runner
25767                .guarded_pr_message(&winner, None, true)
25768                .await
25769                .unwrap()
25770                .is_none()
25771        );
25772        let record = runner.state.github_text.as_ref().unwrap();
25773        assert!(record.rewrite.is_none());
25774        // Records written before the additive field deserialize with no rewrite.
25775        let mut old = serde_json::to_value(record).unwrap();
25776        old.as_object_mut().unwrap().remove("rewrite");
25777        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25778        assert!(old.rewrite.is_none());
25779        let id = record.question.clone().unwrap();
25780        ask::Questions::open()
25781            .update(&id, |q| {
25782                q.choices.push(crate::github_text::USE_REWRITE.into());
25783                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25784            })
25785            .unwrap();
25786        let message = runner
25787            .guarded_pr_message(&winner, None, true)
25788            .await
25789            .unwrap()
25790            .unwrap();
25791        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25792        assert_eq!(
25793            runner.state.github_text.as_ref().unwrap().choice,
25794            Some(GithubTextChoice::Fallback)
25795        );
25796    }
25797
25798    #[tokio::test]
25799    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25800        crate::run::pin_test_home();
25801        let dir = tempfile::tempdir().unwrap();
25802        let mut runner = runner_at(RunStatus::Gating);
25803        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25804        runner.state.repo = dir.path().to_owned();
25805        runner.state.candidates[0].worktree = dir.path().to_owned();
25806        seed_public_summary(&mut runner);
25807        let winner = runner.state.candidates[0].clone();
25808        assert!(
25809            runner
25810                .guarded_pr_message(&winner, None, true)
25811                .await
25812                .unwrap()
25813                .is_none()
25814        );
25815        let store = ask::Questions::open();
25816        let find = |run: &str| {
25817            store
25818                .list()
25819                .into_iter()
25820                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
25821                .unwrap()
25822        };
25823        let run = runner.state.id.clone();
25824        let q = find(&run);
25825        let fp = runner
25826            .state
25827            .github_text
25828            .as_ref()
25829            .unwrap()
25830            .fingerprint
25831            .clone();
25832        let name = crate::github_text::artifact_name(&fp);
25833        let path = crate::run::artifact_path(&runner.state, &name);
25834        assert!(q.detail.contains(&path.display().to_string()));
25835        assert!(q.detail.contains("title-language: title"));
25836        let saved = std::fs::read_to_string(&path).expect("artifact written");
25837        assert!(saved.contains("日本語のタイトル"));
25838        assert!(q.cwd.is_none());
25839        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
25840        // A bad replacement is refused and asked about once more.
25841        let say = |id: &str, text: &str, choice: &str| {
25842            store
25843                .update(id, |q| {
25844                    q.thread.push(ask::Turn {
25845                        who: ask::Who::Operator,
25846                        body: text.to_owned(),
25847                        at: jiff::Timestamp::now(),
25848                        note: None,
25849                    });
25850                    q.answer(ask::Answer::Choice(choice.to_owned()))
25851                })
25852                .unwrap();
25853        };
25854        say(&q.id, "まだ日本語", "use my text");
25855        assert!(
25856            runner
25857                .guarded_pr_message(&winner, None, true)
25858                .await
25859                .unwrap()
25860                .is_none()
25861        );
25862        let second = find(&run);
25863        assert_ne!(second.id, q.id);
25864        assert!(second.detail.contains("did not pass"));
25865        // The retry still compares the original text; the rejected
25866        // replacement is named by category only.
25867        assert!(second.detail.contains("日本語のタイトル"));
25868        assert!(!second.detail.contains("まだ日本語"));
25869        assert!(second.detail.contains(&path.display().to_string()));
25870        say(&second.id, "fix: retry failed requests", "use my text");
25871        let message = runner
25872            .guarded_pr_message(&winner, None, true)
25873            .await
25874            .unwrap()
25875            .expect("a vetted replacement is posted");
25876        assert_eq!(message.title, "fix: retry failed requests");
25877        assert_eq!(
25878            runner
25879                .state
25880                .github_text
25881                .as_ref()
25882                .unwrap()
25883                .chosen_title
25884                .as_deref(),
25885            Some("fix: retry failed requests")
25886        );
25887        assert!(runner.state.github_text.as_ref().unwrap().resolved);
25888        // Resumed again: the saved decision is applied, nothing is re-asked.
25889        let again = runner
25890            .guarded_pr_message(&winner, None, true)
25891            .await
25892            .unwrap()
25893            .unwrap();
25894        assert_eq!(again.title, message.title);
25895        assert_eq!(
25896            store
25897                .list()
25898                .into_iter()
25899                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
25900                .count(),
25901            2
25902        );
25903    }
25904
25905    #[test]
25906    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
25907        // What magi itself writes stays English under any configured language,
25908        // so a future localisation of these headings fails here. (The agents'
25909        // own text is also checked by the posting gate.)
25910        let mut state = state_with_summary(
25911            "add retries",
25912            "TITLE: fix(web): batch reads\n- reads run.json once",
25913        );
25914        state.config.graph.language = "ja".to_owned();
25915        let m = pr_message(&state, 'A');
25916        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
25917        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
25918
25919        // The task is the operator's own text: it goes in untouched, and the
25920        // fallback title (no summary) may be in its language too.
25921        let task = "今回やってほしいこと: results projector を直す";
25922        let mut state = state_with_summary(task, "- no title line");
25923        state.config.graph.language = "ja".to_owned();
25924        let m = pr_message(&state, 'A');
25925        assert_eq!(
25926            m.title,
25927            format!("chore: land candidate A of run {}", state.id)
25928        );
25929        assert!(
25930            m.body.contains(&format!(
25931                "<summary>Original task</summary>\n\n{task}\n\n</details>"
25932            )),
25933            "{}",
25934            m.body
25935        );
25936    }
25937
25938    #[test]
25939    fn pr_message_scrubs_home_paths_and_addresses() {
25940        let state = state_with_summary(
25941            "fix it in /Users/someone/src/x",
25942            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
25943        );
25944        let m = pr_message(&state, 'A');
25945        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
25946            assert!(!m.body.contains(leak), "{}", m.body);
25947        }
25948        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
25949    }
25950
25951    #[test]
25952    fn pr_message_survives_a_task_that_closes_details() {
25953        let state = state_with_summary("a </details> b", "TITLE: fix: x");
25954        let m = pr_message(&state, 'A');
25955        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
25956    }
25957
25958    #[test]
25959    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
25960        let cmd = manual_merge_command(
25961            MergeStyle::Squash,
25962            Path::new("/repo"),
25963            "b",
25964            "fix: \"quoted\" $(x) `y`\n\nbody",
25965        );
25966        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
25967    }
25968
25969    #[test]
25970    fn manual_merge_command_matches_the_configured_style() {
25971        let repo = Path::new("/repo");
25972        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
25973
25974        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
25975        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
25976
25977        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
25978        assert_eq!(
25979            squash,
25980            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
25981             \"Merge magi run 0832 (candidate A)\""
25982        );
25983
25984        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
25985        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
25986    }
25987
25988    #[test]
25989    fn a_nudge_gets_a_quarter_of_the_budget() {
25990        // The judge and implement budgets magi ships with.
25991        assert_eq!(retry_budget(secs(1200), true), secs(300));
25992        assert_eq!(retry_budget(secs(3600), true), secs(900));
25993    }
25994
25995    #[test]
25996    fn a_resent_prompt_keeps_the_whole_budget() {
25997        // The seat kept no context, so the retry is the original job again and
25998        // shortening it would only guarantee a second failure.
25999        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26000        assert_eq!(retry_budget(secs(60), false), secs(60));
26001    }
26002
26003    #[test]
26004    fn the_floor_never_exceeds_the_original_budget() {
26005        // A short configured timeout must not be *raised* by the floor: the
26006        // operator asked for a bound, and a retry may not outlast the attempt
26007        // it is retrying.
26008        assert_eq!(retry_budget(secs(60), true), secs(60));
26009        assert_eq!(retry_budget(secs(480), true), secs(120));
26010        assert_eq!(retry_budget(secs(0), true), secs(0));
26011    }
26012
26013    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26014        agent::CommandEvidence {
26015            id: "item1".to_owned(),
26016            description: "cargo test".to_owned(),
26017            exit_code,
26018            result_summary: String::new(),
26019            source: "codex".to_owned(),
26020        }
26021    }
26022
26023    #[test]
26024    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26025        // No evidence is not the same fact as unconfirmed evidence: a
26026        // backend with no adapter, or a reply that ran no commands at all,
26027        // must not be misread as carrying a dangling job.
26028        assert!(!has_unconfirmed_command(&[]));
26029    }
26030
26031    #[test]
26032    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26033        // Deliberately not a check on the exit code's *value*: a fixer
26034        // legitimately runs something that fails mid-iteration before it
26035        // succeeds, and that must never by itself reopen a valid report.
26036        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26037        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26038        assert!(!has_unconfirmed_command(&[
26039            evidence(Some(0)),
26040            evidence(Some(101))
26041        ]));
26042    }
26043
26044    #[test]
26045    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26046        assert!(has_unconfirmed_command(&[
26047            evidence(Some(0)),
26048            evidence(None)
26049        ]));
26050    }
26051
26052    fn evidence_with(
26053        description: &str,
26054        exit_code: Option<i32>,
26055        result_summary: &str,
26056    ) -> agent::CommandEvidence {
26057        agent::CommandEvidence {
26058            id: "item1".to_owned(),
26059            description: description.to_owned(),
26060            exit_code,
26061            result_summary: result_summary.to_owned(),
26062            source: "codex".to_owned(),
26063        }
26064    }
26065
26066    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26067        format!(
26068            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{commit}","method":"git merge-base --is-ancestor {commit} HEAD","observed":"exit 0; {commit} is on base","passed":true}},{{"id":"c2","kind":"test","target":"{test_name}","method":"cargo test --lib {test_name}","observed":"test result: ok. 1 passed; 0 failed","passed":true}}],"unresolved":[]}}"#
26069        )
26070    }
26071
26072    #[test]
26073    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26074        let text = valid_noop_summary("b32cfc4", "retry_test");
26075        let claim = verified_noop_claim(true, &[], &text)
26076            .expect("valid structured report with no CommandEvidence must be accepted");
26077        assert!(claim.contains("b32cfc4"), "{claim}");
26078        assert!(claim.contains("retry_test"), "{claim}");
26079    }
26080
26081    #[test]
26082    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26083        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26084        assert!(verified_noop_claim(true, &[], regression).is_none());
26085        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26086        assert!(err.contains("single JSON object"), "{err}");
26087
26088        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26089        assert!(verified_noop_claim(true, &[], legacy).is_none());
26090    }
26091
26092    #[test]
26093    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26094        // A timeout or a bad exit code reads as the ordinary loss it is,
26095        // whatever the reply's own structured JSON claims.
26096        let text = valid_noop_summary("b32cfc4", "retry_test");
26097        assert!(verified_noop_claim(false, &[], &text).is_none());
26098    }
26099
26100    #[test]
26101    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26102        let text = valid_noop_summary("b32cfc4", "retry_test");
26103        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26104        // A matching confirmed command alongside the marker is fine.
26105        assert!(
26106            verified_noop_claim(
26107                true,
26108                &[evidence_with(
26109                    "cargo test --lib retry_test",
26110                    Some(0),
26111                    "1 passed"
26112                )],
26113                &text
26114            )
26115            .is_some()
26116        );
26117    }
26118
26119    #[test]
26120    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26121     {
26122        let text = valid_noop_summary("b32cfc4", "retry_test");
26123
26124        // Unrelated passing command cannot substantiate a claimed test run.
26125        let err = evaluate_noop_claim(
26126            true,
26127            &[evidence_with("git status", Some(0), "nothing to commit")],
26128            &text,
26129        )
26130        .unwrap_err();
26131        assert!(err.contains("no matching command was recorded"), "{err}");
26132
26133        // Final matching command exited non-zero -> rejected even if an
26134        // unrelated command succeeded afterward.
26135        let err = evaluate_noop_claim(
26136            true,
26137            &[
26138                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26139                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26140                evidence_with("rg retry_test src", Some(0), "retry_test"),
26141            ],
26142            &text,
26143        )
26144        .unwrap_err();
26145        assert!(err.contains("exited with"), "{err}");
26146
26147        // A different invocation containing the entire method is not a rerun.
26148        let err = evaluate_noop_claim(
26149            true,
26150            &[evidence_with(
26151                "echo 'cargo test --lib retry_test'",
26152                Some(0),
26153                "retry_test",
26154            )],
26155            &text,
26156        )
26157        .unwrap_err();
26158        assert!(err.contains("no matching command was recorded"), "{err}");
26159
26160        // Mid-investigation failure followed by a passing re-run -> accepted!
26161        assert!(
26162            verified_noop_claim(
26163                true,
26164                &[
26165                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26166                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26167                ],
26168                &text
26169            )
26170            .is_some()
26171        );
26172    }
26173
26174    #[test]
26175    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26176        let text = valid_noop_summary("b32cfc4", "retry_test");
26177        let method = "cargo test --lib retry_test";
26178        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26179        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26180        let failed =
26181            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26182        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26183        for output in [empty, ignored, failed] {
26184            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26185                .unwrap_err();
26186            assert!(err.contains("failure or no passing tests"), "{err}");
26187        }
26188        // Multiple harnesses can legitimately include a filtered-out suite.
26189        let mixed = format!("{passed}\n{empty}");
26190        assert!(
26191            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26192        );
26193        // A later real rerun of the same command can establish success.
26194        assert!(
26195            verified_noop_claim(
26196                true,
26197                &[
26198                    evidence_with(method, Some(0), empty),
26199                    evidence_with(method, Some(0), passed),
26200                ],
26201                &text,
26202            )
26203            .is_some()
26204        );
26205    }
26206
26207    #[test]
26208    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26209        let text = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"README includes the expected header","satisfied":true,"evidence":["p1"]}],"checks":[{"id":"p1","kind":"path","target":"README.md","method":"rg expected README.md","observed":"expected header found","passed":true}],"unresolved":[]}"#;
26210        let failed = evidence_with("rg expected README.md", Some(1), "");
26211        let unrelated = evidence_with("cat README.md", Some(0), "README");
26212        let err =
26213            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26214        assert!(err.contains("exited with"), "{err}");
26215        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26216        assert!(
26217            evaluate_noop_claim(
26218                true,
26219                &[
26220                    failed,
26221                    evidence_with("rg expected README.md", Some(0), "expected header"),
26222                ],
26223                text,
26224            )
26225            .unwrap()
26226            .is_some()
26227        );
26228    }
26229
26230    #[test]
26231    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26232        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26233        assert!(matches!(
26234            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26235            Ok(None)
26236        ));
26237    }
26238
26239    #[tokio::test]
26240    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26241        let tmp = tempfile::tempdir().unwrap();
26242        let repo = tmp.path().join("repo");
26243        std::fs::create_dir_all(&repo).unwrap();
26244        let run_git = |args: &[&str]| {
26245            let out = std::process::Command::new("git")
26246                .args(args)
26247                .current_dir(&repo)
26248                .output()
26249                .unwrap();
26250            assert!(out.status.success(), "git {args:?} failed");
26251            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26252        };
26253        run_git(&["init", "-b", "main"]);
26254        run_git(&["config", "user.name", "test"]);
26255        run_git(&["config", "user.email", "test@example.com"]);
26256        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26257        run_git(&["add", "-A"]);
26258        run_git(&["commit", "-m", "base commit"]);
26259        let base = run_git(&["rev-parse", "HEAD"]);
26260
26261        // Create a commit on a side branch not on `base`.
26262        run_git(&["checkout", "-b", "side"]);
26263        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26264        run_git(&["add", "-A"]);
26265        run_git(&["commit", "-m", "side commit"]);
26266        let side = run_git(&["rev-parse", "HEAD"]);
26267        run_git(&["checkout", "main"]);
26268
26269        // Valid commit on base + existing path -> Accepted.
26270        let valid = format!(
26271            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"readme exists","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{base}","method":"git merge-base --is-ancestor {base} HEAD","observed":"exit 0; base commit is on main","passed":true}},{{"id":"c2","kind":"path","target":"README.md:1","method":"read README.md","observed":"contains expected greeting","passed":true}}],"unresolved":[]}}"#
26272        );
26273        assert!(matches!(
26274            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26275            NoopClaimVerdict::Accepted
26276        ));
26277
26278        // Non-existent commit SHA -> Rejected.
26279        let missing_sha = valid.replace(&base, "deadbeef");
26280        assert!(matches!(
26281            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26282            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26283        ));
26284
26285        // Commit on unmerged side branch -> Rejected.
26286        let side_sha = valid.replace(&base, &side);
26287        assert!(matches!(
26288            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26289            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26290        ));
26291
26292        // Missing file path -> Rejected.
26293        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26294        assert!(matches!(
26295            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26296            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26297        ));
26298    }
26299
26300    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26301    /// pair, in order, labelled A, B, C, ...
26302    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26303        runner.state.candidates = shape
26304            .iter()
26305            .enumerate()
26306            .map(|(i, &(empty, verified))| {
26307                let (summary, verified_noop) = match verified {
26308                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26309                    None => (String::new(), None),
26310                };
26311                Candidate {
26312                    index: i,
26313                    label: (b'A' + i as u8) as char,
26314                    agent: "sonnet".to_owned(),
26315                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26316                    worktree: PathBuf::from(format!("/wt/{i}")),
26317                    summary,
26318                    stat: String::new(),
26319                    files: 0,
26320                    commits: 0,
26321                    empty,
26322                    failed: None,
26323                    verified_noop,
26324                    duration_ms: 0,
26325                    folded: false,
26326                }
26327            })
26328            .collect();
26329    }
26330
26331    #[test]
26332    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26333        ask_test_home();
26334        let mut runner = runner_at(RunStatus::Implementing);
26335        let a = valid_noop_summary("b32cfc4", "test_a");
26336        let b = valid_noop_summary("b32cfc4", "test_b");
26337        set_candidates(
26338            &mut runner,
26339            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26340        );
26341
26342        runner
26343            .after_implement()
26344            .expect("a verified no-op is not an error");
26345
26346        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26347    }
26348
26349    #[test]
26350    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26351        ask_test_home();
26352        let mut runner = runner_at(RunStatus::Implementing);
26353        let a = valid_noop_summary("b32cfc4", "test_a");
26354        // Candidate A declares a verified no-op; candidate B simply wrote
26355        // nothing and said nothing about why. One candidate's claim is not
26356        // the whole run's agreement.
26357        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26358
26359        let err = runner
26360            .after_implement()
26361            .expect_err("an unverified empty candidate must still fail the run");
26362
26363        assert!(
26364            err.to_string().contains("no candidate produced a change"),
26365            "{err}"
26366        );
26367        assert_eq!(runner.state.status, RunStatus::Failed);
26368    }
26369
26370    #[test]
26371    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26372        ask_test_home();
26373        let mut runner = runner_at(RunStatus::Implementing);
26374        // Simulate a saved incomplete run that stored a legacy/incomplete
26375        // `verified_noop` string before this build's strict contract.
26376        set_candidates(
26377            &mut runner,
26378            &[(
26379                true,
26380                Some(
26381                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26382                ),
26383            )],
26384        );
26385
26386        let err = runner
26387            .after_implement()
26388            .expect_err("invalid saved noop claim must fail the run");
26389        assert!(
26390            err.to_string().contains("no candidate produced a change"),
26391            "{err}"
26392        );
26393        assert_eq!(runner.state.status, RunStatus::Failed);
26394        assert!(runner.state.candidates[0].verified_noop.is_none());
26395        assert!(runner.state.candidates[0].failed.is_some());
26396        assert!(runner.state.events.iter().any(|e| {
26397            e.message
26398                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26399        }));
26400    }
26401
26402    #[test]
26403    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26404        ask_test_home();
26405        let mut runner = runner_at(RunStatus::Implementing);
26406        let a = valid_noop_summary("b32cfc4", "test_a");
26407        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26408        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26409
26410        let err = runner
26411            .after_implement()
26412            .expect_err("a failed candidate must never settle as verified no-op");
26413        assert!(err.to_string().contains("no candidate produced a change"));
26414        assert_eq!(runner.state.status, RunStatus::Failed);
26415        assert!(runner.state.candidates[0].verified_noop.is_none());
26416    }
26417
26418    #[test]
26419    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26420        ask_test_home();
26421        let mut runner = runner_at(RunStatus::Implementing);
26422        set_candidates(&mut runner, &[(true, None), (true, None)]);
26423
26424        let err = runner
26425            .after_implement()
26426            .expect_err("no candidate declared anything; this is an ordinary failure");
26427
26428        assert!(
26429            err.to_string().contains("no candidate produced a change"),
26430            "{err}"
26431        );
26432        assert_eq!(runner.state.status, RunStatus::Failed);
26433    }
26434}
26435
26436/// A graft rollback whose restore could not be confirmed (see
26437/// [`Runner::graft`]).
26438#[derive(Debug)]
26439struct GraftRestoreFailed(String);
26440
26441impl std::fmt::Display for GraftRestoreFailed {
26442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26443        write!(
26444            f,
26445            "could not restore the winner to its pre-graft commit: {}",
26446            self.0
26447        )
26448    }
26449}
26450
26451impl std::error::Error for GraftRestoreFailed {}
26452
26453/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26454/// not the agent: they never draw on an agent's own timeout, and running out of
26455/// them never reads as an agent failure.
26456#[cfg(test)]
26457mod resource_wait_tests {
26458    use super::*;
26459    use std::collections::BTreeMap;
26460
26461    fn sh(id: &str, script: &str) -> AgentSpec {
26462        AgentSpec {
26463            id: id.to_owned(),
26464            kind: crate::config::AgentKind::Command,
26465            model: None,
26466            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26467            extra_args: Vec::new(),
26468            env: BTreeMap::new(),
26469            prompt_delivery: None,
26470            max_turn_secs: None,
26471        }
26472    }
26473
26474    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26475        SeatJob {
26476            seat: SeatState::new("impl-A", &spec.id, 1),
26477            spec,
26478            cwd: dir.to_path_buf(),
26479            prompt: "do it".to_owned(),
26480            timeout,
26481            allow_write: true,
26482            sessions: false,
26483            artifacts: dir.join("art"),
26484            stem: "impl-A".to_owned(),
26485            handover: None,
26486        }
26487    }
26488
26489    fn state(resource_wait_secs: u64) -> RunState {
26490        let mut config = Config::default();
26491        config.graph.timeout_resource_wait = resource_wait_secs;
26492        RunState::new(
26493            PathBuf::from("/repo"),
26494            "main".to_owned(),
26495            "abc1234".to_owned(),
26496            "task".to_owned(),
26497            config,
26498        )
26499    }
26500
26501    fn hold(cache: &Path) -> crate::cache::Guard {
26502        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26503        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26504            crate::cache::AcquireOutcome::Acquired(g) => g,
26505            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26506        }
26507    }
26508
26509    async fn run(
26510        jobs: Vec<SeatJob>,
26511        sem: Arc<Semaphore>,
26512        cache: Option<&Path>,
26513        st: &mut RunState,
26514    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26515        let prompts = Prompts::default();
26516        let ctx = WaveCtx {
26517            run: "r",
26518            node: "implement",
26519            prompts: &prompts,
26520            cache,
26521            round: None,
26522            carry_seats: false,
26523            pauses: None,
26524        };
26525        wave(jobs, sem, &ctx, st, 0).await
26526    }
26527
26528    #[tokio::test]
26529    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26530        crate::run::pin_test_home();
26531        let home = crate::run::home();
26532        let tmp = tempfile::tempdir().unwrap();
26533        let repo = tmp.path().join("repo");
26534        let checkout = tmp.path().join("checkout");
26535        std::fs::create_dir(&repo).unwrap();
26536        git::git(&repo, &["init"]).await.unwrap();
26537        git::git(
26538            &repo,
26539            &[
26540                "-c",
26541                "user.name=Fixture",
26542                "-c",
26543                "user.email=fixture@example.invalid",
26544                "commit",
26545                "--allow-empty",
26546                "-m",
26547                "initial",
26548            ],
26549        )
26550        .await
26551        .unwrap();
26552        git::worktree_add_detached(&repo, &checkout, "HEAD")
26553            .await
26554            .unwrap();
26555        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26556        let target_lease = hold(&target);
26557        let shared = tmp.path().join("unrelated");
26558        let _shared_lease = hold(&shared);
26559        let mut st = state(0);
26560        st.repo = repo.clone();
26561        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26562        st.config.verify.e2e = vec![format!(
26563            "CARGO_TARGET_DIR='{}' cargo test",
26564            git::path_arg(&shared)
26565        )];
26566        let config = tmp.path().join("config.toml");
26567        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26568        let prompts = Prompts::default();
26569        let run_id = st.id.clone();
26570        let ctx = WaveCtx {
26571            run: &run_id,
26572            node: "implement",
26573            prompts: &prompts,
26574            cache: None,
26575            round: None,
26576            carry_seats: false,
26577            pauses: None,
26578        };
26579        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26580        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26581        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26582        assert_eq!(results[0].1.turns, 0);
26583        let saved = RunState::load_under(&run_id, &home).unwrap();
26584        let block = saved.resource_block.unwrap();
26585        assert!(matches!(
26586            block.cause,
26587            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26588                if actual == &target
26589        ));
26590        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26591        let mut task = crate::queue::Task::new(
26592            "build".into(),
26593            "build".into(),
26594            repo,
26595            crate::queue::Source::Human,
26596        );
26597        task.runs.push(run_id);
26598        task.hold_machine(Some(format!(
26599            "{}{}",
26600            crate::cache::RESOURCE_HOLD,
26601            block.description()
26602        )));
26603        queue.put(&mut task).unwrap();
26604        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26605        let triage =
26606            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26607        let pending = triage();
26608        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26609        assert_eq!(
26610            queue.get(&task.id).unwrap().status,
26611            crate::queue::TaskStatus::Held
26612        );
26613        drop(target_lease);
26614        assert_eq!(triage().resumed, vec![task.id.clone()]);
26615        assert_eq!(
26616            queue.get(&task.id).unwrap().status,
26617            crate::queue::TaskStatus::Queued
26618        );
26619        assert!(crate::cache::in_use(&home, &shared));
26620    }
26621
26622    #[tokio::test]
26623    async fn verification_cache_wait_preserves_the_command_budget() {
26624        crate::run::pin_test_home();
26625        let tmp = tempfile::tempdir().unwrap();
26626        let cache = tmp.path().join("target");
26627        let guard = hold(&cache);
26628        let release = tokio::spawn(async move {
26629            tokio::time::sleep(Duration::from_millis(100)).await;
26630            guard.release();
26631        });
26632        let mut st = state(10);
26633        let budget = Duration::from_millis(50);
26634        let wait = repository_wait(&st, None);
26635        let (outcomes, _) = with_cache_lease(
26636            &mut st,
26637            Some(&cache),
26638            "gate",
26639            "gate",
26640            tmp.path(),
26641            "abc1234",
26642            budget,
26643            "test gate",
26644            &wait,
26645            |_, available| async move {
26646                assert_eq!(
26647                    available, budget,
26648                    "contention must not shorten verification"
26649                );
26650                (Vec::new(), false, Vec::new())
26651            },
26652        )
26653        .await
26654        .unwrap();
26655        release.await.unwrap();
26656        assert!(outcomes.is_empty(), "{outcomes:?}");
26657        assert!(
26658            st.events
26659                .iter()
26660                .any(|event| event.message.contains("waiting for"))
26661        );
26662        assert!(st.resource_wait.is_none());
26663        // The verification body no longer owns the lease after returning.
26664        hold(&cache).release();
26665    }
26666
26667    #[tokio::test]
26668    async fn verification_cache_wait_expires_without_starting_commands() {
26669        crate::run::pin_test_home();
26670        let tmp = tempfile::tempdir().unwrap();
26671        let cache = tmp.path().join("target");
26672        let _held = hold(&cache);
26673        let mut st = state(0);
26674        let wait = repository_wait(&st, None);
26675        let (outcomes, _) = with_cache_lease(
26676            &mut st,
26677            Some(&cache),
26678            "gate",
26679            "gate",
26680            tmp.path(),
26681            "abc1234",
26682            Duration::from_secs(60),
26683            "test gate",
26684            &wait,
26685            |_, _| async { panic!("commands must not start without the cache lease") },
26686        )
26687        .await
26688        .unwrap();
26689        assert_eq!(outcomes.len(), 1);
26690        assert!(outcomes[0].resource_blocked);
26691        assert!(st.resource_wait.is_none());
26692        assert!(matches!(
26693            st.resource_block.unwrap().cause,
26694            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
26695        ));
26696    }
26697
26698    #[tokio::test]
26699    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
26700        crate::run::pin_test_home();
26701        let tmp = tempfile::tempdir().unwrap();
26702        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
26703        let cache = tmp.path().join("cache");
26704        let mut state = state(21600);
26705        let wait = repository_wait(&state, None);
26706        let (outcomes, _) = with_cache_lease(
26707            &mut state,
26708            Some(&cache),
26709            "gate",
26710            "gate",
26711            tmp.path(),
26712            "head",
26713            Duration::from_secs(60),
26714            "gate",
26715            &wait,
26716            |_, _| async { panic!("freshness failure must not start verification") },
26717        )
26718        .await
26719        .unwrap();
26720        assert_eq!(outcomes.len(), 1);
26721        assert!(outcomes[0].resource_blocked);
26722        let block = state.resource_block.unwrap();
26723        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
26724        assert!(!block.description().contains("timed out"));
26725    }
26726
26727    #[tokio::test]
26728    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
26729        crate::run::pin_test_home();
26730        let tmp = tempfile::tempdir().unwrap();
26731        let cache = tmp.path().join("cache");
26732        let _held = hold(&cache);
26733        let mut state = state(21600);
26734        let pause = Pause::new();
26735        let interrupt = Pause::new();
26736        let cause = ParkCause::Operator;
26737        pause.park_for(cause.clone());
26738        let prompts = Prompts::default();
26739        let ctx = WaveCtx {
26740            run: "test",
26741            node: "fix",
26742            prompts: &prompts,
26743            cache: Some(&cache),
26744            round: None,
26745            carry_seats: false,
26746            pauses: Some((&pause, &interrupt)),
26747        };
26748        let result = wave(
26749            vec![job(
26750                sh("writer", "exit 99"),
26751                tmp.path(),
26752                Duration::from_secs(1),
26753            )],
26754            Arc::new(Semaphore::new(1)),
26755            &ctx,
26756            &mut state,
26757            0,
26758        )
26759        .await;
26760        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
26761        assert_eq!(result[0].1.turns, 0);
26762        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26763        assert_eq!(
26764            state.resource_block.unwrap().cause,
26765            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
26766        );
26767        assert!(state.active.is_empty());
26768    }
26769
26770    #[tokio::test]
26771    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
26772        crate::run::pin_test_home();
26773        let tmp = tempfile::tempdir().unwrap();
26774        let cache = tmp.path().join("target-a");
26775        let guard = hold(&cache);
26776        // Held for longer than the agent's whole 1s budget.
26777        tokio::spawn(async move {
26778            tokio::time::sleep(Duration::from_millis(1500)).await;
26779            guard.release();
26780        });
26781        let mut st = state(60);
26782        let results = run(
26783            vec![job(
26784                sh("alpha", "echo ok"),
26785                tmp.path(),
26786                Duration::from_secs(1),
26787            )],
26788            Arc::new(Semaphore::new(1)),
26789            Some(&cache),
26790            &mut st,
26791        )
26792        .await;
26793        assert!(
26794            matches!(results[0].2, AgentOutcome::Ok(_)),
26795            "the wait must not be charged to the agent"
26796        );
26797        assert!(st.resource_block.is_none());
26798        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26799        assert!(st.resource_wait.is_none() && st.active.is_empty());
26800    }
26801
26802    #[tokio::test]
26803    #[cfg(unix)]
26804    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
26805        use std::os::fd::AsRawFd as _;
26806        crate::run::pin_test_home();
26807        let tmp = tempfile::tempdir().unwrap();
26808        crate::git::git(tmp.path(), &["init"]).await.unwrap();
26809        let common = tmp.path().join(".git");
26810        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
26811        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
26812        assert_eq!(
26813            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
26814            0
26815        );
26816        let mut st = state(1);
26817        st.config.coordination = crate::config::test_coordination();
26818        let mut reader = job(
26819            sh("reader", "echo must-not-run"),
26820            tmp.path(),
26821            Duration::from_secs(30),
26822        );
26823        reader.allow_write = false;
26824        let results = run(
26825            vec![reader.clone()],
26826            Arc::new(Semaphore::new(1)),
26827            None,
26828            &mut st,
26829        )
26830        .await;
26831        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26832        assert_eq!(results[0].1.turns, 0);
26833        assert!(FailClass::of(&results[0].2).is_none());
26834        assert_eq!(
26835            st.resource_block.as_ref().unwrap().kind,
26836            "repository coordination"
26837        );
26838        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26839        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26840        drop(external);
26841        let editor = crate::repo_lock::SeatLease::for_checkout(
26842            tmp.path(),
26843            true,
26844            crate::config::test_coordination().as_ref(),
26845        )
26846        .await
26847        .unwrap();
26848        let pause = Pause::new();
26849        let interrupt = Pause::new();
26850        let prompts = Prompts::default();
26851        let ctx = WaveCtx {
26852            run: "r",
26853            node: "review",
26854            prompts: &prompts,
26855            cache: None,
26856            round: None,
26857            carry_seats: false,
26858            pauses: Some((&pause, &interrupt)),
26859        };
26860        let (results, ()) = tokio::join!(
26861            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
26862            async {
26863                tokio::time::sleep(Duration::from_millis(50)).await;
26864                pause.park();
26865            }
26866        );
26867        assert!(
26868            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
26869        );
26870        assert_eq!(results[0].1.turns, 0);
26871        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26872        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26873        drop(editor);
26874    }
26875
26876    #[tokio::test]
26877    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
26878        crate::run::pin_test_home();
26879        let tmp = tempfile::tempdir().unwrap();
26880        let cache = tmp.path().join("target-b");
26881        let _held = hold(&cache);
26882        let mut st = state(1);
26883        let results = run(
26884            vec![job(
26885                sh("alpha", "echo ok"),
26886                tmp.path(),
26887                Duration::from_secs(1),
26888            )],
26889            Arc::new(Semaphore::new(1)),
26890            Some(&cache),
26891            &mut st,
26892        )
26893        .await;
26894        let (_, seat, out) = &results[0];
26895        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
26896        assert!(wave_blocked(&results));
26897        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
26898        assert_eq!(seat.turns, 0, "nothing was asked");
26899        assert!(
26900            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
26901            "no agent was spawned"
26902        );
26903        assert!(FailClass::of(out).is_none(), "not a failure class");
26904        let block = st.resource_block.as_ref().expect("recorded for the resume");
26905        assert_eq!(block.kind, "shared build cache");
26906        assert!(matches!(
26907            block.cause,
26908            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
26909        ));
26910        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26911        assert!(st.active.is_empty());
26912    }
26913
26914    #[tokio::test]
26915    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
26916        crate::run::pin_test_home();
26917        let tmp = tempfile::tempdir().unwrap();
26918        let mut st = state(1);
26919        let results = run(
26920            vec![job(
26921                sh("alpha", "echo ok"),
26922                tmp.path(),
26923                Duration::from_secs(1),
26924            )],
26925            Arc::new(Semaphore::new(0)),
26926            None,
26927            &mut st,
26928        )
26929        .await;
26930        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26931        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
26932        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
26933    }
26934
26935    #[tokio::test]
26936    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
26937        crate::run::pin_test_home();
26938        let tmp = tempfile::tempdir().unwrap();
26939        let mut st = state(60);
26940        let results = run(
26941            vec![job(
26942                sh("alpha", "sleep 30"),
26943                tmp.path(),
26944                Duration::from_secs(1),
26945            )],
26946            Arc::new(Semaphore::new(1)),
26947            None,
26948            &mut st,
26949        )
26950        .await;
26951        let out = &results[0].2;
26952        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
26953        let class = FailClass::of(out).expect("a failure");
26954        assert_eq!(class, FailClass::Timeout);
26955        assert!(should_hand_over(None, &class), "existing handover policy");
26956        assert!(st.resource_block.is_none());
26957    }
26958}
26959
26960/// A fold acts on the record it locked, and on nothing else.
26961#[cfg(test)]
26962mod fold_record_tests {
26963    use super::*;
26964
26965    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
26966        error.downcast_ref::<FoldRefusal>()
26967    }
26968
26969    /// A deletion that lands after the fold's look at the record and before its
26970    /// locks must neither be undone (the fold's lock files bring the directory
26971    /// back, its stale copy the record) nor be acted on.
26972    #[tokio::test]
26973    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
26974        let dir = tempfile::tempdir().unwrap();
26975        let home = dir.path();
26976        let repo = home.join("repo");
26977        std::fs::create_dir_all(&repo).unwrap();
26978        crate::clean::tests::init_repo(&repo);
26979        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
26980            &home.join("runs"),
26981            &home.join("wt"),
26982            &repo,
26983            "20260801-000000-y001",
26984            RunStatus::Superseded,
26985        )
26986        .await;
26987        let mut state = RunState::load_under(&id, home).unwrap();
26988        BEFORE_LOCKS.with(|hook| {
26989            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
26990                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
26991            }));
26992        });
26993
26994        let error = fold_run(&mut state, true, home).await.unwrap_err();
26995        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
26996        assert!(
26997            !home.join("runs").join(&id).exists(),
26998            "the fold's own lock files must not bring a deleted run back"
26999        );
27000        assert!(worktree.exists(), "nothing of a deleted run is removed");
27001    }
27002
27003    /// The caller's `state` is only a first look: a record that was never
27004    /// saved is not a record the fold may write.
27005    #[tokio::test]
27006    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27007        let dir = tempfile::tempdir().unwrap();
27008        let home = dir.path();
27009        let mut state = RunState::new(
27010            home.join("repo"),
27011            "main".to_owned(),
27012            "abc".to_owned(),
27013            "fixture".to_owned(),
27014            crate::config::Config::default(),
27015        );
27016        state.status = RunStatus::Superseded;
27017        let error = fold_run(&mut state, true, home).await.unwrap_err();
27018        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27019        assert!(
27020            !home.join("runs").exists(),
27021            "nothing was created: {error:#}"
27022        );
27023    }
27024
27025    /// A refusal changes nothing. A directory whose record is another run's is
27026    /// not the run that was locked: every entry point answers `record gone`,
27027    /// the other run's worktree is left alone, the record stays as it was, and
27028    /// the lock files are not unlinked (an unlinked lock file lets the next
27029    /// caller lock a different inode - `pr_head::owner_lock`).
27030    #[tokio::test]
27031    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27032        let dir = tempfile::tempdir().unwrap();
27033        let home = dir.path();
27034        let repo = home.join("repo");
27035        std::fs::create_dir_all(&repo).unwrap();
27036        crate::clean::tests::init_repo(&repo);
27037        let runs = home.join("runs");
27038        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27039            &runs,
27040            &home.join("wt"),
27041            &repo,
27042            "20260801-000000-y101",
27043            RunStatus::Superseded,
27044        )
27045        .await;
27046        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27047            &runs,
27048            &home.join("wt"),
27049            &repo,
27050            "20260801-000000-y102",
27051            RunStatus::Superseded,
27052        )
27053        .await;
27054        let first_look = RunState::load_under(&id, home).unwrap();
27055        let record = runs.join(&id).join("run.json");
27056        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27057        let before = std::fs::read(&record).unwrap();
27058        for entry in ["fold_run", "fold_run_when", "override"] {
27059            let mut state = first_look.clone();
27060            let result = match entry {
27061                "fold_run" => fold_run(&mut state, true, home).await,
27062                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27063                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27064            };
27065            let error = result.unwrap_err();
27066            assert_eq!(
27067                refusal(&error),
27068                Some(&FoldRefusal::RecordGone),
27069                "{entry}: {error:#}"
27070            );
27071            assert!(own.exists() && theirs.exists(), "{entry}");
27072            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27073            for lock in ["pr-owner.lock", "driver.lock"] {
27074                assert!(
27075                    runs.join(&id).join(lock).exists(),
27076                    "{entry}: {lock} stays in place"
27077                );
27078            }
27079            assert!(
27080                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27081                "{entry}: the other run was not folded"
27082            );
27083        }
27084    }
27085
27086    /// The refusal is added to the error underneath, never substituted for it:
27087    /// callers match `ResourceBlocked` for a coordination wait.
27088    #[test]
27089    fn a_live_refusal_keeps_the_error_callers_match() {
27090        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27091            "repository coordination".into(),
27092        ));
27093        let error = live_or(blocked);
27094        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27095        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27096        // Anything that is not a held lock is passed through untouched.
27097        let other = live_or(anyhow::anyhow!("git exploded"));
27098        assert!(refusal(&other).is_none());
27099    }
27100
27101    /// Contention is `live`, a lock call that failed for another reason is a
27102    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27103    #[test]
27104    fn source_verification_failures_are_told_apart() {
27105        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27106            .context("Cargo build is active");
27107        let error = source_proof_failure(contended);
27108        assert!(
27109            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27110            "{error:#}"
27111        );
27112
27113        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27114            "Cargo lock target/debug/.cargo-lock".into(),
27115            std::io::Error::from(std::io::ErrorKind::Interrupted),
27116        ));
27117        let error = source_proof_failure(failed);
27118        assert!(refusal(&error).is_none(), "{error:#}");
27119        assert!(
27120            error
27121                .chain()
27122                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27123        );
27124
27125        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27126        assert!(matches!(
27127            refusal(&error),
27128            Some(FoldRefusal::ProofIncomplete(_))
27129        ));
27130    }
27131
27132    /// A run directory that is not there is `record gone` at the lock, not
27133    /// something to create for the lock's sake.
27134    #[test]
27135    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27136        let dir = tempfile::tempdir().unwrap();
27137        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27138            .map(drop)
27139            .map_err(lock_refusal)
27140            .unwrap_err();
27141        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27142        assert!(!dir.path().join("runs").exists());
27143    }
27144}