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        match crate::queue::Queue::open().get(task) {
1013            Ok(owner) => selection.check_retained_task(&owner, &crate::run::home())?,
1014            Err(_) => selection.check_task_assignment(task, &selection.instruction, assignment)?,
1015        }
1016        let base_branch =
1017            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1018                .await?;
1019        let fetched_base = resolve_base(
1020            repo,
1021            &base_branch,
1022            &config.merge.remote,
1023            config.coordination.as_ref(),
1024        )
1025        .await?;
1026        let base_commit = fetched_base.commit.clone();
1027        selection
1028            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1029            .await?;
1030        Box::pin(selection.verify_source(repo)).await?;
1031        if let Some(proof) = &selection.source_proof {
1032            anyhow::ensure!(
1033                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1034                "source rebase base is outside the fetched landing base"
1035            );
1036        }
1037        let roles = config.resolve_roles()?;
1038        let max_parallel = config.graph.max_parallel.max(1);
1039        let mut state = RunState::new(
1040            repo.to_path_buf(),
1041            base_branch,
1042            base_commit.clone(),
1043            selection.instruction.clone(),
1044            config,
1045        );
1046        state.fetched_base = Some(fetched_base);
1047        state.set_origin(crate::run::Origin::queue(task))?;
1048        state.pr_head = Some(selection.branch.clone());
1049        state.pr_recovery = Some(selection.clone());
1050        state.stale_pr_recovery = selection.disposition
1051            == Some(crate::pr_recovery::Disposition::Land)
1052            && !git::is_ancestor(repo, &base_commit, &selection.head).await
1053            && crate::queue::Queue::open().get(task).is_ok_and(|task| {
1054                task.execution_runs().iter().any(|id| {
1055                    RunState::load(id).is_ok_and(|old| {
1056                        old.status == RunStatus::Ready
1057                            && !old.released()
1058                            && old.retired_to.is_none()
1059                            && old.pr_taken_over_by.is_none()
1060                            && task.assignment_accepts(&old)
1061                            && old.pr_branch() == Some(selection.branch.as_str())
1062                            && old
1063                                .pr
1064                                .as_ref()
1065                                .is_some_and(|pr| pr.state == "open" && pr.url == selection.url)
1066                    })
1067                })
1068            });
1069        if state.stale_pr_recovery {
1070            state.event("recovery", "stale public PR: a content conflict requires an explicit base-conflict repair grant");
1071        }
1072        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1073    }
1074
1075    async fn open_selected(
1076        repo: &Path,
1077        mut state: RunState,
1078        roles: ResolvedRoles,
1079        max_parallel: usize,
1080        base_commit: String,
1081        selection: crate::pr_recovery::Selection,
1082    ) -> Result<Self> {
1083        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1084        let opened = async {
1085            startup.stage(&mut state, "predecessors")?;
1086            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1087            startup.stage(&mut state, "open-selected")?;
1088            let branch = state.branch_for('A');
1089            let wait = repository_wait(&state, None);
1090            let prepared = async {
1091                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1092                git::git(repo, &["branch", &branch, selection.source()]).await?;
1093                drop(coordination);
1094                anyhow::Ok(())
1095            }
1096            .await;
1097            prepared?;
1098            state.event(
1099                "recovery",
1100                format!(
1101                    "selected implementation {} for {} (public lease {})",
1102                    selection.source(),
1103                    selection.url,
1104                    selection.head
1105                ),
1106            );
1107            let takeover = crate::handover::Takeover {
1108                earlier: Vec::new(),
1109                home: crate::run::home(),
1110                choice: None,
1111                task_instruction: Some(selection.instruction.clone()),
1112            };
1113            state.save()?;
1114            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1115        }
1116        .await;
1117        startup.finish(&mut state, opened)?;
1118        Ok(Self {
1119            state,
1120            roles,
1121            sem: Arc::new(Semaphore::new(max_parallel)),
1122            pause: Pause::new(),
1123            interrupt: Pause::new(),
1124        })
1125    }
1126
1127    /// What the newest earlier attempt that reviewed `branch` leaves for this
1128    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1129    /// no earlier attempts. Reads the earlier record only: ownership of its
1130    /// worktree and branch is [`crate::handover`]'s business.
1131    async fn inherit(
1132        repo: &Path,
1133        branch: &str,
1134        base_commit: &str,
1135        takeover: &crate::handover::Takeover,
1136    ) -> Option<crate::recovery::RecoveryRecord> {
1137        use crate::recovery::{Relation, assess};
1138        let newest = takeover.earlier.last()?;
1139        let mut chosen = None;
1140        for id in takeover.earlier.iter().rev() {
1141            if let Ok(old) = RunState::load_under(id, &takeover.home)
1142                && !old.reviews.is_empty()
1143                && (old.winner().is_some_and(|w| w.branch == branch)
1144                    || old.pr_head.as_deref() == Some(branch))
1145            {
1146                chosen = Some(old);
1147                break;
1148            }
1149        }
1150        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1151            .await
1152            .unwrap_or_default();
1153        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1154            Some(last) if last.head == tip => Relation::Same,
1155            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1156            _ => Relation::Diverged,
1157        };
1158        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1159        Some(assess(from, chosen.as_ref(), base_commit, relation))
1160    }
1161
1162    /// The half of [`Runner::review_taking_over`] that can fail after an
1163    /// earlier attempt's worktree was released.
1164    async fn open_review(
1165        repo: &Path,
1166        branch: &str,
1167        state: &mut RunState,
1168        base_commit: String,
1169        takeover: &crate::handover::Takeover,
1170    ) -> Result<()> {
1171        startup_stage(state, "review-sync")?;
1172        let wait = repository_wait(state, None);
1173        let _coordination = coordinate_operation(state, repo, &wait).await?;
1174        if state.foreign_checkout.is_some() {
1175            // Never reconcile or force-move a ref checked out by the operator.
1176            if state.pr_head.is_none() {
1177                state.pr_head = Some(branch.to_owned());
1178            }
1179        } else if state.pr_recovery.is_none() {
1180            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1181        }
1182        // The commit subjects are the closest thing to a task statement that
1183        // existing work carries, and the reviewers are told as much.
1184        let start = review_base(
1185            repo,
1186            &state.config.merge.remote,
1187            &state.base_branch,
1188            &base_commit,
1189            branch,
1190        )
1191        .await;
1192        let log = git::log_oneline(repo, &start, branch)
1193            .await
1194            .unwrap_or_default();
1195        let log_text = if log.trim().is_empty() {
1196            "(no commit messages)"
1197        } else {
1198            log.trim()
1199        };
1200        let mut instruction = format!(
1201            "Review the work already on branch `{branch}`. There is no task \
1202             statement: what the change claims to do is whatever its commits \
1203             say.\n\n{log_text}"
1204        );
1205        // A retry of a task whose earlier attempt left reviews behind carries
1206        // that attempt's evidence, and the task's own statement with it: the
1207        // completion criteria are the task's, not whatever the commits claim.
1208        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1209            if let Some(task) = takeover
1210                .task_instruction
1211                .as_deref()
1212                .filter(|t| !t.trim().is_empty())
1213                && rec.reviewed_head.is_some()
1214            {
1215                instruction = format!(
1216                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1217                    task.trim()
1218                );
1219                rec.criteria_inherited = true;
1220            }
1221            state.event("recovery", rec.summary());
1222            state.recovery = Some(rec);
1223        }
1224        if let Some(selected) = &state.pr_recovery {
1225            instruction = selected.instruction.clone();
1226        }
1227        state.task_instruction = takeover.task_instruction.clone();
1228        state.instruction = instruction;
1229        state.reviewed_commits = Some(
1230            git::subjects(repo, &start, branch)
1231                .await
1232                .unwrap_or_default(),
1233        );
1234
1235        // A takeover must not forget a hold that a previous review observed,
1236        // even if repairs have since removed it from the branch.
1237        for id in &takeover.earlier {
1238            if let Ok(old) = RunState::load_under(id, &takeover.home)
1239                && old.repo == state.repo
1240                && (old.pr_head.as_deref() == Some(branch)
1241                    || old.winner().is_some_and(|w| w.branch == branch))
1242            {
1243                for hold in old.branch_owner_holds {
1244                    if !state.branch_owner_holds.contains(&hold) {
1245                        state.event(
1246                            "approval-policy",
1247                            format!(
1248                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1249                                hold.control.key(),
1250                                hold.file,
1251                                hold.head
1252                            ),
1253                        );
1254                        state.branch_owner_holds.push(hold);
1255                    }
1256                }
1257            }
1258        }
1259        // Select the actual review tip before observing owner policy. A foreign
1260        // checkout can lag its remote descendant, and repairs must not erase
1261        // holds introduced only on that selected commit.
1262        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1263            let tracking = format!("{}/{branch}", state.config.merge.remote);
1264            // A surviving tracking ref is not evidence that the remote still
1265            // offers this tip. Adopt it only after a successful fetch here.
1266            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1267            let mut head = checkout.synced_head.clone();
1268            if matches!(fetched, Ok(out) if out.ok()) {
1269                let remote = git::rev_parse(repo, &tracking).await?;
1270                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1271                    head = remote;
1272                }
1273            }
1274            head
1275        } else {
1276            git::rev_parse(repo, branch).await?
1277        };
1278        state.observe_branch_owner_holds(&reviewed_head).await;
1279
1280        // An attached worktree, so the fixer's commits land on the branch under
1281        // review rather than on a detached head nobody will look at again.
1282        let worktree = state.worktree_root().join("under-review");
1283        if let Some(parent) = worktree.parent() {
1284            tokio::fs::create_dir_all(parent).await.ok();
1285        }
1286        let path = worktree.to_string_lossy().to_string();
1287        let review_branch = if state.foreign_checkout.is_some() {
1288            let shadow = format!("magi/{}/review", state.short());
1289            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1290            shadow
1291        } else {
1292            branch.to_owned()
1293        };
1294        startup_stage(state, "review-checkout")?;
1295        git::git(repo, &["worktree", "add", &path, &review_branch])
1296            .await
1297            .with_context(|| {
1298                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1299            })?;
1300
1301        startup_stage(state, "worktree-setup")?;
1302        let setup = match ensure_setup_config(state, repo).await {
1303            Ok(()) => {
1304                worktree_setup::prepare_with(
1305                    &state.config,
1306                    repo,
1307                    &worktree,
1308                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1309                )
1310                .await
1311            }
1312            Err(e) => Err(e),
1313        };
1314        if let Err(e) = setup {
1315            git::worktree_remove_clean(repo, &worktree).await.ok();
1316            return Err(e);
1317        }
1318        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1319            .await
1320            .unwrap_or(0);
1321        if commits == 0 {
1322            git::worktree_remove_clean(repo, &worktree).await.ok();
1323            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1324        }
1325        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1326            .await
1327            .map(|f| f.len())
1328            .unwrap_or(0);
1329        if files == 0
1330            && let (Ok(head_tree), Ok(base_tree)) = (
1331                git::tree_of(&worktree, "HEAD").await,
1332                git::tree_of(&worktree, &base_commit).await,
1333            )
1334            && head_tree == base_tree
1335        {
1336            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1337            git::worktree_remove_clean(repo, &worktree).await.ok();
1338            bail!(
1339                "`{branch}` at {} has a tree identical to base {}; this usually means \
1340                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1341                 against `{}/{branch}`) rather than an empty change",
1342                short(&head),
1343                short(&base_commit),
1344                state.config.merge.remote
1345            );
1346        }
1347        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1348            .await
1349            .unwrap_or_default();
1350
1351        state.candidates.push(Candidate {
1352            index: 0,
1353            label: 'A',
1354            // Not an agent id on purpose: nothing in the roster wrote this, and
1355            // the stats tables must not credit anyone with a win for it.
1356            agent: EXISTING_BRANCH.to_owned(),
1357            branch: review_branch,
1358            worktree,
1359            summary: String::new(),
1360            stat,
1361            files,
1362            commits,
1363            empty: false,
1364            failed: None,
1365            verified_noop: None,
1366            duration_ms: 0,
1367            folded: false,
1368        });
1369        state.tally = Some(Tally {
1370            first_choice: BTreeMap::from([('A', 0)]),
1371            borda: BTreeMap::new(),
1372            winner: 'A',
1373            rankings: 0,
1374            unanimous_initial: false,
1375            deliberated: false,
1376            changed_votes: 0,
1377            unanimous_final: false,
1378            tie_break: None,
1379            // No panel sat, so no quorum applies. Zero judges is the correct
1380            // number for work that never competed, and must not be reported as
1381            // a collapsed panel.
1382            judges: 0,
1383            present: 0,
1384            quorum: 0,
1385            met_quorum: true,
1386            uncontested: Some("review-only run: nothing competed".to_owned()),
1387        });
1388        state.status = RunStatus::Reviewing;
1389        state.prep_complete = Some(true);
1390        state.event(
1391            "start",
1392            format!(
1393                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1394                state.id
1395            ),
1396        );
1397        Ok(())
1398    }
1399
1400    /// Authorize one bounded synchronization interval, under the caller's queue task
1401    /// claim and the same owner/execution locks used by run maintenance.
1402    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1403        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1404    }
1405
1406    /// Authorize a known preparation failure against the inspected evidence.
1407    pub async fn authorize_base_preparation_recovery(
1408        home: &Path,
1409        id: &str,
1410        task: &str,
1411        digest: &str,
1412    ) -> Result<()> {
1413        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1414    }
1415
1416    /// Queue release uses its durable approval generation exactly once.
1417    pub(crate) async fn authorize_base_recovery_from_resumption(
1418        home: &Path,
1419        id: &str,
1420        task: &str,
1421    ) -> Result<()> {
1422        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1423    }
1424
1425    pub(crate) async fn authorize_base_recovery_control(
1426        home: &Path,
1427        task: &str,
1428        control: &mut crate::base_recovery_control::Transaction,
1429    ) -> Result<()> {
1430        let id = control.request.run.clone();
1431        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1432    }
1433
1434    async fn authorize_base_recovery_request(
1435        home: &Path,
1436        id: &str,
1437        task: &str,
1438        resumption: bool,
1439        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1440        terminal_digest: Option<&str>,
1441    ) -> Result<()> {
1442        let _owner = crate::pr_head::owner_lock(home, id)?;
1443        let mut state = RunState::load_under(id, home)?;
1444        crate::pr_head::ensure_owner(&state)?;
1445        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1446        anyhow::ensure!(
1447            queued.execution_runs().last().is_some_and(|run| run == id)
1448                && queued.assignment_accepts(&state)
1449                && queued.status != crate::queue::TaskStatus::Done
1450                && !queued.fresh_start
1451                && queued.review_branch.is_none(),
1452            "run task ownership changed"
1453        );
1454        anyhow::ensure!(
1455            state
1456                .origin
1457                .as_ref()
1458                .and_then(|o| o.task.as_deref())
1459                .is_none_or(|owner| owner == task),
1460            "run belongs to another task"
1461        );
1462        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1463        anyhow::ensure!(
1464            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1465            "run is live or its ownership is unknown"
1466        );
1467        // Judge the previous driver's lease before acquiring our maintenance
1468        // lease. The owner lock excludes new driver claims across both steps.
1469        let _execution = crate::driver::maintenance(home, id)?;
1470        anyhow::ensure!(
1471            state.status.resumable()
1472                && state.released_to.is_none()
1473                && state.retired_to.is_none()
1474                && state.pr_taken_over_by.is_none(),
1475            "run ownership is final"
1476        );
1477        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1478        anyhow::ensure!(
1479            !state.pr_publication_pending
1480                && !crate::handover::landing_checkpoint(&state)
1481                && state.merge_decision.is_none(),
1482            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1483        );
1484        let winner = state.winner().context("run has no retained winner")?;
1485        anyhow::ensure!(
1486            git::is_clean(&winner.worktree).await?,
1487            "retained worktree has uncommitted changes"
1488        );
1489        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1490        anyhow::ensure!(
1491            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1492            "retained worktree does not match the winner branch"
1493        );
1494        if let Some(control) = control.as_ref() {
1495            anyhow::ensure!(
1496                head.starts_with(&control.request.head),
1497                "retained HEAD changed since the owner request"
1498            );
1499            anyhow::ensure!(
1500                state
1501                    .base_sync_recovery
1502                    .stop
1503                    .as_ref()
1504                    .is_none_or(|stop| stop.head == head),
1505                "retained HEAD differs from the recorded stop head; inspect it first"
1506            );
1507        }
1508        anyhow::ensure!(
1509            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1510            "{}",
1511            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1512        );
1513        state.ensure_base_episode();
1514        state.record_base_sync_stop(&head);
1515        let preparation = state.unknown_preparation_stop(&head);
1516        anyhow::ensure!(
1517            state
1518                .base_sync_recovery
1519                .stop
1520                .as_ref()
1521                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1522                || (preparation && !resumption),
1523            "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"
1524        );
1525        let fetched =
1526            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1527        anyhow::ensure!(
1528            fetched.ok(),
1529            "cannot authorize base recovery without a fetched base"
1530        );
1531        let approved_tip = git::rev_parse(
1532            &state.repo,
1533            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1534        )
1535        .await?;
1536        let preparation_digest = state.preparation_digest(&head);
1537        anyhow::ensure!(
1538            preparation
1539                || (terminal_digest.is_none()
1540                    && control
1541                        .as_ref()
1542                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1543            "preparation evidence digest does not name an eligible preparation stop"
1544        );
1545        if preparation {
1546            anyhow::ensure!(
1547                crate::daemon::compatible_run_instruction(&state, &queued),
1548                "task instruction does not match the retained run"
1549            );
1550            if let Some(control) = control.as_ref() {
1551                anyhow::ensure!(
1552                    control.request.head == head
1553                        && control.request.evidence_digest.is_some()
1554                        && control.request.evidence_digest == preparation_digest
1555                        && control.request.decision.is_none(),
1556                    "preparation stop requires the full HEAD and current inspected evidence digest"
1557                );
1558            } else {
1559                anyhow::ensure!(
1560                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1561                    "preparation stop requires the current inspected evidence digest"
1562                );
1563            }
1564            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1565            anyhow::ensure!(
1566                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1567                "current base does not descend from the stopped base"
1568            );
1569            git::probe_rebase_preparation(
1570                &state,
1571                &head,
1572                &home.join("runs").join(id),
1573                &repository_wait(&state, None),
1574            )
1575            .await?;
1576        }
1577        if let Some(control) = control.as_deref_mut() {
1578            let queue = crate::queue::Queue::at(home.join("queue"));
1579            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1580            if let Some(prior) = state
1581                .base_sync_recovery
1582                .authorizations
1583                .iter()
1584                .find(|a| a.request.as_deref() == Some(&control.key()))
1585            {
1586                anyhow::ensure!(
1587                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1588                    "recovery request was consumed or invalidated; it cannot queue again"
1589                );
1590                return control.enqueue(&queue);
1591            }
1592        }
1593        if resumption {
1594            anyhow::ensure!(
1595                crate::daemon::compatible_run_instruction(&state, &queued),
1596                "resumption instruction does not match the retained run"
1597            );
1598            let approval = queued
1599                .resumption
1600                .as_ref()
1601                .context("no operator resumption")?;
1602            anyhow::ensure!(
1603                approval.instruction == queued.instruction,
1604                "resumption approval does not match the current task instruction"
1605            );
1606            state.authorize_base_sync_resumption(task, approval)?;
1607        } else {
1608            state.authorize_base_sync(task)?;
1609        }
1610        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1611        state
1612            .base_sync_recovery
1613            .authorizations
1614            .last_mut()
1615            .unwrap()
1616            .scope = Some(crate::base_sync_recovery::Scope {
1617            tip: approved_tip,
1618            instruction: queued.instruction.clone(),
1619            episode,
1620            preparation_digest,
1621        });
1622        if let Some(control) = control.as_deref_mut() {
1623            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1624            authorization.request = Some(control.key());
1625            authorization.generation = control.generation();
1626            authorization.decision = control.decision();
1627            authorization.question = control
1628                .request
1629                .decision
1630                .as_ref()
1631                .map(|_| control.request.request.clone());
1632        }
1633        state.event(
1634            "base-recovery",
1635            if preparation {
1636                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1637            } else {
1638                "owner authorized a bounded base synchronization interval; fresh verification required"
1639            },
1640        );
1641        state.save_under(home)?;
1642        if let Some(control) = control {
1643            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1644        }
1645        Ok(())
1646    }
1647
1648    /// Reopen an existing run.
1649    pub fn resume(id: &str) -> Result<Self> {
1650        let state = RunState::load(id)?;
1651        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1652        if state.startup.as_ref().is_some_and(|s| !s.complete)
1653            || (state.status == RunStatus::Prep
1654                && state.instruction.trim().is_empty()
1655                && state.candidates.is_empty()
1656                && state.prep_complete == Some(false))
1657        {
1658            bail!(
1659                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1660            );
1661        }
1662        crate::pr_head::ensure_owner(&state)?;
1663        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1664            bail!(
1665                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1666            );
1667        }
1668        if let Some(to) = &state.released_to {
1669            bail!(
1670                "run {} cannot be resumed: its worktree was released to run {}",
1671                state.short(),
1672                crate::run::short_of(to)
1673            );
1674        }
1675        let roles = state.config.resolve_roles()?;
1676        if let Some(id) = &state.config.graph.selected_implementer
1677            && state.candidates.iter().any(|c| c.agent != *id)
1678        {
1679            bail!(
1680                "replacement implementer pin does not match the saved candidates; task must stay held"
1681            );
1682        }
1683        let max_parallel = state.config.graph.max_parallel.max(1);
1684        Ok(Self {
1685            state,
1686            roles,
1687            sem: Arc::new(Semaphore::new(max_parallel)),
1688            pause: Pause::new(),
1689            interrupt: Pause::new(),
1690        })
1691    }
1692
1693    /// Walk the graph to a terminal state, skipping nodes already recorded.
1694    ///
1695    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1696    /// the phone - ends here, so this is the one place a run that ended
1697    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1698    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1699    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1700        // Allocate before polling: boxing inside an async wrapper would still
1701        // retain its construction frame while the nested graph is polled.
1702        Box::pin(self.execute_inner(None))
1703    }
1704
1705    pub(crate) async fn execute_sync_only(
1706        &mut self,
1707        request: crate::base_sync_only::Request,
1708    ) -> Result<()> {
1709        Box::pin(self.execute_inner(Some(request))).await
1710    }
1711
1712    async fn execute_inner(
1713        &mut self,
1714        sync_only: Option<crate::base_sync_only::Request>,
1715    ) -> Result<()> {
1716        anyhow::ensure!(
1717            self.state.startup.as_ref().is_none_or(|s| s.complete),
1718            "startup incomplete; inspect retained evidence before explicit recovery"
1719        );
1720        if let Some(selection) = &self.state.pr_recovery
1721            && (selection.source_proof.is_some() || selection.source_run.is_some())
1722        {
1723            Box::pin(selection.verify_source(&self.state.repo)).await?;
1724        }
1725        // Queue claims cover daemon work; this also serializes manual drivers
1726        // consuming a repair answer, including the new review and decision.
1727        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1728            || self.state.land_approval.is_some()
1729            || self.state.merge_decision.is_some()
1730            || !self.state.merge_repairs.is_empty()
1731            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1732        {
1733            let claim = FixClaim::acquire(&self.state.dir())?;
1734            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1735            let disk = RunState::load(&self.state.id)?;
1736            let checkpoint = |s: &RunState| {
1737                (
1738                    s.merge_repairs.len(),
1739                    s.merge_repairs
1740                        .last()
1741                        .map(|r| (r.question.clone(), r.phase)),
1742                    s.land_approval
1743                        .as_ref()
1744                        .map(|a| (a.question.clone(), a.head.clone())),
1745                )
1746            };
1747            if checkpoint(&disk) != checkpoint(&self.state) {
1748                bail!(
1749                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1750                );
1751            }
1752            Some(claim)
1753        } else {
1754            None
1755        };
1756        let base_only = sync_only.is_some();
1757        let mut execution = self.claim_driver(sync_only).await?;
1758        let runner = &mut *execution.runner;
1759        let wait = runner.repository_wait();
1760        // Keep the graph's large future off the callers' stack, including
1761        // standalone task attempts running on a default-sized test thread.
1762        let result = if base_only {
1763            wait.scope(Box::pin(async {
1764                let repo = runner.state.repo.clone();
1765                let result = async {
1766                    let _coordination = runner.coordinate(&repo).await?;
1767                    anyhow::ensure!(
1768                        !runner.pause.parked() && !runner.interrupt.parked(),
1769                        "paused before base synchronization"
1770                    );
1771                    crate::base_sync_only::sync(&mut runner.state).await
1772                }
1773                .await;
1774                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1775                pass.result = match result {
1776                    Ok(outcome) => outcome,
1777                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1778                };
1779                let summary = pass.summary();
1780                runner.state.event("base-sync-only", summary);
1781                runner.state.save()
1782            }))
1783            .await
1784        } else {
1785            wait.scope(Box::pin(runner.execute_graph())).await
1786        };
1787        let result = match result {
1788            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1789                record_repository_block(&mut runner.state, &e);
1790                runner.park_here()?;
1791                Ok(())
1792            }
1793            other => other,
1794        };
1795        execution.driver.finish(&mut runner.state).await?;
1796        let ended = if result.is_err() {
1797            Some({
1798                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1799                if let Err(error) = &result {
1800                    notice.message = format!(
1801                        "Run {} stopped with an error: {}",
1802                        runner.state.id,
1803                        error.to_string().lines().next().unwrap_or("unknown error")
1804                    );
1805                }
1806                notice
1807            })
1808        } else {
1809            crate::notices::run_ended(&runner.state)
1810        };
1811        if let Some(notice) = ended {
1812            crate::notices::raise(notice);
1813        }
1814        result
1815    }
1816
1817    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1818        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1819    }
1820
1821    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1822        let wait = self.repository_wait();
1823        coordinate_operation(&mut self.state, cwd, &wait).await
1824    }
1825
1826    /// Validate ownership and persist the driver claim in one critical section.
1827    async fn claim_driver(
1828        &mut self,
1829        sync_only: Option<crate::base_sync_only::Request>,
1830    ) -> Result<DriverExecution<'_>> {
1831        let owner = match crate::pr_head::owner_lock_wait(
1832            &crate::run::home(),
1833            &self.state.id,
1834            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1835        )
1836        .await
1837        {
1838            Ok(owner) => owner,
1839            Err(error) => {
1840                let detail = format!("worktree maintenance or ownership update: {error:#}");
1841                // Admission did not own run.json: retain this resource outcome
1842                // in memory for queue settlement without overwriting a concurrent
1843                // retirement or publication transaction.
1844                self.state.resource_block = Some(crate::run::ResourceBlock {
1845                    cause: crate::run::ResourceBlockCause::Other,
1846                    node: "start".into(),
1847                    kind: "worktree maintenance".into(),
1848                    detail: detail.clone(),
1849                    at: Timestamp::now(),
1850                });
1851                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1852            }
1853        };
1854        let disk = RunState::load(&self.state.id)?;
1855        crate::pr_head::ensure_owner(&disk)?;
1856        let now = Timestamp::now();
1857        let home = crate::run::home();
1858        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1859        let assessment = disk.assess_liveness_under(&home, claim, now);
1860        // Only proven-live ownership refuses here. Unknown records (legacy runs
1861        // with no claim marker or process identity) fall through to the
1862        // exclusive execution lease taken just below, which is what actually
1863        // keeps a second driver out.
1864        anyhow::ensure!(
1865            assessment.verdict != crate::run::Liveness::Live,
1866            "{}",
1867            assessment.live_driver_refusal()
1868        );
1869        if let Some(to) = &disk.released_to {
1870            bail!(
1871                "run {} cannot continue: its worktree was released to run {}",
1872                self.state.short(),
1873                crate::run::short_of(to)
1874            );
1875        }
1876        anyhow::ensure!(
1877            serde_json::to_value(&disk.base_sync_recovery)?
1878                == serde_json::to_value(&self.state.base_sync_recovery)?,
1879            "base recovery changed since this run was loaded; reload the saved run"
1880        );
1881        anyhow::ensure!(
1882            disk.sync_only_passes == self.state.sync_only_passes,
1883            "base-only synchronization changed since this run was loaded; reload the saved run"
1884        );
1885        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1886        let mut execution = DriverExecution {
1887            runner: self,
1888            driver,
1889        };
1890        // Declare after the execution guard: on any claim error this short
1891        // lock must drop before that guard reloads and releases ownership.
1892        let _owner = owner;
1893        if let Some(request) = sync_only {
1894            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1895            anyhow::ensure!(
1896                request.run == disk.id,
1897                "sync-base-only request targets a different run"
1898            );
1899            let state = &mut execution.runner.state;
1900            let task_entry = state.next_pass_task_entry;
1901            *state = disk;
1902            state.next_pass_task_entry = task_entry;
1903            if state.pending_sync_only().is_some() {
1904                let pass_index = state.passes.len();
1905                let pass = state.sync_only_passes.last_mut().unwrap();
1906                anyhow::ensure!(
1907                    pass.request == request,
1908                    "interrupted base-only synchronization belongs to a different request"
1909                );
1910                pass.pass_index = pass_index;
1911            } else {
1912                let pass = crate::base_sync_only::Pass::new(request, state);
1913                state.sync_only_passes.push(pass);
1914            }
1915            if state.status == RunStatus::Failed {
1916                state.status = RunStatus::Blocked;
1917            }
1918        } else {
1919            anyhow::ensure!(
1920                disk.pending_sync_only().is_none(),
1921                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1922            );
1923            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1924                .await?;
1925        }
1926        let state = &mut execution.runner.state;
1927        // Moving again, so it is no longer parked. Set before the walk rather
1928        // than in `resume`, so every way of re-entering the graph clears it
1929        // and a card cannot claim a run is waiting to be resumed while the
1930        // agents are already working.
1931        state.parked = false;
1932        state.resource_wait = None;
1933        state.resource_block = None;
1934        // Any seat this state still lists as answering belongs to whatever
1935        // process last drove this run — this one included, if it crashed
1936        // mid-wave. Cleared and flushed immediately, before anything else
1937        // runs, so a resume can never show a seat as live when nothing is
1938        // asking it anything yet; the node that actually dispatches the next
1939        // wave repopulates it.
1940        state.clear_active();
1941        // Recorded in the same spot, and flushed together with the clear
1942        // above: this is the pid a reader checks (`RunState::liveness`) when
1943        // no daemon claim exists to answer "is a process still driving this
1944        // run" — a plain `magi run` / `magi review` typed into a terminal
1945        // claims nothing there. Always overwritten, never only-if-absent, so
1946        // a resumed run's stale pid from a previous, possibly-dead process
1947        // can never survive into this one's own report. Unlike
1948        // `clear_active`, this changes on every single `execute()` call, so
1949        // the save below is now unconditional rather than only-if-cleared.
1950        //
1951        // `driver_started_at` is recorded in the same breath, from this same
1952        // pid, so `liveness` can tell a live pid that is genuinely still us
1953        // apart from one the OS has since handed to an unrelated process —
1954        // see that field's own doc for why the pid alone is not enough.
1955        let pid = std::process::id();
1956        state.driver_pid = Some(pid);
1957        state.driver_started_at = crate::proc::process_started_at(pid);
1958        state.driver_exited = false;
1959        state.driver_claimed = Some(true);
1960        state.begin_pass();
1961        execution.driver.bind(state);
1962        state.save()?;
1963        execution.driver.record(state)?;
1964        Ok(execution)
1965    }
1966
1967    /// No conflict checkpoint proves dispatch was never reached. End that
1968    /// consumed generation so an owner can explicitly authorize a fresh one.
1969    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1970        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1971        if let Err(error) = &result
1972            && !error.is::<crate::repo_lock::ResourceBlocked>()
1973            && self
1974                .state
1975                .repair_grants
1976                .last()
1977                .is_some_and(|g| g.conflict.is_none())
1978        {
1979            self.state.repair_grants.last_mut().unwrap().phase =
1980                crate::repair_budget::Phase::Complete;
1981            self.state.status = RunStatus::Blocked;
1982            self.state.save()?;
1983            bail!(
1984                "{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",
1985                self.state.passes.last().map_or(0, |p| p.index)
1986            );
1987        }
1988        result
1989    }
1990
1991    /// A grant owns only these repair attempts. Confirmation reviews cannot
1992    /// create another fixer allowance, and every operation is restart-checkpointed.
1993    async fn execute_granted_repair(&mut self) -> Result<()> {
1994        use crate::repair_budget::{Kind, Phase};
1995        let index = self.state.repair_grants.len() - 1;
1996        let winner = self
1997            .state
1998            .winner()
1999            .cloned()
2000            .context("repair winner missing")?;
2001        loop {
2002            let grant = self.state.repair_grants[index].clone();
2003            match grant.phase {
2004                Phase::Pending => {
2005                    if grant.spent >= grant.receipt.request.rounds {
2006                        self.state.repair_grants[index].phase = Phase::Complete;
2007                        self.state.status = RunStatus::Blocked;
2008                        self.state.save()?;
2009                        return Ok(());
2010                    }
2011                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
2012                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
2013                            .await?;
2014                    }
2015                    // Reserve before dispatch. A crash can consume an attempt,
2016                    // but can never duplicate it or reset saved fixer history.
2017                    self.state.repair_grants[index].spent += 1;
2018                    self.state.repair_grants[index].phase = Phase::Fixing;
2019                    self.state.save()?;
2020                    match grant.receipt.request.kind {
2021                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
2022                        Kind::Gate => {
2023                            let failed = self.state.gate.clone();
2024                            let _ = self.gate_fix_round(&winner, &failed).await?;
2025                        }
2026                        Kind::Review => {
2027                            let mut record = self
2028                                .state
2029                                .reviews
2030                                .last()
2031                                .cloned()
2032                                .context("review failure missing")?;
2033                            let round = record.round;
2034                            let step = self.run_fix_round(&winner, &mut record).await?;
2035                            self.state.reviews[round - 1] = record;
2036                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2037                                self.state.repair_grants[index].phase = Phase::Complete;
2038                                self.state.status = RunStatus::Blocked;
2039                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2040                                self.state.save()?;
2041                                return Ok(());
2042                            }
2043                            if matches!(step, FixStep::Resource) {
2044                                self.stop_for_resource()?;
2045                                return Ok(());
2046                            }
2047                            self.state.save()?;
2048                        }
2049                    }
2050                    if self.resource_halt()? {
2051                        return Ok(());
2052                    }
2053                }
2054                Phase::Fixing => {
2055                    if grant.receipt.request.kind == Kind::BaseConflict {
2056                        self.repair_base_conflict(false).await?;
2057                    }
2058                    // Interrupted fixers may have left source changes or an
2059                    // unpushed commit. Preserve them before fresh assessment.
2060                    let _coordination = self.coordinate(&winner.worktree).await?;
2061                    let rescued = git::rescue_commit(
2062                        &winner.worktree,
2063                        "magi: preserve interrupted granted repair",
2064                    )
2065                    .await?;
2066                    self.state.note_withheld("repair-grant", &rescued.withheld);
2067                    // Fresh checks must supersede even a same-head failure.
2068                    // Archive rather than erase failure evidence or counters.
2069                    self.state
2070                        .verification_history
2071                        .push(crate::run::VerificationEvidence {
2072                            superseded_by: None,
2073                            archived_at: Some(Timestamp::now()),
2074                            fixes_spent: Some(self.state.gate_fixes.len()),
2075                            gate_head: self.state.gate_head.take(),
2076                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2077                            gate: std::mem::take(&mut self.state.gate),
2078                            e2e: self.state.head_e2e.take(),
2079                        });
2080                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2081                        self.state
2082                            .verification_history
2083                            .push(crate::run::VerificationEvidence {
2084                                superseded_by: None,
2085                                archived_at: Some(Timestamp::now()),
2086                                fixes_spent: Some(self.state.gate_fixes.len()),
2087                                gate_head: None,
2088                                gate_ran: false,
2089                                gate: Vec::new(),
2090                                e2e: Some(e2e),
2091                            });
2092                    }
2093                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2094                    self.state.repair_grants[index].head =
2095                        git::rev_parse(&winner.worktree, "HEAD").await?;
2096                    self.state.repair_grants[index].phase = Phase::Reviewing;
2097                    if grant.receipt.request.kind == Kind::BaseConflict {
2098                        self.state.base_sync_recovery.stop = None;
2099                        if let Some(sync) = &mut self.state.base_sync {
2100                            sync.tip = grant
2101                                .receipt
2102                                .request
2103                                .tip
2104                                .clone()
2105                                .context("repair base tip missing")?;
2106                            sync.conflict = None;
2107                            sync.behind = 0;
2108                        }
2109                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2110                    }
2111                    self.state.save()?;
2112                }
2113                Phase::Reviewing => {
2114                    self.review_loop_pass().await?;
2115                    if self.resource_halt()? {
2116                        return Ok(());
2117                    }
2118                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2119                    let reviewed = (self.state.reviews.len() > grant.review_start)
2120                        .then(|| self.state.reviews.last())
2121                        .flatten();
2122                    let review_passed = reviewed.is_some_and(|r| {
2123                        r.clean
2124                            && r.expected > 0
2125                            && r.answered == r.expected
2126                            && matches!(
2127                                r.e2e_status(),
2128                                E2eStatus::Passed | E2eStatus::NotConfigured
2129                            )
2130                            && ((r.e2e_status() == E2eStatus::NotConfigured
2131                                && self.state.config.verify.e2e.is_empty())
2132                                || r.verified_head.as_deref() == Some(head.as_str()))
2133                    });
2134                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2135                    if !clean {
2136                        let next = if review_passed
2137                            && let Some(r) = reviewed
2138                            && r.head != head
2139                        {
2140                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2141                                &self.state,
2142                                r,
2143                                &head,
2144                            )
2145                            .await
2146                            .map(|_| Some(Phase::Reviewing))
2147                        } else if grant.receipt.request.kind == Kind::Review
2148                            && grant.spent < grant.receipt.request.rounds
2149                        {
2150                            crate::repair_budget::prove_review_target(&self.state, &head)
2151                                .await
2152                                .map(|_| Some(Phase::Pending))
2153                        } else {
2154                            Ok(None)
2155                        };
2156                        let next = match next {
2157                            Ok(next) => next,
2158                            Err(error) => {
2159                                if self.state.repair_grants[index]
2160                                    .checkpoint_provenance_retry(&head, &error)
2161                                {
2162                                    self.state.status = RunStatus::Blocked;
2163                                    self.state.event("repair-grant", format!(
2164                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2165                                    ));
2166                                    self.state.save()?;
2167                                    return Ok(());
2168                                }
2169                                None
2170                            }
2171                        };
2172                        if next == Some(Phase::Reviewing) {
2173                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2174                            self.state.repair_grants[index].head = head;
2175                            self.state.repair_grants[index].phase = Phase::Reviewing;
2176                            self.state.status = RunStatus::Blocked;
2177                            self.state.event(
2178                                "repair-grant",
2179                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2180                            );
2181                            self.state.save()?;
2182                            return Ok(());
2183                        }
2184                        // A confirmation review carries no additional fix budget.
2185                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2186                            self.state.repair_grants[index].head = head;
2187                            Phase::Pending
2188                        } else {
2189                            Phase::Complete
2190                        };
2191                        self.state.status = RunStatus::Blocked;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "fresh review did not clear the repaired head; no publication",
2195                        );
2196                        self.state.save()?;
2197                        if self.state.repair_grants[index].phase == Phase::Pending {
2198                            continue;
2199                        }
2200                        return Ok(());
2201                    }
2202                    self.state.repair_grants[index].phase = Phase::Gating;
2203                    self.state.save()?;
2204                }
2205                Phase::Gating => {
2206                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    self.state.reconcile_verification_head(&head);
2208                    let wait = self.repository_wait();
2209                    if self
2210                        .state
2211                        .reviews
2212                        .last()
2213                        .is_none_or(|r| r.head != head || !r.clean)
2214                    {
2215                        self.state.status = RunStatus::Blocked;
2216                        self.state.repair_grants[index].phase = Phase::Complete;
2217                        self.state.event(
2218                            "repair-grant",
2219                            "head changed since fresh review; repair held",
2220                        );
2221                        self.state.save()?;
2222                        return Ok(());
2223                    }
2224                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2225                        return Ok(());
2226                    }
2227                    let outcomes = self.run_gate(&winner).await?;
2228                    if verify_inconclusive(&outcomes) {
2229                        return Ok(());
2230                    }
2231                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2232                    if after != head {
2233                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2234                        self.state.repair_grants[index].head = after;
2235                        self.state.repair_grants[index].phase = Phase::Reviewing;
2236                        self.state.status = RunStatus::Blocked;
2237                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2238                        self.state.save()?;
2239                        return Ok(());
2240                    }
2241                    let passed = outcomes.iter().all(CommandOutcome::ok);
2242                    // Follow-up grants owe the same guarded checkout delivery
2243                    // as the conflict repair that introduced the new head.
2244                    if passed
2245                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2246                    {
2247                        return Ok(());
2248                    }
2249                    self.state.repair_grants[index].succeeded = passed;
2250                    self.state.gate = outcomes;
2251                    self.state.gate_ran = true;
2252                    self.state.status = if passed {
2253                        RunStatus::Gating
2254                    } else {
2255                        RunStatus::Blocked
2256                    };
2257                    self.state.repair_grants[index].phase = if !passed
2258                        && grant.receipt.request.kind == Kind::Gate
2259                        && grant.spent < grant.receipt.request.rounds
2260                    {
2261                        Phase::Pending
2262                    } else {
2263                        Phase::Complete
2264                    };
2265                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2266                        // Persist publication debt with the successful checkpoint.
2267                        self.state.pr_publication_pending = true;
2268                    } else if passed {
2269                        self.state.status = RunStatus::Ready;
2270                    }
2271                    self.state.save()?;
2272                    if !passed {
2273                        continue;
2274                    }
2275                    // Existing PR ownership and push lease stay in place. The
2276                    // normal publisher owes the new reviewed/gated SHA, and
2277                    // land's fresh owner approval remains mandatory.
2278                    if self.state.config.merge.mode != MergeMode::Pr {
2279                        self.state.status = RunStatus::Ready;
2280                        self.state.event(
2281                            "repair-grant",
2282                            "repair verified locally; grant carries no merge authorization",
2283                        );
2284                        self.state.save()?;
2285                        return Ok(());
2286                    }
2287                    return self.merge().await;
2288                }
2289                Phase::Complete => return Ok(()),
2290            }
2291        }
2292    }
2293
2294    async fn execute_graph(&mut self) -> Result<()> {
2295        // Even a terminal run may reenter through an explicit recovery action.
2296        // Restore before prep shortcuts, saved conversations or graph nodes use
2297        // a disposable path; GC may already have removed its original objects.
2298        let archive_home = crate::run::home().canonicalize()?;
2299        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2300            let repo = self.state.repo.clone();
2301            let _coordination = self.coordinate(&repo).await?;
2302            ensure_setup_config(&mut self.state, &repo).await?;
2303            crate::retention::restore_execution_seats(
2304                &archive_home,
2305                &self.state,
2306                _coordination.as_ref(),
2307            )
2308            .await?;
2309        }
2310        self.state.configure_recovery_resume()?;
2311        // A revision is not reviewed until its own repair completes. No
2312        // other resume checkpoint may reuse the preceding instruction's review.
2313        if let Some(revision) = self.state.unfinished_instruction_revision() {
2314            if self.state.merge_repairs.last().is_some_and(|repair| {
2315                repair.question == revision.repair
2316                    && matches!(
2317                        repair.phase,
2318                        crate::run::MergeRepairPhase::Requested
2319                            | crate::run::MergeRepairPhase::Fixing
2320                            | crate::run::MergeRepairPhase::Reviewing
2321                    )
2322            }) {
2323                if self.repair_merge_review().await? {
2324                    self.run_land().await?;
2325                }
2326                self.settle_questions();
2327            } else {
2328                self.state.status = RunStatus::Blocked;
2329                self.state.parked = false;
2330                self.state.event("repair", "instruction revision repair did not complete; normal resume cannot land it. Inspect the retained branch and explicitly recover the PR for a fresh review of the revised instruction");
2331                self.state.save()?;
2332            }
2333            return Ok(());
2334        }
2335        if self
2336            .state
2337            .repair_grants
2338            .last()
2339            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2340        {
2341            return self.execute_granted_repair().await;
2342        }
2343        if self
2344            .state
2345            .repair_grants
2346            .last()
2347            .is_some_and(|g| !g.succeeded)
2348        {
2349            self.state.status = RunStatus::Blocked;
2350            self.state.save()?;
2351            return Ok(());
2352        }
2353        // Preservation may invalidate an old empty classification. Resolve it
2354        // before any resume shortcut can reuse a verdict or publish a branch.
2355        self.persist_candidates().await?;
2356        // A saved base stop outranks stage markers, including legacy Voting.
2357        // Recovery never reenters implementation, deliberation or voting.
2358        if self.state.base_sync_blocked() {
2359            self.sync_to_base().await?;
2360            if !self.state.base_sync_blocked()
2361                && self.state.status != RunStatus::AlreadyInBase
2362                && !self.resource_halt()?
2363            {
2364                self.finish_after_tally().await?;
2365            }
2366            return Ok(());
2367        }
2368        if self
2369            .state
2370            .merge_decision
2371            .as_ref()
2372            .is_some_and(|decision| !decision.closed)
2373            && self.state.status != RunStatus::Landing
2374        {
2375            if crate::merge_decision::resumable_hold(&self.state) {
2376                self.state.merge = Some(MergeOutcome {
2377                    mode: MergeMode::Pr,
2378                    ok: false,
2379                    detail: self
2380                        .state
2381                        .merge_decision
2382                        .as_ref()
2383                        .unwrap()
2384                        .target
2385                        .pr
2386                        .clone(),
2387                    empty: false,
2388                });
2389                self.run_land().await?;
2390                self.settle_questions();
2391                return Ok(());
2392            }
2393            bail!(
2394                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2395            );
2396        }
2397        if self.state.config.graph.selected_implementer.is_some()
2398            && self.state.status == RunStatus::Blocked
2399            && self.state.tally.is_none()
2400            && self.state.candidate_preservation.is_empty()
2401            && self.state.interrupted_implementations.is_empty()
2402        {
2403            bail!(
2404                "selected implementation is held; explicitly release the owning task to retry it"
2405            );
2406        }
2407
2408        if self.state.merge_repairs.last().is_some_and(|r| {
2409            matches!(
2410                r.phase,
2411                crate::run::MergeRepairPhase::Requested
2412                    | crate::run::MergeRepairPhase::Fixing
2413                    | crate::run::MergeRepairPhase::Reviewing
2414            )
2415        }) {
2416            if self.repair_merge_review().await? {
2417                self.run_land().await?;
2418            }
2419            self.settle_questions();
2420            return Ok(());
2421        }
2422        // Publication already passed review and gate. Resume only that node:
2423        // syncing to a newer base here could change the verified commit.
2424        if self.state.pr_publication_pending {
2425            self.merge().await?;
2426            if self.resource_halt()? {
2427                return Ok(());
2428            }
2429            self.state.save()?;
2430            self.settle_questions();
2431            return Ok(());
2432        }
2433        // A run that already lost its quorum never resumes into the verdict
2434        // machinery: `deliberate` and `vote` would otherwise clobber the
2435        // stalled marker back to Voting and the run would keep going past a
2436        // verdict that is no longer trustworthy. Everything already recorded is
2437        // kept, so the run stays resumable (or foldable) for a human to pick up.
2438        //
2439        // On --resume the run gets one chance to repair itself: the seats a
2440        // rate limit took out are re-asked. If their quota has since reset and
2441        // the quorum is restored, the run picks up and finishes; otherwise it
2442        // stays stale and still-resumable for a later retry. If it does not
2443        // recover, the returned status stays `Stalled` and nothing was
2444        // clobbered (the recovery only mutates entries for the lost seats).
2445        if self.state.status == RunStatus::Stalled {
2446            if self.recover_stall().await? {
2447                self.finish_after_tally().await?;
2448            } else {
2449                // Still below quorum: persist the marker and stay resumable.
2450                self.state.save()?;
2451            }
2452            return Ok(());
2453        }
2454        // A run parked inside `land` - watching CI, mid fix-round, or
2455        // waiting on the owner's merge approval - resumes directly into it,
2456        // never back through `prep`. Everything before `merge` already
2457        // concluded; that is the only way `status` reaches `Landing` in the
2458        // first place. Re-walking `review_loop` first would also be actively
2459        // wrong: its own status recomputation (see its doc) treats any
2460        // clean round as reason to set `status` to `Gating`, which would
2461        // clobber this marker before `merge` ever ran, and this run would
2462        // never find its way back into `land` at all.
2463        if self.state.status == RunStatus::Landing
2464            || crate::handover::landing_checkpoint(&self.state)
2465        {
2466            self.state.land_sync_pending = true;
2467            self.state.save()?;
2468            self.run_land().await?;
2469            // `run_land` may have settled the run right here - CI came back
2470            // green and the PR merged, say - without ever passing back
2471            // through `merge`'s own trailing call. Whatever it left `status`
2472            // as is what this has to read.
2473            self.settle_questions();
2474            return Ok(());
2475        }
2476        // A run parked at `merge` on the owner's word about a withheld PR text
2477        // resumes straight into `merge`. Re-walking the tail would sync to the
2478        // base again (possibly rebasing, possibly spending the fixer) after the
2479        // gate had passed, and then push a tree nobody reviewed or gated.
2480        if self.state.github_text.is_some()
2481            && self.state.merge.is_none()
2482            && self.state.status == RunStatus::Gating
2483        {
2484            self.merge().await?;
2485            if self.resource_halt()? {
2486                return Ok(());
2487            }
2488            self.state.save()?;
2489            return Ok(());
2490        }
2491        // A resource stop left the reserved synchronization unfinished. Reconcile
2492        // its exact HEAD and base before starting any earlier graph stage.
2493        if self.state.pending_base_operation().is_some() {
2494            return self.finish_after_tally().await;
2495        }
2496        if let Err(e) = self.prep().await {
2497            if e.is::<crate::repo_lock::ResourceBlocked>() {
2498                return Err(e);
2499            }
2500            self.state.status = RunStatus::Blocked;
2501            self.state
2502                .prep_failure
2503                .get_or_insert_with(|| format!("{e:#}"));
2504            self.state
2505                .event("prep", format!("preparation stopped: {e:#}"));
2506            self.state.save()?;
2507            return Err(e);
2508        }
2509        if self.park_here()? {
2510            return Ok(());
2511        }
2512        self.advise().await?;
2513        if self.park_here()? {
2514            return Ok(());
2515        }
2516        self.implement().await?;
2517        if self.park_here()? {
2518            return Ok(());
2519        }
2520        // `after_implement` already saved the state and settled any open
2521        // questions when it set this; nothing later in the graph has
2522        // anything to judge.
2523        if self.state.status == RunStatus::VerifiedNoop {
2524            return Ok(());
2525        }
2526        self.judge().await?;
2527        if self.park_here()? {
2528            return Ok(());
2529        }
2530        self.deliberate().await?;
2531        if self.park_here()? {
2532            return Ok(());
2533        }
2534        self.vote().await?;
2535        if self.park_here()? {
2536            return Ok(());
2537        }
2538        self.tally()?;
2539        // A verdict that lost its quorum is not trustworthy: do not review,
2540        // gate, or merge on it. Everything already done is kept, so the run
2541        // stays resumable (or foldable); the human can replace the agent that
2542        // ran out of quota and pick it up.
2543        if self.state.status == RunStatus::Stalled {
2544            // Persist the stalled marker now — the normal end-of-execute save
2545            // below is below this early return, and without it a resumed run
2546            // would reload a pre-tally status and keep going.
2547            self.state.save()?;
2548            return Ok(());
2549        }
2550        self.finish_after_tally().await?;
2551        Ok(())
2552    }
2553
2554    /// A wave could not start its agents because a shared resource stayed busy
2555    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2556    /// resumable. Unstarted seats have no result; completed peers retain
2557    /// their saved candidate state.
2558    fn stop_for_resource(&mut self) -> Result<()> {
2559        // Resource acquisition observes cancellation inside a node. Complete
2560        // the same durable park as every other node boundary before returning.
2561        if self.pause.parked() || self.interrupt.parked() {
2562            self.park_here()?;
2563            return Ok(());
2564        }
2565        if self.state.resource_block.is_some() {
2566            self.state.status = RunStatus::Blocked;
2567        }
2568        self.state.save()
2569    }
2570
2571    /// Stop walking the graph if a node ended on a resource block.
2572    fn resource_halt(&mut self) -> Result<bool> {
2573        if self.state.resource_block.is_none() {
2574            return Ok(false);
2575        }
2576        self.stop_for_resource()?;
2577        Ok(true)
2578    }
2579
2580    /// Park here if asked to, recording it in the run's own timeline.
2581    ///
2582    /// Returns whether the caller should stop walking the graph. The state is
2583    /// saved either way by the node that just finished; this adds the event so
2584    /// the operator's card says why a run that is neither finished nor moving
2585    /// is sitting where it is.
2586    fn park_here(&mut self) -> Result<bool> {
2587        let parking = self.pause.parked() || self.interrupt.parked();
2588        if !parking && self.state.resource_block.is_some() {
2589            self.stop_for_resource()?;
2590            return Ok(true);
2591        }
2592        // Either handle asking is enough - see `Pause`'s own doc for why
2593        // they are never the same one. `interrupt` is checked second so a
2594        // reason it carries is preferred in the message below over a plain
2595        // shutdown park racing it at the same boundary.
2596        if !self.pause.parked() && !self.interrupt.parked() {
2597            return Ok(false);
2598        }
2599        if self.state.parked {
2600            return Ok(true);
2601        }
2602        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2603        if let Some(block) = &mut self.state.resource_block
2604            && matches!(
2605                block.cause,
2606                crate::run::ResourceBlockCause::Cancelled { .. }
2607            )
2608        {
2609            block.cause = crate::run::ResourceBlockCause::Cancelled {
2610                park: cause.clone(),
2611            };
2612        }
2613        let why = match cause.as_ref().map(ParkCause::label) {
2614            Some(reason) => format!(
2615                "parked after `{}` ({reason}) — resume to carry on from here",
2616                self.state.status.as_str()
2617            ),
2618            None => format!(
2619                "parked after `{}` — resume to carry on from here",
2620                self.state.status.as_str()
2621            ),
2622        };
2623        self.state.event("park", why);
2624        self.state
2625            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2626        self.state.parked = true;
2627        self.state.save()?;
2628        Ok(true)
2629    }
2630
2631    /// Only a new explicit operator approval may retry failed preparation.
2632    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2633        if self.state.prep_failure.is_none() {
2634            return Ok(());
2635        }
2636        let failed_at = self
2637            .state
2638            .events
2639            .iter()
2640            .rev()
2641            .find(|event| event.node == "prep")
2642            .map_or(self.state.updated_at, |event| event.at);
2643        anyhow::ensure!(
2644            approval_at > failed_at,
2645            "preparation retry requires a new explicit release after the failure"
2646        );
2647        self.state.prep_failure = None;
2648        self.state.prep_complete = Some(false);
2649        self.state
2650            .event("prep-retry", "operator approved retry of preparation");
2651        Ok(())
2652    }
2653
2654    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2655    pub fn on_pause(&mut self, pause: Pause) {
2656        self.pause = pause;
2657    }
2658
2659    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2660    /// scheduler asking this one run - and no other - to park so a task
2661    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2662    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2663    /// handle.
2664    pub fn watch_interrupt(&mut self, pause: Pause) {
2665        self.interrupt = pause;
2666    }
2667
2668    /// Abandon this run's own open questions, once `status` has actually
2669    /// settled rather than merely paused.
2670    ///
2671    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2672    /// either back up with the candidates, the review round and the seat
2673    /// sessions already on disk, so a question an implementer asked mid-round
2674    /// may still get a real answer read by a real resume. Only the statuses
2675    /// `resumable` excludes are actually final: the run merged, it reached
2676    /// `Ready` with nothing left to do, it failed outright with no
2677    /// established point to continue from, or every candidate agreed, with
2678    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2679    /// every one of those the seat that asked is gone for good, exactly like
2680    /// the run being deleted under `magi run rm` - so the same cleanup
2681    /// applies, worded for what actually happened instead of "the run was
2682    /// deleted".
2683    ///
2684    /// Best-effort and silent on success: called from every place `status`
2685    /// can land on one of those three, including ones a resumed run revisits,
2686    /// so it must cost nothing when there was nothing open to begin with.
2687    fn settle_questions(&mut self) {
2688        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2689            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2690        }
2691    }
2692
2693    /// The tail of the graph after a trustworthy tally: fold losers, review,
2694    /// gate, merge, and persist.
2695    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2696        Box::pin(self.finish_after_tally_inner())
2697    }
2698
2699    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2700        // Before the losers are folded: their branches are what the graft
2701        // reads from.
2702        self.graft().await?;
2703        if self.resource_halt()? {
2704            return Ok(());
2705        }
2706        self.fold_losers().await?;
2707        // Before review starts, and again right before the gate: a run's
2708        // review rounds can themselves take long enough for the base to move
2709        // a second time, and the gate is the one node whose "green" gets
2710        // acted on.
2711        self.sync_to_base().await?;
2712        if self.hold_base_sync().await? || self.resource_halt()? {
2713            return Ok(());
2714        }
2715        if self.state.status == RunStatus::AlreadyInBase {
2716            return Ok(());
2717        }
2718        self.review_loop().await?;
2719        if self.resource_halt()? {
2720            return Ok(());
2721        }
2722        self.sync_to_base().await?;
2723        if self.hold_base_sync().await? || self.resource_halt()? {
2724            return Ok(());
2725        }
2726        if self.state.status == RunStatus::AlreadyInBase {
2727            return Ok(());
2728        }
2729        self.gate().await?;
2730        self.merge().await?;
2731        if self.resource_halt()? {
2732            return Ok(());
2733        }
2734        self.state.save()?;
2735        Ok(())
2736    }
2737
2738    // ---------------------------------------------------------------- prep
2739
2740    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2741    /// run with the step and its output in the event; it is never swallowed.
2742    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2743    /// resume starts over instead of finding candidates and missing seats.
2744    async fn setup_seat_worktree(
2745        &mut self,
2746        repo: &Path,
2747        wt: &Path,
2748        in_prep: bool,
2749        coordination: Option<&crate::repo_lock::SeatLease>,
2750    ) -> Result<()> {
2751        let result = match ensure_setup_config(&mut self.state, repo).await {
2752            Ok(()) => {
2753                worktree_setup::prepare_with(
2754                    &self.state.config,
2755                    repo,
2756                    wt,
2757                    crate::build_target::Coordination::Held(coordination),
2758                )
2759                .await
2760            }
2761            Err(e) => Err(e),
2762        };
2763        if let Err(e) = result {
2764            git::worktree_remove_clean(repo, wt).await.ok();
2765            if in_prep {
2766                self.rollback_prep(repo).await;
2767            }
2768            self.state.status = RunStatus::Blocked;
2769            self.state.event(
2770                "setup",
2771                format!("worktree setup failed in {}: {e:#}", wt.display()),
2772            );
2773            self.state.save()?;
2774            return Err(e);
2775        }
2776        Ok(())
2777    }
2778
2779    /// Undo everything `prep` created, so a resume re-runs it whole.
2780    async fn rollback_prep(&mut self, repo: &Path) {
2781        let root = self.state.worktree_root();
2782        for c in std::mem::take(&mut self.state.candidates) {
2783            if matches!(
2784                git::worktree_remove_clean(repo, &c.worktree).await,
2785                Ok(true)
2786            ) {
2787                git::branch_delete(repo, &c.branch).await.ok();
2788            } else {
2789                self.state.candidates.push(c);
2790            }
2791        }
2792        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2793        for j in 1..=seats {
2794            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2795                .await
2796                .ok();
2797        }
2798        for k in 1..=self.state.config.graph.advisors {
2799            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2800                .await
2801                .ok();
2802        }
2803    }
2804
2805    async fn prep(&mut self) -> Result<()> {
2806        if let Some(reason) = &self.state.prep_failure {
2807            bail!(
2808                "candidate preparation previously failed: {reason}; correct the source before retrying"
2809            );
2810        }
2811        if self
2812            .state
2813            .prep_complete
2814            .unwrap_or(!self.state.candidates.is_empty())
2815        {
2816            return Ok(());
2817        }
2818        let repo = self.state.repo.clone();
2819        // Includes rollback, config, refs, checkout creation and setup. No
2820        // repository mutation may precede the real shared lock acquisition.
2821        let _coordination = self.coordinate(&repo).await?;
2822        let base = self.state.base_commit.clone();
2823        let plan = self.state.sources.plan(&repo, &base).await?;
2824        self.rollback_prep(&repo).await;
2825        if !self.state.candidates.is_empty() {
2826            bail!(
2827                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2828            );
2829        }
2830        self.state.prep_complete = Some(false);
2831        self.state.status = RunStatus::Prep;
2832        self.state.save()?;
2833        let repo = self.state.repo.clone();
2834        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2835        let root = self.state.worktree_root();
2836        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2837
2838        // The hook is the write-time half of the blindness contract; the
2839        // presentation filter in `blind` is the half that cannot be bypassed.
2840        let hooks_dir = self.state.dir().join("hooks");
2841        if self.state.config.blind.commit_msg_hook {
2842            std::fs::create_dir_all(&hooks_dir)
2843                .with_context(|| format!("create {}", hooks_dir.display()))?;
2844            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2845            let path = hooks_dir.join("commit-msg");
2846            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2847            make_executable(&path)?;
2848            // Ref-counted rather than a plain idempotent set: with more than
2849            // one run able to be in flight in the same repository at once
2850            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2851            // true?" check cannot tell "another run of mine still needs
2852            // this" from "nobody does", and the run that happens to finish
2853            // first would disable the hook out from under a sibling still
2854            // relying on it.
2855            git::acquire_worktree_config(&repo).await?;
2856            self.state.enabled_worktree_config = true;
2857        }
2858
2859        // `[worktree] setup` hides its products per worktree, which needs the
2860        // same per-worktree config the hook does. Held until fold, like it.
2861        ensure_setup_config(&mut self.state, &repo).await?;
2862
2863        for (index, (spec, label)) in self
2864            .roles
2865            .implementers
2866            .clone()
2867            .into_iter()
2868            .zip(labels)
2869            .enumerate()
2870        {
2871            let branch = self.state.branch_for(label);
2872            let worktree = root.join(format!("cand-{label}"));
2873            // Persist intent before Git can leave a partially created tree.
2874            // Candidate registration follows setup, so it cannot inventory
2875            // crashes or refusals during creation itself.
2876            self.state.event(
2877                "prep-intent",
2878                serde_json::json!({
2879                    "branch": branch,
2880                    "worktree": worktree,
2881                    "start": start,
2882                    "picks": plan.picks,
2883                })
2884                .to_string(),
2885            );
2886            self.state.save()?;
2887            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2888            if self.state.config.blind.commit_msg_hook {
2889                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2890            }
2891            git::local_exclude(&worktree, "/.magi/").await?;
2892            if let Err(e) = worktree_setup::prepare_with(
2893                &self.state.config,
2894                &repo,
2895                &worktree,
2896                crate::build_target::Coordination::Held(_coordination.as_ref()),
2897            )
2898            .await
2899            {
2900                // Nothing of this prep may survive: a resume must start over,
2901                // not find half the candidates and skip the rest.
2902                git::worktree_remove_clean(&repo, &worktree).await.ok();
2903                git::branch_delete(&repo, &branch).await.ok();
2904                self.rollback_prep(&repo).await;
2905                self.state.status = RunStatus::Blocked;
2906                self.state
2907                    .event("prep", format!("worktree setup failed: {e:#}"));
2908                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2909                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2910                }
2911                self.state.save()?;
2912                return Err(e);
2913            }
2914            self.state.candidates.push(Candidate {
2915                index,
2916                label,
2917                agent: spec.id.clone(),
2918                branch,
2919                worktree,
2920                summary: String::new(),
2921                stat: String::new(),
2922                files: 0,
2923                commits: 0,
2924                empty: false,
2925                failed: None,
2926                verified_noop: None,
2927                duration_ms: 0,
2928                folded: false,
2929            });
2930            self.state.save()?;
2931            for pick in &plan.picks {
2932                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2933                {
2934                    self.state.status = RunStatus::Blocked;
2935                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2936                    self.state
2937                        .event("prep", format!("cannot apply referenced commit: {e}"));
2938                    self.state.save()?;
2939                    return Err(e);
2940                }
2941            }
2942        }
2943
2944        for j in 1..=self.roles.judges.len() {
2945            let wt = root.join(format!("judge-{j}"));
2946            if !wt.exists() {
2947                git::worktree_add_detached(&repo, &wt, &base).await?;
2948                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2949                    .await?;
2950            }
2951        }
2952
2953        // Disposable, detached checkouts for the design-deliberation stage's
2954        // advisor seats — the same shape as the judges' above, at the same
2955        // base commit, since advisors also only ever read. Sized off the
2956        // configured count directly rather than a resolved roster: unlike
2957        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2958        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2959        // `prep` has no `ResolvedRoles` field to read a count from here.
2960        if self.state.config.graph.advise {
2961            for k in 1..=self.state.config.graph.advisors {
2962                let wt = root.join(format!("advisor-{k}"));
2963                if !wt.exists() {
2964                    git::worktree_add_detached(&repo, &wt, &base).await?;
2965                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2966                        .await?;
2967                }
2968            }
2969        }
2970
2971        // A judge cannot tell it is looking at its own patch — the seats keep
2972        // separate conversations — but a panel that shares agents with the
2973        // field is less independent than it looks, and that is worth saying out
2974        // loud once per run rather than leaving it in the config.
2975        let authors: Vec<&str> = self
2976            .roles
2977            .implementers
2978            .iter()
2979            .map(|a| a.id.as_str())
2980            .collect();
2981        let overlap: Vec<String> = self
2982            .roles
2983            .judges
2984            .iter()
2985            .enumerate()
2986            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2987            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2988            .collect();
2989        if !overlap.is_empty() {
2990            let note = format!(
2991                "{} also authored a candidate; blind, but the panel is less \
2992                 independent than {} distinct agents would be",
2993                overlap.join(", "),
2994                self.roles.judges.len()
2995            );
2996            self.state.event("prep", note);
2997        }
2998
2999        self.state.event(
3000            "prep",
3001            format!(
3002                "{} candidates, {} judges, base {} ({})",
3003                self.state.candidates.len(),
3004                self.roles.judges.len(),
3005                &self.state.base_commit[..7.min(self.state.base_commit.len())],
3006                self.state.base_branch
3007            ),
3008        );
3009        self.state.prep_complete = Some(true);
3010        self.state.status = RunStatus::Implementing;
3011        self.state.save()?;
3012        Ok(())
3013    }
3014
3015    // -------------------------------------------------------------- advise
3016
3017    /// The design-deliberation stage: independent, read-only advisor seats
3018    /// each sketch a design before any implementer touches the repository,
3019    /// and (when at least one produced a usable proposal) a synthesis seat
3020    /// blends them into a brief `implement` carries in every candidate's
3021    /// prompt.
3022    ///
3023    /// `[graph] advise` is the on/off switch, on by default; `[graph]
3024    /// advisors` is the proposal count. Everything here is best-effort and
3025    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
3026    /// that cannot reach quota, or a synthesis seat that produced nothing
3027    /// usable all leave `implement` exactly as it was before this stage
3028    /// existed — the task instruction alone — rather than failing the whole
3029    /// competition over an enrichment stage. Every outcome is still recorded
3030    /// as an event, so a run that got nothing from this stage says why.
3031    ///
3032    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
3033    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
3034    /// resumed run whose stage failed would re-run it, and re-spend the
3035    /// agent calls, on every reentry before `implement`.
3036    ///
3037    /// Also skipped once any candidate shows implementation progress — the
3038    /// exact predicate `implement` itself uses to decide a candidate is no
3039    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
3040    /// is not enough: a run created by an older binary that predates this
3041    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
3042    /// an already-`Implementing`-or-later run under this build would
3043    /// otherwise walk straight back through `prep` (a no-op once candidates
3044    /// exist) into this node and spawn every advisor seat against worktrees
3045    /// `prep` never recreated — after implementation has already started,
3046    /// which is exactly the invariant this stage exists to guarantee.
3047    async fn advise(&mut self) -> Result<()> {
3048        let implement_untouched = self
3049            .state
3050            .candidates
3051            .iter()
3052            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3053        if !self.state.config.graph.advise || self.state.advise_attempted {
3054            return Ok(());
3055        }
3056        if !implement_untouched {
3057            self.state.event(
3058                "advise",
3059                "skipping the design-deliberation stage: at least one \
3060                 candidate already shows implementation progress, so this \
3061                 run is past the point the stage exists to run before"
3062                    .to_owned(),
3063            );
3064            self.state.advise_attempted = true;
3065            self.state.save()?;
3066            return Ok(());
3067        }
3068        let run_id = self.state.id.clone();
3069        let prompts = self.state.config.prompts.clone();
3070        let instruction = self.state.instruction.clone();
3071        let language = self.state.config.graph.language.clone();
3072        let root = self.state.worktree_root();
3073        let n = self.state.config.graph.advisors;
3074        let where_recorded = self.state.dir().join("run.json");
3075
3076        let seats = match self.state.config.advisors() {
3077            Ok(seats) if !seats.is_empty() => seats,
3078            Ok(_) => {
3079                self.state.event(
3080                    "advise",
3081                    format!(
3082                        "[graph] advisors is 0; skipping the design-deliberation \
3083                         stage and continuing without a synthesis brief (see {})",
3084                        where_recorded.display()
3085                    ),
3086                );
3087                self.state.advise_attempted = true;
3088                self.state.save()?;
3089                return Ok(());
3090            }
3091            Err(e) => {
3092                self.state.event(
3093                    "advise",
3094                    format!(
3095                        "could not resolve advisor seats ({e:#}); continuing \
3096                         without a design-deliberation brief (see {})",
3097                        where_recorded.display()
3098                    ),
3099                );
3100                self.state.advise_attempted = true;
3101                self.state.save()?;
3102                return Ok(());
3103            }
3104        };
3105
3106        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3107        let artifacts = agent::artifacts_dir(&self.state.dir());
3108        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3109
3110        let mut jobs = Vec::new();
3111        for (i, spec) in seats.iter().cloned().enumerate() {
3112            let seat_key = format!("advisor-{}", i + 1);
3113            let seat = self.seat(&seat_key, &spec.id);
3114            jobs.push(SeatJob {
3115                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3116                spec,
3117                seat,
3118                cwd: worktrees[i % worktrees.len()].clone(),
3119                timeout,
3120                allow_write: false,
3121                sessions: false,
3122                artifacts: artifacts.clone(),
3123                stem: seat_key,
3124                handover: None,
3125            });
3126        }
3127
3128        self.state.event(
3129            "advise",
3130            format!(
3131                "{} advisor seat(s) sketching a design in parallel",
3132                jobs.len()
3133            ),
3134        );
3135        let mut quota_losses = Vec::new();
3136        let cache = self.state.config.cache_dir();
3137        let ctx = WaveCtx {
3138            carry_seats: false,
3139            pauses: Some((&self.pause, &self.interrupt)),
3140            run: &run_id,
3141            node: "advise",
3142            prompts: &prompts,
3143            cache: cache.as_deref(),
3144            round: None,
3145        };
3146        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3147        let results = ask_json_wave::<Proposal>(
3148            jobs,
3149            Arc::clone(&self.sem),
3150            self.state.config.graph.retries,
3151            &advisor_roster,
3152            &ctx,
3153            &mut quota_losses,
3154            &mut self.state,
3155            &|p: &Proposal| p.validate(),
3156        )
3157        .await;
3158        if self.state.resource_block.is_some() {
3159            return self.stop_for_resource();
3160        }
3161        self.state.quota.extend(quota_losses);
3162
3163        let mut records = Vec::with_capacity(results.len());
3164        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3165            let agent_id = seat.agent.clone();
3166            self.state.seats.insert(seat.key.clone(), seat);
3167            match res {
3168                Ok((proposal, out)) => {
3169                    self.state
3170                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3171                    records.push(advise::AdvisorRecord::proposed(
3172                        i + 1,
3173                        agent_id,
3174                        proposal,
3175                        out.duration_ms,
3176                    ));
3177                }
3178                Err(e) => {
3179                    self.state.event(
3180                        "advise",
3181                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3182                    );
3183                    records.push(advise::AdvisorRecord::failed(
3184                        i + 1,
3185                        agent_id,
3186                        e.to_string(),
3187                    ));
3188                }
3189            }
3190        }
3191
3192        let mut advice = advise::Advice {
3193            records,
3194            synthesis: None,
3195        };
3196        if advice.proposals().is_empty() {
3197            self.state.event(
3198                "advise",
3199                "no advisor produced a usable proposal; continuing without a \
3200                 synthesis brief"
3201                    .to_owned(),
3202            );
3203        } else {
3204            match self
3205                .synthesize_brief(
3206                    &advice,
3207                    &instruction,
3208                    &language,
3209                    &worktrees[0],
3210                    &artifacts,
3211                    &run_id,
3212                    &prompts,
3213                    cache.as_deref(),
3214                )
3215                .await
3216            {
3217                Ok(Some(text)) => {
3218                    self.state.event(
3219                        "advise",
3220                        "synthesized a design brief for the implementer".to_owned(),
3221                    );
3222                    advice.synthesis = Some(text);
3223                }
3224                Ok(None) => {
3225                    self.state.event(
3226                        "advise",
3227                        "the synthesis seat produced nothing usable; continuing \
3228                         without a design brief"
3229                            .to_owned(),
3230                    );
3231                }
3232                Err(e) => {
3233                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3234                        return Err(e);
3235                    }
3236                    self.state.event(
3237                        "advise",
3238                        format!("could not synthesize a design brief: {e:#}"),
3239                    );
3240                }
3241            }
3242        }
3243        advise::apply_reflection(&mut advice);
3244
3245        self.state.advice = Some(advice);
3246        self.state.advise_attempted = true;
3247        self.state.save()?;
3248        Ok(())
3249    }
3250
3251    /// The synthesis seat: reads every advisor's proposal and blends them
3252    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3253    /// out of [`Runner::advise`] only for readability — it is not called
3254    /// anywhere else.
3255    ///
3256    /// Picked the same way [`crate::talk`]'s standing conversation and
3257    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3258    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3259    /// order (a claude seat, else the first runnable agent in roster order)
3260    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3261    /// in [`crate::config`] for why a dedicated field exists here at all.
3262    #[allow(clippy::too_many_arguments)]
3263    async fn synthesize_brief(
3264        &mut self,
3265        advice: &advise::Advice,
3266        instruction: &str,
3267        language: &str,
3268        cwd: &Path,
3269        artifacts: &Path,
3270        run_id: &str,
3271        prompts: &Prompts,
3272        cache: Option<&Path>,
3273    ) -> Result<Option<String>> {
3274        let chain = agent::pick_chain(
3275            &self.state.config.agents,
3276            self.state.config.roles.synthesizer.as_ref(),
3277            &agent::installed,
3278            "synthesizer",
3279        )?;
3280        let proposals = advice.proposals();
3281        let mut prompt = prompt::with_overlay(
3282            prompt::synthesize_brief(instruction, &proposals, language),
3283            prompts.overlay("advise"),
3284        );
3285        if cache.is_some() {
3286            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3287            // below — see `prompt::build_cache_note`'s doc for why telling a
3288            // read-only seat to build through the shared cache is exactly how
3289            // a sandbox's write refusal gets misread as a defect.
3290            prompt.push('\n');
3291            prompt.push_str(&prompt::build_cache_note("advise", false));
3292        }
3293        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3294        // Each id is tried once, in order; a quota hit, error or unusable
3295        // answer moves to the next. The seat is single-turn (`sessions:
3296        // false`) and the prompt is the whole context, so a fallback agent
3297        // needs nothing carried over.
3298        let mut last = None;
3299        for (n, spec) in chain.iter().enumerate() {
3300            if n > 0 {
3301                self.state
3302                    .event("advise", format!("synthesis falling back to {}", spec.id));
3303            }
3304            let mut seat = self.seat("advise-synthesis", &spec.id);
3305            let wait = self.repository_wait();
3306            let outcome = wait
3307                .scope(agent::invoke(
3308                    spec,
3309                    &mut seat,
3310                    &Invocation {
3311                        coordination: self.state.config.coordination.as_ref(),
3312                        fetched_base: None,
3313                        cwd,
3314                        prompt: &prompt,
3315                        timeout,
3316                        allow_write: false,
3317                        sessions: false,
3318                        artifacts,
3319                        stem: &if n == 0 {
3320                            "advise-synthesis".to_owned()
3321                        } else {
3322                            format!("advise-synthesis-{}", spec.id)
3323                        },
3324                        run: run_id,
3325                        node: "advise",
3326                        cache_dir: None,
3327                        attachments: &[],
3328                        writable: &[],
3329                    },
3330                ))
3331                .await;
3332            if outcome.is_ok() {
3333                self.state.seats.insert(seat.key.clone(), seat);
3334            }
3335            let advance = agent::chain_advances(&outcome);
3336            last = Some(outcome);
3337            if !advance {
3338                break;
3339            }
3340        }
3341        // Exhausted: the last attempt's result is what a single failed seat
3342        // would have produced.
3343        let out = last.expect("a chain holds at least one agent")?;
3344        if !out.usable() {
3345            return Ok(None);
3346        }
3347        let text =
3348            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3349        Ok((!text.trim().is_empty()).then_some(text))
3350    }
3351
3352    // ----------------------------------------------------------- implement
3353
3354    async fn implement(&mut self) -> Result<()> {
3355        self.persist_candidates().await?;
3356        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3357        // agent files with `magi task add` name the run that paid for it. The
3358        // prompt overlay is cloned alongside it because the waves borrow it
3359        // while `self` is mutably borrowed by the node's own bookkeeping.
3360        let run_id = self.state.id.clone();
3361        let prompts = self.state.config.prompts.clone();
3362        let todo: Vec<usize> = self
3363            .state
3364            .candidates
3365            .iter()
3366            .enumerate()
3367            .filter(|(_, c)| {
3368                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3369                    && c.failed.is_none()
3370                    && !c.empty
3371            })
3372            .map(|(i, _)| i)
3373            .collect();
3374        if todo.is_empty() {
3375            return self.after_implement();
3376        }
3377        self.state.status = RunStatus::Implementing;
3378
3379        let language = self.state.config.graph.language.clone();
3380        let github_language = self.state.config.graph.github_language.clone();
3381        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3382        let sessions = self.state.config.graph.sessions;
3383        let artifacts = agent::artifacts_dir(&self.state.dir());
3384        // The design-deliberation stage's blended brief, when `advise` found
3385        // one — carried into every implementer's prompt the same way
3386        // regardless of which candidate it is.
3387        let brief = self
3388            .state
3389            .advice
3390            .as_ref()
3391            .and_then(|a| a.synthesis.as_deref())
3392            .map(str::to_owned);
3393        let attachments = self.state.attachments.clone();
3394
3395        let mut jobs = Vec::new();
3396        for &i in &todo {
3397            let (index, label, worktree) = {
3398                let c = &self.state.candidates[i];
3399                (c.index, c.label, c.worktree.clone())
3400            };
3401            let spec = self.roles.implementers[index].clone();
3402            let seat_key = format!("impl-{label}");
3403            let seat = self.seat(&seat_key, &spec.id);
3404            let instruction = seeded_instruction(&self.state);
3405            jobs.push(SeatJob {
3406                spec,
3407                seat,
3408                prompt: prompt::implement_in(
3409                    &instruction,
3410                    &worktree.to_string_lossy(),
3411                    &language,
3412                    &github_language,
3413                    brief.as_deref(),
3414                    &attachments,
3415                ),
3416                cwd: worktree,
3417                timeout,
3418                allow_write: true,
3419                sessions,
3420                artifacts: artifacts.clone(),
3421                stem: format!("impl-{label}"),
3422                handover: None,
3423            });
3424        }
3425
3426        self.state.event(
3427            "implement",
3428            format!("{} candidates in parallel", jobs.len()),
3429        );
3430        // Kept so a seat whose CLI hung up can be asked again from the same
3431        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3432        // can update a seat's own entry once a fallback agent takes it over —
3433        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3434        // whichever agent actually answered, not the one that quota'd out.
3435        let mut sent = jobs.clone();
3436        // Where each seat's checkout stood before its turn. A reply is judged
3437        // against this, never against the run's base: a tree that carries an
3438        // inherited patch is ahead of the base before the seat does anything.
3439        let mut baselines = Vec::with_capacity(sent.len());
3440        for (job, &i) in sent.iter().zip(&todo) {
3441            baselines.push((
3442                self.state.candidates[i].label,
3443                git::rev_parse(&job.cwd, "HEAD").await.ok(),
3444            ));
3445        }
3446        let cache = self.state.config.cache_dir();
3447        let ctx = WaveCtx {
3448            carry_seats: false,
3449            pauses: Some((&self.pause, &self.interrupt)),
3450            run: &run_id,
3451            node: "implement",
3452            prompts: &prompts,
3453            cache: cache.as_deref(),
3454            round: None,
3455        };
3456        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3457        if !wave_blocked(&results) {
3458            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3459                .await;
3460            self.retry_unstarted(&mut results, &sent, &baselines, &prompts, &run_id)
3461                .await?;
3462            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3463                .await?;
3464            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3465                .await;
3466        }
3467        // Do not finalize failed candidates when the entire wave needs machine
3468        // recovery: leaving them pending resumes this node with its work intact.
3469        if !results.is_empty()
3470            && results
3471                .iter()
3472                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3473        {
3474            let losses: Vec<_> = results
3475                .iter()
3476                .map(|(_, seat, out)| {
3477                    let AgentOutcome::Quota(o) = out else {
3478                        unreachable!()
3479                    };
3480                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3481                })
3482                .collect();
3483            self.state.quota.extend(losses.clone());
3484            for (_, seat, _) in results {
3485                self.state.seats.insert(seat.key.clone(), seat);
3486            }
3487            for &i in &todo {
3488                let label = self.state.candidates[i].label;
3489                self.state.interrupted_implementations.insert(label);
3490                self.state
3491                    .candidate_preservation
3492                    .insert(label, "machine outage awaiting persistence".into());
3493            }
3494            // Preserve partial edits too, while keeping every interrupted seat
3495            // pending even when its tree already contains an inherited patch.
3496            block_machine_outage(&mut self.state, "implement", &losses);
3497            self.state.save()?;
3498            self.persist_candidates().await?;
3499            for &i in &todo {
3500                self.state
3501                    .interrupted_implementations
3502                    .insert(self.state.candidates[i].label);
3503            }
3504            return self.stop_for_resource();
3505        }
3506        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3507
3508        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3509            && results
3510                .iter()
3511                .any(|(_, _, out)| FailClass::of(out).is_some());
3512        let base_commit = self.state.base_commit.clone();
3513        let blind_cfg = self.state.config.blind.clone();
3514        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3515        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3516            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3517                // Executed turns interrupted by disk pressure already carry
3518                // a preservation barrier from wave. Admission-only waits do
3519                // not. Keep the interrupted seat's session for recovery too.
3520                if self
3521                    .state
3522                    .candidate_preservation
3523                    .contains_key(&self.state.candidates[i].label)
3524                {
3525                    self.state.seats.insert(seat.key.clone(), seat);
3526                }
3527                continue;
3528            }
3529            let seat_key = seat.key.clone();
3530            // A quota fallback (`resume_seat_handovers`) may have handed this
3531            // seat to a different agent than the one `prep` recorded on the
3532            // candidate; the stats tables and any later fixer-defaults-to-
3533            // winner's-author lookup must credit whoever actually answered —
3534            // unless every fallback also quota'd out, in which case nobody
3535            // actually answered and crediting the last agent tried would
3536            // erase every earlier agent's own quota loss from the stats
3537            // tables instead of just this one seat's.
3538            let agent = seat.agent.clone();
3539            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3540            self.state.seats.insert(seat.key.clone(), seat);
3541            let label = self.state.candidates[i].label;
3542            let worktree = self.state.candidates[i].worktree.clone();
3543            self.state.interrupted_implementations.remove(&label);
3544
3545            let (sanitized_summary, duration, failed, verified_claim) = match out {
3546                AgentOutcome::Ok(o) => {
3547                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3548                    let failed = (!o.usable()).then(|| {
3549                        if o.timed_out {
3550                            "agent timed out".to_owned()
3551                        } else {
3552                            format!(
3553                                "agent exited with {}",
3554                                crate::notices::exit_status(o.exit_code)
3555                            )
3556                        }
3557                    });
3558                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3559                    let verified_claim = match verified_noop_claim_in_worktree(
3560                        failed.is_none(),
3561                        &o.commands,
3562                        &text,
3563                        &worktree,
3564                        &base_commit,
3565                    )
3566                    .await
3567                    {
3568                        NoopClaimVerdict::Accepted => {
3569                            if matches!(
3570                                verdict::parse_verified_noop(&sanitized_summary),
3571                                Some(Ok(_))
3572                            ) {
3573                                Some(sanitized_summary.clone())
3574                            } else {
3575                                rejected_noops.push((
3576                                    label,
3577                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3578                                ));
3579                                None
3580                            }
3581                        }
3582                        NoopClaimVerdict::Rejected(reason) => {
3583                            rejected_noops.push((label, reason));
3584                            None
3585                        }
3586                        NoopClaimVerdict::Absent => None,
3587                    };
3588                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3589                }
3590                // Left un-resumed by `resume_undelivered` (a dirty tree
3591                // already rescues the work, or there was no session left to
3592                // resume into) — reported like the ordinary failure it is,
3593                // never as if `o.text` (the CLI's raw error JSON) were an
3594                // answer.
3595                AgentOutcome::Dropped(o) => {
3596                    let why = o
3597                        .dropped
3598                        .as_ref()
3599                        .map(|d| d.why.as_str())
3600                        .unwrap_or("the CLI ended the stream without delivering its answer");
3601                    (
3602                        String::new(),
3603                        o.duration_ms,
3604                        Some(format!("the CLI dropped the stream ({why})")),
3605                        None,
3606                    )
3607                }
3608                AgentOutcome::Quota(o) => {
3609                    self.state.quota.push(QuotaLoss::from_report(
3610                        seat_key,
3611                        "implement",
3612                        o.quota.as_ref(),
3613                    ));
3614                    (
3615                        String::new(),
3616                        o.duration_ms,
3617                        Some("rate limited (quota); produced no change".to_owned()),
3618                        None,
3619                    )
3620                }
3621                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3622                    (String::new(), 0, Some(e), None)
3623                }
3624            };
3625
3626            // Save every completed turn before any fallible Git operation. A failed
3627            // rescue must not erase the reply or prevent collection of other seats.
3628            let c = &mut self.state.candidates[i];
3629            if !exhausted_the_fallback_chain {
3630                c.agent = agent;
3631            }
3632            c.summary = sanitized_summary;
3633            c.duration_ms = duration;
3634            c.failed = failed;
3635            c.verified_noop = verified_claim;
3636            self.state
3637                .candidate_preservation
3638                .insert(label, "awaiting persistence".to_owned());
3639        }
3640        self.state.save()?;
3641        self.persist_candidates().await?;
3642
3643        let mut recorded_rejection = false;
3644        for (label, reason) in rejected_noops {
3645            if self.state.interrupted_implementations.contains(&label) {
3646                continue;
3647            }
3648            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3649                && c.empty
3650            {
3651                c.verified_noop = None;
3652                c.failed
3653                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3654                self.state.event(
3655                    "implement",
3656                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3657                );
3658                recorded_rejection = true;
3659            }
3660        }
3661        if recorded_rejection {
3662            self.state.save()?;
3663        }
3664
3665        if resource_blocked {
3666            return self.stop_for_resource();
3667        }
3668        if selected_failed {
3669            self.state.status = RunStatus::Blocked;
3670            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3671            self.state.save()?;
3672            bail!(
3673                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3674            );
3675        }
3676        self.after_implement()
3677    }
3678
3679    /// Retry only persistence after a completed implementation turn.
3680    async fn persist_candidates(&mut self) -> Result<()> {
3681        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3682        for label in labels {
3683            let i = self
3684                .state
3685                .candidates
3686                .iter()
3687                .position(|c| c.label == label)
3688                .context("pending candidate is missing")?;
3689            let c = self.state.candidates[i].clone();
3690            let interrupted = self.state.interrupted_implementations.contains(&label);
3691            let result = async {
3692                let wait = crate::repo_lock::WaitPolicy::new(
3693                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3694                    || false,
3695                );
3696                let _coordination =
3697                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3698                // Best effort evidence requires no index writes. A successful snapshot
3699                // never authorizes removal of a tree whose rescue failed.
3700                if let Err(e) = git::snapshot_uncommitted(
3701                    &c.worktree,
3702                    &self
3703                        .state
3704                        .dir()
3705                        .join("artifacts")
3706                        .join(format!("candidate-{label}-recovery")),
3707                )
3708                .await
3709                {
3710                    self.state.event(
3711                        "preserve",
3712                        format!("candidate {label} snapshot incomplete: {e:#}"),
3713                    );
3714                }
3715                let rescued = git::rescue_commit(
3716                    &c.worktree,
3717                    &format!("magi: candidate {label} (uncommitted work)"),
3718                )
3719                .await?;
3720                self.state.note_withheld("implement", &rescued.withheld);
3721                let base = &self.state.base_commit;
3722                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3723                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3724                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3725                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3726                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3727                if c.empty && commits > 0 && !patch.trim().is_empty()
3728                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3729                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3730                        || self.state.tally.is_some())
3731                {
3732                    // Keep the old classification and pending marker so every
3733                    // retry stops too. Retain decisions as recovery evidence;
3734                    // only a supported recovery operation may replace them.
3735                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3736                }
3737                let c = &mut self.state.candidates[i];
3738                c.commits = commits;
3739                c.stat = stat;
3740                c.files = files;
3741                let no_changes = commits == 0 || patch.trim().is_empty();
3742                c.empty = no_changes && !interrupted;
3743                if interrupted && no_changes {
3744                    c.failed = None;
3745                    c.verified_noop = None;
3746                }
3747                if !c.empty {
3748                    c.failed = None;
3749                    c.verified_noop = None;
3750                }
3751                self.state.event(
3752                    "preserve",
3753                    format!("candidate {label}: {files} files, {commits} commits"),
3754                );
3755                Ok::<_, anyhow::Error>(())
3756            }
3757            .await;
3758            match result {
3759                Ok(()) => {
3760                    self.state.candidate_preservation.remove(&label);
3761                    if !interrupted || self.state.candidates[i].files > 0 {
3762                        self.state.interrupted_implementations.remove(&label);
3763                    }
3764                }
3765                Err(e) => {
3766                    let reason = format!("candidate {label} preservation failed: {e:#}");
3767                    self.state.event("preserve", &reason);
3768                    self.state.candidate_preservation.insert(label, reason);
3769                }
3770            }
3771            if self.state.candidate_preservation.is_empty()
3772                && self.state.status == RunStatus::Blocked
3773                && self.state.candidates.iter().all(|c| c.failed.is_none())
3774            {
3775                // Persist the recovered phase with the cleared pending marker;
3776                // a crash between saves must not turn this into a selected-seat
3777                // failure hold on the next resume.
3778                self.state.status = RunStatus::Implementing;
3779                self.state.event(
3780                    "preserve",
3781                    "candidate persistence recovered; implementation can continue",
3782                );
3783            }
3784            self.state.save()?;
3785        }
3786        if !self.state.candidate_preservation.is_empty() {
3787            self.state.status = RunStatus::Blocked;
3788            self.state.save()?;
3789            bail!(
3790                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3791            );
3792        }
3793        Ok(())
3794    }
3795
3796    /// Ask again, once, for work a CLI did and then failed to hand over.
3797    ///
3798    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3799    /// status with an empty response and a usage report showing output tokens,
3800    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3801    /// seven minutes and 14,267 output tokens that arrived as an empty
3802    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3803    ///
3804    /// Two conditions, and both matter:
3805    ///
3806    /// - **Only when the tree is untouched.** Often the agent has already
3807    ///   written its files and only the closing message was lost; the rescue
3808    ///   commit below picks that up and there is nothing to ask for. Re-asking
3809    ///   then would pay for a second implementation of work already on disk.
3810    /// - **Once.** A CLI that drops one stream can drop the next, and this
3811    ///   node is the most expensive in the graph.
3812    ///
3813    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3814    /// dropped reply still carried its `conversation_id`, so the seat is asked
3815    /// to finish what it was doing rather than sent the whole task again. It
3816    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3817    /// node's - for the same reason a re-ranked judge does: restating finished
3818    /// work is not the work.
3819    ///
3820    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3821    /// same way until it resets, while an abandoned conversation is still
3822    /// there to be picked up.
3823    async fn resume_undelivered(
3824        &mut self,
3825        results: &mut [(usize, SeatState, AgentOutcome)],
3826        sent: &[SeatJob],
3827        prompts: &Prompts,
3828        run_id: &str,
3829    ) {
3830        for (wi, seat, out) in results.iter_mut() {
3831            let Some(dropped) = (match &*out {
3832                AgentOutcome::Dropped(o) => o.dropped.clone(),
3833                _ => None,
3834            }) else {
3835                continue;
3836            };
3837            let Some(job) = sent.get(*wi) else { continue };
3838            // Already on disk? Then only the closing message was lost.
3839            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3840                self.state.event(
3841                    "implement",
3842                    format!(
3843                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3844                         work is in the tree",
3845                        seat.key, dropped.output_tokens, dropped.why
3846                    ),
3847                );
3848                continue;
3849            }
3850            // The re-ask only makes sense as a resume: `resume_after_drop`
3851            // says nothing about the task, trusting the seat to still hold it.
3852            // Without a session to resume — sessions disabled, or this CLI's
3853            // drop shape happened not to carry a session id — that prompt
3854            // would open a brand-new conversation with no context at all,
3855            // which is worse than leaving this as the ordinary failure it
3856            // already is.
3857            if !has_context(&job.spec, seat, job.sessions) {
3858                self.state.event(
3859                    "implement",
3860                    format!(
3861                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3862                         is no session left to resume",
3863                        seat.key, dropped.output_tokens, dropped.why
3864                    ),
3865                );
3866                continue;
3867            }
3868            self.state.event(
3869                "implement",
3870                format!(
3871                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3872                     conversation",
3873                    seat.key, dropped.output_tokens, dropped.why
3874                ),
3875            );
3876            let mut retry = job.clone();
3877            retry.seat = seat.clone();
3878            retry.prompt = prompt::resume_after_drop(&dropped.why);
3879            retry.timeout = retry_budget(job.timeout, true);
3880            retry.stem = format!("{}-resume", job.stem);
3881            let cache = self.state.config.cache_dir();
3882            let ctx = WaveCtx {
3883                carry_seats: false,
3884                pauses: Some((&self.pause, &self.interrupt)),
3885                run: run_id,
3886                node: "implement",
3887                prompts,
3888                cache: cache.as_deref(),
3889                round: None,
3890            };
3891            let (resumed_seat, resumed) =
3892                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3893            *seat = resumed_seat;
3894            *out = resumed;
3895        }
3896    }
3897
3898    /// Fall an implement seat through to the next untried agent in the
3899    /// implementer roster when it lost to quota — or, since the handover was
3900    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3901    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3902    /// quota path itself being unchanged — instead of leaving the
3903    /// seat's loss final the moment one agent's account runs dry.
3904    ///
3905    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3906    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3907    /// truncates to the single slot rotation picked, so a solo task whose one
3908    /// implementer hits quota mid-run used to have nothing else to try. This
3909    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3910    /// unrotated roster — which is the only place the *other* candidates in
3911    /// the machine's roster still exist once `implementers` has been cut down
3912    /// to size.
3913    ///
3914    /// Walks forward from just past the seat's own original position in the
3915    /// roster, never wrapping back to the front: a later candidate slot (say
3916    /// `beta`, the roster's second entry) must fall through to the *next*
3917    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3918    /// almost certainly a different candidate's own agent already — and once
3919    /// the roster's tail is exhausted there is nothing left to fall through
3920    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3921    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3922    /// let this retry that id forever. The loop keeps falling through until
3923    /// an attempt lands something other than `Quota` or the roster's tail
3924    /// runs out of untried ids, at which point the seat is left exactly as
3925    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3926    /// `QuotaLoss` recorded, the candidate failed/empty.
3927    ///
3928    /// `sent` is taken mutably and updated with the fallback agent's spec:
3929    /// `resume_unconfirmed_commands`, which runs after this and also reads
3930    /// `sent`, must see whichever agent actually ended up answering the seat
3931    /// — reading the stale, original spec there would check session
3932    /// eligibility against the wrong CLI and could hand a fallback agent's
3933    /// session id to the agent that just lost the seat to quota.
3934    ///
3935    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3936    /// — `self.seat` only reuses state when the agent id is unchanged, so
3937    /// handing it a different id already gets this for free. Reusing the old
3938    /// seat would resume a different CLI's session as if it were a
3939    /// continuation of this one.
3940    ///
3941    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3942    /// a quota loss cuts an agent off mid-turn, so anything already in the
3943    /// tree is unfinished work, not a completed candidate a re-ask would pay
3944    /// for twice. A dirty tree is rescued into a commit first (the same
3945    /// neutral-identity rescue `implement`'s own outcome loop gives every
3946    /// candidate) so the next agent starts clean.
3947    ///
3948    /// The new agent gets the implementer's full prompt and full
3949    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3950    /// it has no session and no context, and is implementing the task from
3951    /// nothing, unlike a resumed drop which is only restating work already
3952    /// done.
3953    ///
3954    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3955    /// `implement` event, never into `self.state.quota` — that is what
3956    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3957    /// go unspent, and a seat that ultimately recovered on its second or
3958    /// third agent is not the stalled panel that check exists to catch. Only
3959    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3960    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3961    /// outcome loop already has — this helper never pushes to it itself.
3962    async fn resume_seat_handovers(
3963        &mut self,
3964        results: &mut [(usize, SeatState, AgentOutcome)],
3965        sent: &mut [SeatJob],
3966        prompts: &Prompts,
3967        run_id: &str,
3968    ) -> Result<()> {
3969        let instruction = seeded_instruction(&self.state);
3970        let language = self.state.config.graph.language.clone();
3971        let github_language = self.state.config.graph.github_language.clone();
3972        let brief = self
3973            .state
3974            .advice
3975            .as_ref()
3976            .and_then(|a| a.synthesis.as_deref())
3977            .map(str::to_owned);
3978        let attachments = self.state.attachments.clone();
3979        for (wi, seat, out) in results.iter_mut() {
3980            // Who holds the other candidate seats of this wave right now
3981            // (earlier handovers already written back to `sent`).
3982            let others: BTreeSet<String> = sent
3983                .iter()
3984                .enumerate()
3985                .filter(|(j, _)| j != wi)
3986                .map(|(_, j)| j.spec.id.clone())
3987                .collect();
3988            let Some(job) = sent.get_mut(*wi) else {
3989                continue;
3990            };
3991            // Where the seat's own original agent sits in the roster — the
3992            // fallback walk starts just past here, never at the front, so a
3993            // later candidate slot's quota loss does not fall back onto an
3994            // earlier slot's own agent.
3995            let start = self
3996                .roles
3997                .implementer_roster
3998                .iter()
3999                .position(|s| s.id == job.spec.id)
4000                .unwrap_or(0);
4001            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
4002            let mut fallback_attempt = 0usize;
4003            let mut prev: Option<FailClass> = None;
4004            while let Some(cur) = FailClass::of(&*out) {
4005                if !should_hand_over(prev.as_ref(), &cur) {
4006                    break;
4007                }
4008                let Some(next) =
4009                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
4010                        .cloned()
4011                else {
4012                    break;
4013                };
4014                tried.insert(next.id.clone());
4015                fallback_attempt += 1;
4016
4017                let coordination = self.coordinate(&job.cwd).await?;
4018                if let Ok(r) = git::rescue_commit(
4019                    &job.cwd,
4020                    &format!(
4021                        "magi: candidate {} (uncommitted work before {} fallback)",
4022                        seat.key,
4023                        if cur == FailClass::Quota {
4024                            "quota"
4025                        } else {
4026                            "handover"
4027                        }
4028                    ),
4029                )
4030                .await
4031                {
4032                    self.state.note_withheld("implement", &r.withheld);
4033                }
4034                drop(coordination);
4035
4036                record_handover(
4037                    &mut self.state,
4038                    "implement",
4039                    &seat.key,
4040                    &seat.agent,
4041                    &next.id,
4042                    &cur,
4043                    &fail_reason(&*out),
4044                );
4045                prev = Some(cur.clone());
4046
4047                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
4048                self.state.seats.insert(seat.key.clone(), new_seat.clone());
4049                // Kept in sync on `sent` itself, not just the local retry: a
4050                // later helper (`resume_unconfirmed_commands`) reads `sent`
4051                // after this one returns and must see whichever agent is now
4052                // occupying the seat, not the one that just quota'd out —
4053                // otherwise it would judge session/continuation eligibility
4054                // by the wrong CLI and could resend a fallback's session id
4055                // to the agent that lost it the seat in the first place.
4056                job.spec = next.clone();
4057                let mut retry = job.clone();
4058                retry.seat = new_seat;
4059                retry.prompt = prompt::implement_in(
4060                    &instruction,
4061                    &job.cwd.to_string_lossy(),
4062                    &language,
4063                    &github_language,
4064                    brief.as_deref(),
4065                    &attachments,
4066                );
4067                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4068                let cache = self.state.config.cache_dir();
4069                let ctx = WaveCtx {
4070                    carry_seats: false,
4071                    pauses: Some((&self.pause, &self.interrupt)),
4072                    run: run_id,
4073                    node: "implement",
4074                    prompts,
4075                    cache: cache.as_deref(),
4076                    round: None,
4077                };
4078                let (fallback_seat, fallback_out) = run_one(
4079                    retry,
4080                    Arc::clone(&self.sem),
4081                    &ctx,
4082                    &mut self.state,
4083                    fallback_attempt,
4084                )
4085                .await;
4086                *seat = fallback_seat;
4087                *out = fallback_out;
4088            }
4089        }
4090        Ok(())
4091    }
4092
4093    /// Ask an implement seat's own CLI to confirm what it started, once, when
4094    /// its reply reported a command whose completion status it never
4095    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4096    /// that does and does not mean.
4097    ///
4098    /// The completion contract this task asks for, extended to `implement`
4099    /// with the same signal `continue_fix_report` reads for the fixer,
4100    /// rather than a keyword search over the reply or a hard requirement on
4101    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4102    /// a candidate's CLI turn ended cleanly while a test run it had started
4103    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4104    /// named in it at all is untouched by this: `commands` is empty, so
4105    /// there is nothing to be unconfirmed.
4106    ///
4107    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4108    /// this is not about recovering edits that might already be on disk, it
4109    /// is about a result the seat itself never vouched for, which resuming
4110    /// asks for regardless of what the tree already holds. Bounded to one
4111    /// attempt for the same reason `resume_undelivered` is — this is the
4112    /// most expensive node in the graph — and a seat that still cannot
4113    /// confirm on that attempt is left as whatever its (possibly still
4114    /// unconfirmed) reply says; this does not invent a new "failed" reason
4115    /// for a candidate that otherwise produced a real, committed change.
4116    async fn resume_unconfirmed_commands(
4117        &mut self,
4118        results: &mut [(usize, SeatState, AgentOutcome)],
4119        sent: &[SeatJob],
4120        prompts: &Prompts,
4121        run_id: &str,
4122    ) {
4123        for (wi, seat, out) in results.iter_mut() {
4124            let AgentOutcome::Ok(o) = &*out else {
4125                continue;
4126            };
4127            if !has_unconfirmed_command(&o.commands) {
4128                continue;
4129            }
4130            let Some(job) = sent.get(*wi) else { continue };
4131            if !has_context(&job.spec, seat, job.sessions) {
4132                self.state.event(
4133                    "implement",
4134                    format!(
4135                        "{}: the reply named a command whose own CLI never confirmed the exit \
4136                         status of, but there is no session left to resume",
4137                        seat.key
4138                    ),
4139                );
4140                continue;
4141            }
4142            self.state.event(
4143                "implement",
4144                format!(
4145                    "{}: the reply named a command whose own CLI never confirmed the exit \
4146                     status of; resuming the conversation",
4147                    seat.key
4148                ),
4149            );
4150            let mut retry = job.clone();
4151            retry.seat = seat.clone();
4152            retry.prompt = prompt::resume_incomplete(
4153                "a command in your last reply had no confirmed exit status",
4154            );
4155            retry.timeout = retry_budget(job.timeout, true);
4156            retry.stem = format!("{}-confirm", job.stem);
4157            let cache = self.state.config.cache_dir();
4158            let ctx = WaveCtx {
4159                carry_seats: false,
4160                pauses: Some((&self.pause, &self.interrupt)),
4161                run: run_id,
4162                node: "implement",
4163                prompts,
4164                cache: cache.as_deref(),
4165                round: None,
4166            };
4167            let (resumed_seat, resumed) =
4168                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4169            *seat = resumed_seat;
4170            *out = resumed;
4171        }
4172    }
4173
4174    /// Ask an implement seat again, once per candidate and run, when its
4175    /// turn ended cleanly without starting the work.
4176    ///
4177    /// The shape behind 86f0, 3ce0 and eca7: the model's first response was a
4178    /// final answer ("Implementation incomplete. No files were changed...")
4179    /// after six to twelve seconds, with no tool call and no change. That is
4180    /// a usable exit-0 reply, so none of the other recoveries sees it — it is
4181    /// not a dropped stream, not a failure and names no unconfirmed command —
4182    /// and the candidate was recorded as an ordinary empty one.
4183    ///
4184    /// Decided on evidence, never on the reply's wording (see
4185    /// [`ended_unstarted`]), and never for a reply whose `NO CHANGE NEEDED`
4186    /// claim verifies: that one did answer the task.
4187    ///
4188    /// The seat's own conversation is resumed with [`prompt::resume_unstarted`]
4189    /// when it has one; without a session the whole prompt goes out again.
4190    /// Either way the budget is the full `timeout_implement`, not a nudge's
4191    /// quarter: nothing was done yet, so this is the job itself.
4192    ///
4193    /// Bounded by [`RunState::unstarted_retries`], saved before the agent is
4194    /// asked so a restart cannot grant a second retry. A seat that ends the
4195    /// same way again becomes an ordinary failure with [`UNSTARTED_TWICE`] as
4196    /// its reason, which `resume_seat_handovers` (run next) may hand to the
4197    /// next roster agent like any other failure.
4198    async fn retry_unstarted(
4199        &mut self,
4200        results: &mut [(usize, SeatState, AgentOutcome)],
4201        sent: &[SeatJob],
4202        baselines: &[(char, Option<String>)],
4203        prompts: &Prompts,
4204        run_id: &str,
4205    ) -> Result<()> {
4206        for (wi, seat, out) in results.iter_mut() {
4207            let (Some(job), Some((label, before))) = (sent.get(*wi), baselines.get(*wi)) else {
4208                continue;
4209            };
4210            if !self.unstarted(out, before.as_deref(), &job.cwd).await {
4211                continue;
4212            }
4213            if !self.state.unstarted_retries.insert(*label) {
4214                self.state
4215                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4216                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4217                continue;
4218            }
4219            let resumed = has_context(&job.spec, seat, job.sessions);
4220            self.state.event(
4221                "implement",
4222                format!(
4223                    "{}: the turn ended without starting the work (no tool call, worktree \
4224                     unchanged); {}",
4225                    seat.key,
4226                    if resumed {
4227                        "resuming the conversation once"
4228                    } else {
4229                        "sending the task once more"
4230                    }
4231                ),
4232            );
4233            self.state.save()?;
4234            let mut retry = job.clone();
4235            retry.seat = seat.clone();
4236            if resumed {
4237                retry.prompt = prompt::resume_unstarted();
4238            }
4239            retry.stem = format!("{}-unstarted", job.stem);
4240            let cache = self.state.config.cache_dir();
4241            let ctx = WaveCtx {
4242                carry_seats: false,
4243                pauses: Some((&self.pause, &self.interrupt)),
4244                run: run_id,
4245                node: "implement",
4246                prompts,
4247                cache: cache.as_deref(),
4248                round: None,
4249            };
4250            let (answered_seat, answer) =
4251                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4252            *seat = answered_seat;
4253            *out = answer;
4254            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
4255                // No agent was spawned, so the retry was not spent.
4256                self.state.unstarted_retries.remove(label);
4257                continue;
4258            }
4259            if self.unstarted(out, before.as_deref(), &job.cwd).await {
4260                self.state
4261                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4262                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4263            }
4264        }
4265        Ok(())
4266    }
4267
4268    /// Whether `out` is a clean reply from a seat that never started the
4269    /// work in `cwd`, and whose reply does not verify as a no-op either.
4270    async fn unstarted(&self, out: &AgentOutcome, before: Option<&str>, cwd: &Path) -> bool {
4271        let AgentOutcome::Ok(o) = out else {
4272            return false;
4273        };
4274        // The CLI's own record first: most replies stop here without git.
4275        if o.tool_calls != Some(0) {
4276            return false;
4277        }
4278        let after = git::rev_parse(cwd, "HEAD").await.ok();
4279        let clean = git::is_clean(cwd).await.ok();
4280        if !ended_unstarted(o, before, after.as_deref(), clean) {
4281            return false;
4282        }
4283        let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
4284        verified_noop_claim_in_worktree(true, &o.commands, &text, cwd, &self.state.base_commit)
4285            .await
4286            != NoopClaimVerdict::Accepted
4287    }
4288
4289    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4290    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4291    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4292    /// that motivated this.
4293    ///
4294    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4295    /// own nudge loop already covers for judge/review/vote seats, and not a
4296    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4297    /// implement seats: here the CLI turn genuinely finished while the node's
4298    /// own work — the fixer's account of what it did — had not. Gated purely
4299    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4300    /// reply, never on any wording in it, so a fixer whose valid, first-try
4301    /// `FixReport` happens to mention having waited on a background test is
4302    /// never resumed — the `Ok(report)` branch at the call site returns
4303    /// before this is ever invoked.
4304    ///
4305    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4306    /// attempt ([`retry_budget`]), nothing attempted once the session is
4307    /// gone, and a quota hit ends the loop immediately rather than retrying a
4308    /// rate limit that fails the same way again.
4309    async fn continue_fix_report(
4310        &mut self,
4311        mut seat: SeatState,
4312        parse_err: String,
4313        job: &SeatJob,
4314        prompts: &Prompts,
4315        run_id: &str,
4316        round: usize,
4317    ) -> (
4318        SeatState,
4319        Option<FixReport>,
4320        Option<String>,
4321        ContinuationRecord,
4322    ) {
4323        let mut last_err = parse_err;
4324        let mut cumulative_wait_ms = 0u64;
4325        let mut attempts = 0usize;
4326        loop {
4327            if !has_context(&job.spec, &seat, job.sessions) {
4328                self.state.event(
4329                    "fix",
4330                    format!(
4331                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4332                         session left to resume into"
4333                    ),
4334                );
4335                let outcome = if attempts == 0 {
4336                    ContinuationOutcome::NoSession
4337                } else {
4338                    ContinuationOutcome::Exhausted
4339                };
4340                return (
4341                    seat,
4342                    None,
4343                    Some(format!("unparsable fix report: {last_err}")),
4344                    ContinuationRecord {
4345                        attempts,
4346                        cumulative_wait_ms,
4347                        outcome,
4348                    },
4349                );
4350            }
4351            if attempts >= MAX_FIX_CONTINUATIONS {
4352                self.state.event(
4353                    "fix",
4354                    format!(
4355                        "round {round}: fixer's reply still had no adoption report after \
4356                         {attempts} continuation(s) ({last_err}); giving up"
4357                    ),
4358                );
4359                return (
4360                    seat,
4361                    None,
4362                    Some(format!(
4363                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4364                    )),
4365                    ContinuationRecord {
4366                        attempts,
4367                        cumulative_wait_ms,
4368                        outcome: ContinuationOutcome::Exhausted,
4369                    },
4370                );
4371            }
4372            attempts += 1;
4373            self.state.event(
4374                "fix",
4375                format!(
4376                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4377                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4378                ),
4379            );
4380            let mut retry = job.clone();
4381            retry.seat = seat.clone();
4382            retry.prompt = prompt::resume_incomplete(&last_err);
4383            retry.timeout = retry_budget(job.timeout, true);
4384            retry.stem = format!("{}-continue{attempts}", job.stem);
4385            let cache = self.state.config.cache_dir();
4386            let ctx = WaveCtx {
4387                carry_seats: false,
4388                pauses: Some((&self.pause, &self.interrupt)),
4389                run: run_id,
4390                node: "fix",
4391                prompts,
4392                cache: cache.as_deref(),
4393                round: Some(round),
4394            };
4395            let (resumed_seat, resumed_out) = run_one(
4396                retry,
4397                Arc::clone(&self.sem),
4398                &ctx,
4399                &mut self.state,
4400                attempts,
4401            )
4402            .await;
4403            seat = resumed_seat;
4404            match resumed_out {
4405                AgentOutcome::Ok(o) => {
4406                    cumulative_wait_ms += o.duration_ms;
4407                    match verdict::extract_json::<FixReport>(&o.text) {
4408                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4409                            self.state.event(
4410                                "fix",
4411                                format!(
4412                                    "round {round}: fixer's adoption report recovered after \
4413                                     {attempts} continuation(s)"
4414                                ),
4415                            );
4416                            return (
4417                                seat,
4418                                Some(report),
4419                                None,
4420                                ContinuationRecord {
4421                                    attempts,
4422                                    cumulative_wait_ms,
4423                                    outcome: ContinuationOutcome::Resumed,
4424                                },
4425                            );
4426                        }
4427                        // The report parsed, but this same reply's own
4428                        // CommandEvidence — the identical record `state.jobs`
4429                        // renders — names a command whose CLI never
4430                        // confirmed an exit status. Read together, that is
4431                        // not a resolved answer: keep nudging rather than
4432                        // accept a report standing next to a command the
4433                        // seat's own CLI cannot vouch for.
4434                        Ok(_) => {
4435                            last_err = "the reply parsed, but it reported a command whose own CLI \
4436                                 never confirmed an exit status"
4437                                .to_owned();
4438                        }
4439                        Err(e) => last_err = e.to_string(),
4440                    }
4441                }
4442                AgentOutcome::Quota(o) => {
4443                    cumulative_wait_ms += o.duration_ms;
4444                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4445                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4446                    self.state.quota.push(loss);
4447                    self.state.event(
4448                        "fix",
4449                        format!(
4450                            "round {round}: continuation rate limited (quota); not retrying now"
4451                        ),
4452                    );
4453                    return (
4454                        seat,
4455                        None,
4456                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4457                        ContinuationRecord {
4458                            attempts,
4459                            cumulative_wait_ms,
4460                            outcome: ContinuationOutcome::QuotaLost,
4461                        },
4462                    );
4463                }
4464                AgentOutcome::Dropped(o) => {
4465                    cumulative_wait_ms += o.duration_ms;
4466                    let why = o
4467                        .dropped
4468                        .as_ref()
4469                        .map(|d| d.why.as_str())
4470                        .unwrap_or("the CLI ended the stream without delivering its answer");
4471                    last_err = format!("the CLI dropped the stream ({why})");
4472                }
4473                AgentOutcome::Failed(e) => last_err = e,
4474                // The continuation was never started; the report stays lost
4475                // and the caller records that, without any handover.
4476                AgentOutcome::ResourceBlocked(e) => {
4477                    return (
4478                        seat,
4479                        None,
4480                        Some(format!("the continuation was not started: {e}")),
4481                        ContinuationRecord {
4482                            attempts: attempts.saturating_sub(1),
4483                            cumulative_wait_ms,
4484                            outcome: ContinuationOutcome::NoSession,
4485                        },
4486                    );
4487                }
4488            }
4489        }
4490    }
4491
4492    fn after_implement(&mut self) -> Result<()> {
4493        if !self.state.candidate_preservation.is_empty() {
4494            bail!("candidate preservation incomplete; judging is unsafe");
4495        }
4496        // Scan every candidate patch once the set is complete.
4497        if self.state.leaks.is_empty() {
4498            let cfg = self.state.config.blind.clone();
4499            let mut leaks = Vec::new();
4500            for c in &self.state.candidates {
4501                let Some(patch) =
4502                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4503                else {
4504                    continue;
4505                };
4506                leaks.extend(blind::scan(
4507                    &format!("candidate {} patch", c.label),
4508                    &patch,
4509                    &cfg.vendor_tokens,
4510                ));
4511            }
4512            if !leaks.is_empty() {
4513                let summary = leaks
4514                    .iter()
4515                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4516                    .collect::<Vec<_>>()
4517                    .join(", ");
4518                match cfg.on_leak {
4519                    LeakPolicy::Fail => {
4520                        self.state.status = RunStatus::Failed;
4521                        self.state
4522                            .event("blind", format!("vendor text in a patch: {summary}"));
4523                        self.state.leaks = leaks;
4524                        self.state.save()?;
4525                        self.settle_questions();
4526                        bail!(
4527                            "blind.on_leak = \"fail\" and vendor text reached a \
4528                             judged patch: {summary}"
4529                        );
4530                    }
4531                    LeakPolicy::Redact => self.state.event(
4532                        "blind",
4533                        format!("redacting vendor text for judging: {summary}"),
4534                    ),
4535                    LeakPolicy::Warn => self.state.event(
4536                        "blind",
4537                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4538                    ),
4539                }
4540                self.state.leaks = leaks;
4541            }
4542        }
4543
4544        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4545        // incomplete or inconsistent saved state cannot bypass the strict contract.
4546        let mut invalidated = Vec::new();
4547        for c in &mut self.state.candidates {
4548            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4549                c.verified_noop = None;
4550                if c.empty && c.failed.is_none() {
4551                    c.failed = Some(
4552                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4553                            .to_owned(),
4554                    );
4555                }
4556                invalidated.push(c.label);
4557            }
4558        }
4559        for label in invalidated {
4560            self.state.event(
4561                "implement",
4562                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4563            );
4564        }
4565
4566        if self.state.viable().is_empty() {
4567            if self.state.all_candidates_verified_noop() {
4568                // Every candidate agreed, with evidence the adoption guard
4569                // accepted, that nothing belongs in this worktree. That is
4570                // not the same fact as a candidate that simply failed to
4571                // write anything, and settling it as an ordinary `Failed`
4572                // (see `SCHEMA`'s doc for schema 10) is what let two of
4573                // task 391f's attempts burn a retry each re-discovering the
4574                // same already-landed fix. Terminal either way, so `judge`
4575                // must never run over an empty candidate set — unlike the
4576                // `Failed` branch below this returns `Ok`, not an error:
4577                // nothing here failed.
4578                self.state.status = RunStatus::VerifiedNoop;
4579                self.state.save()?;
4580                self.settle_questions();
4581                return Ok(());
4582            }
4583            self.state.status = RunStatus::Failed;
4584            self.state.save()?;
4585            self.settle_questions();
4586            bail!("no candidate produced a change; nothing to judge");
4587        }
4588        self.state.status = RunStatus::Judging;
4589        self.state.save()?;
4590        Ok(())
4591    }
4592
4593    // --------------------------------------------------------------- judge
4594
4595    async fn judge(&mut self) -> Result<()> {
4596        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4597        // agent files with `magi task add` name the run that paid for it. The
4598        // prompt overlay is cloned alongside it because the waves borrow it
4599        // while `self` is mutably borrowed by the node's own bookkeeping.
4600        let run_id = self.state.id.clone();
4601        let prompts = self.state.config.prompts.clone();
4602        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4603            return Ok(());
4604        }
4605        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4606        if viable.len() == 1 {
4607            // Recorded so this is a one-time event: `judgements` stays empty
4608            // either way, which without this flag is indistinguishable from
4609            // "not yet judged" on the next reentry — and status is left
4610            // untouched, so a later node's conclusion (e.g. `Blocked` after
4611            // the review budget ran out) survives a resume instead of being
4612            // clobbered back to `Judging` by this node running again.
4613            self.state.judge_skipped = true;
4614            self.state.event(
4615                "judge",
4616                format!(
4617                    "only candidate {} produced a change; judging skipped",
4618                    viable[0].label
4619                ),
4620            );
4621            self.state.save()?;
4622            return Ok(());
4623        }
4624        self.state.status = RunStatus::Judging;
4625
4626        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4627        let language = self.state.config.graph.language.clone();
4628        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4629        let sessions = self.state.config.graph.sessions;
4630        let artifacts = agent::artifacts_dir(&self.state.dir());
4631        let root = self.state.worktree_root();
4632        let base_short = short(&self.state.base_commit);
4633
4634        let mut jobs = Vec::new();
4635        let mut orders = Vec::new();
4636        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4637            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4638            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4639            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4640            let seat_key = format!("judge-{}", j + 1);
4641            let seat = self.seat(&seat_key, &spec.id);
4642            jobs.push(SeatJob {
4643                prompt: prompt::judge(
4644                    &self.state.instruction,
4645                    &views,
4646                    self.roles.judges.len(),
4647                    &base_short,
4648                    &language,
4649                ),
4650                spec,
4651                seat,
4652                cwd: root.join(format!("judge-{}", j + 1)),
4653                timeout,
4654                allow_write: false,
4655                sessions,
4656                artifacts: artifacts.clone(),
4657                stem: format!("judge-{}", j + 1),
4658                handover: None,
4659            });
4660        }
4661
4662        self.state.event(
4663            "judge",
4664            format!(
4665                "{} judges ranking {} candidates blind",
4666                jobs.len(),
4667                viable.len()
4668            ),
4669        );
4670        let labels_for_check = labels.clone();
4671        let mut quota_losses = Vec::new();
4672        let cache = self.state.config.cache_dir();
4673        let ctx = WaveCtx {
4674            carry_seats: false,
4675            pauses: Some((&self.pause, &self.interrupt)),
4676            run: &run_id,
4677            node: "judge",
4678            prompts: &prompts,
4679            cache: cache.as_deref(),
4680            round: None,
4681        };
4682        let results = ask_json_wave::<Ranking>(
4683            jobs,
4684            Arc::clone(&self.sem),
4685            self.state.config.graph.retries,
4686            &self.roles.judge_roster,
4687            &ctx,
4688            &mut quota_losses,
4689            &mut self.state,
4690            &move |r: &Ranking| r.validate(&labels_for_check),
4691        )
4692        .await;
4693        if self.state.resource_block.is_some() {
4694            return self.stop_for_resource();
4695        }
4696        self.state.quota.extend(quota_losses);
4697
4698        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4699            let agent_id = seat.agent.clone();
4700            self.state.seats.insert(seat.key.clone(), seat);
4701            let mut record = Judgement {
4702                judge: j + 1,
4703                seat: format!("judge-{}", j + 1),
4704                agent: agent_id,
4705                ranking: Vec::new(),
4706                reasons: BTreeMap::new(),
4707                confidence: None,
4708                strengths: BTreeMap::new(),
4709                order: orders[j].clone(),
4710                failed: None,
4711                duration_ms: 0,
4712            };
4713            match res {
4714                Ok((ranking, out)) => {
4715                    record.ranking = ranking.normalized();
4716                    record.reasons = ranking.reasons;
4717                    record.strengths = ranking.strengths;
4718                    record.confidence = ranking.confidence;
4719                    record.duration_ms = out.duration_ms;
4720                    self.state.event(
4721                        "judge",
4722                        format!(
4723                            "judge {} ranked {}",
4724                            j + 1,
4725                            record.ranking.iter().collect::<String>()
4726                        ),
4727                    );
4728                }
4729                Err(e) => {
4730                    record.failed = Some(e.to_string());
4731                    self.state
4732                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4733                }
4734            }
4735            self.state.judgements.push(record);
4736            self.state.save()?;
4737        }
4738        Ok(())
4739    }
4740
4741    // ---------------------------------------------------------- deliberate
4742
4743    async fn deliberate(&mut self) -> Result<()> {
4744        if self.hold_base_sync().await? {
4745            return Ok(());
4746        }
4747        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4748        // agent files with `magi task add` name the run that paid for it. The
4749        // prompt overlay is cloned alongside it because the waves borrow it
4750        // while `self` is mutably borrowed by the node's own bookkeeping.
4751        let run_id = self.state.id.clone();
4752        let prompts = self.state.config.prompts.clone();
4753        let rounds = self.state.config.graph.deliberate_rounds;
4754        // Resume unfinished rounds after an outage, but never reopen a tally.
4755        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4756            return Ok(());
4757        }
4758        let tops: Vec<char> = self
4759            .state
4760            .judgements
4761            .iter()
4762            .filter_map(|j| j.ranking.first().copied())
4763            .collect();
4764        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4765            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4766                self.state.event(
4767                    "deliberate",
4768                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4769                );
4770            }
4771            self.state.status = RunStatus::Voting;
4772            self.state.save()?;
4773            return Ok(());
4774        }
4775
4776        self.state.status = RunStatus::Deliberating;
4777        self.state.event(
4778            "deliberate",
4779            format!(
4780                "split: first choices were {} — opening {rounds} round(s)",
4781                tops.iter().collect::<String>()
4782            ),
4783        );
4784
4785        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4786        let language = self.state.config.graph.language.clone();
4787        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4788        let sessions = self.state.config.graph.sessions;
4789        let artifacts = agent::artifacts_dir(&self.state.dir());
4790        let root = self.state.worktree_root();
4791        let base_short = short(&self.state.base_commit);
4792
4793        // Judges argue in sequence so that a turn can answer the one before it;
4794        // that is the difference between deliberation and three parallel
4795        // monologues.
4796        for round in self.state.deliberation.len() + 1..=rounds {
4797            let mut turns: Vec<DeliberationTurn> = Vec::new();
4798            let mut round_losses = Vec::new();
4799            let mut asked = 0;
4800            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4801                if self.state.judgements[j].failed.is_some() {
4802                    continue;
4803                }
4804                let seat_key = format!("judge-{}", j + 1);
4805                let spec = self.occupant(&seat_key, spec);
4806                let mut seat = self.seat(&seat_key, &spec.id);
4807                let transcript = self.transcript(&turns, j);
4808                let build = |context: Option<&str>| {
4809                    prompt::deliberate(
4810                        &self.state.instruction,
4811                        context,
4812                        &transcript,
4813                        round,
4814                        rounds,
4815                        &language,
4816                    )
4817                };
4818                let block = self.candidate_block(&viable, &base_short);
4819                let full = build(Some(&block));
4820                let text = if has_context(&spec, &seat, sessions) {
4821                    build(None)
4822                } else {
4823                    full.clone()
4824                };
4825                let job = SeatJob {
4826                    spec,
4827                    seat: seat.clone(),
4828                    prompt: text,
4829                    cwd: root.join(format!("judge-{}", j + 1)),
4830                    timeout,
4831                    allow_write: false,
4832                    sessions,
4833                    artifacts: artifacts.clone(),
4834                    stem: format!("delib-{round}-judge-{}", j + 1),
4835                    handover: Some(full),
4836                };
4837                let cache = self.state.config.cache_dir();
4838                let ctx = WaveCtx {
4839                    carry_seats: false,
4840                    pauses: Some((&self.pause, &self.interrupt)),
4841                    run: &run_id,
4842                    node: "deliberate",
4843                    prompts: &prompts,
4844                    cache: cache.as_deref(),
4845                    round: None,
4846                };
4847                // A turn is never nudged (`retries` 0): a failed seat is
4848                // handed to the next roster agent, which gets the full
4849                // context. An empty answer is a turn, not a failure.
4850                let mut losses = Vec::new();
4851                asked += 1;
4852                let mut results = ask_wave_with::<String>(
4853                    vec![job],
4854                    Arc::clone(&self.sem),
4855                    0,
4856                    &self.roles.judge_roster,
4857                    &ctx,
4858                    &mut losses,
4859                    &mut self.state,
4860                    &|text: &str| {
4861                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4862                    },
4863                )
4864                .await;
4865                if self.state.resource_block.is_some() {
4866                    return self.stop_for_resource();
4867                }
4868                round_losses.extend(losses.iter().cloned());
4869                self.state.quota.extend(losses);
4870                let (updated, res, _) = results.pop().expect("one job in, one result out");
4871                seat = updated;
4872                let agent_id = seat.agent.clone();
4873                self.state.seats.insert(seat.key.clone(), seat);
4874                let body = match res {
4875                    Ok((body, _)) => body,
4876                    // Skip the seat; a CLI's raw error JSON is never read as
4877                    // this judge's position.
4878                    Err(e) => {
4879                        self.state
4880                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4881                        continue;
4882                    }
4883                };
4884                let tentative = verdict::extract_json::<Position>(&body)
4885                    .ok()
4886                    .and_then(|p| p.tentative)
4887                    .and_then(|s| s.trim().chars().next())
4888                    .map(|c| c.to_ascii_uppercase());
4889                self.state.event(
4890                    "deliberate",
4891                    format!(
4892                        "round {round}: judge {} now favours {}",
4893                        j + 1,
4894                        tentative.map_or("—".to_owned(), |c| c.to_string())
4895                    ),
4896                );
4897                turns.push(DeliberationTurn {
4898                    judge: j + 1,
4899                    agent: agent_id,
4900                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4901                    tentative,
4902                });
4903            }
4904            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4905                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4906                return self.stop_for_resource();
4907            }
4908            self.state
4909                .deliberation
4910                .push(DeliberationRound { round, turns });
4911            self.state.save()?;
4912        }
4913
4914        self.state.status = RunStatus::Voting;
4915        self.state.save()?;
4916        Ok(())
4917    }
4918
4919    // ---------------------------------------------------------------- vote
4920
4921    async fn vote(&mut self) -> Result<()> {
4922        if self.hold_base_sync().await? {
4923            return Ok(());
4924        }
4925        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4926        // agent files with `magi task add` name the run that paid for it. The
4927        // prompt overlay is cloned alongside it because the waves borrow it
4928        // while `self` is mutably borrowed by the node's own bookkeeping.
4929        let run_id = self.state.id.clone();
4930        let prompts = self.state.config.prompts.clone();
4931        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4932            return Ok(());
4933        }
4934        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4935        if viable.len() == 1 {
4936            return Ok(());
4937        }
4938        self.state.status = RunStatus::Voting;
4939
4940        let language = self.state.config.graph.language.clone();
4941        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4942        let sessions = self.state.config.graph.sessions;
4943        let artifacts = agent::artifacts_dir(&self.state.dir());
4944        let root = self.state.worktree_root();
4945        let base_short = short(&self.state.base_commit);
4946        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4947
4948        let mut jobs = Vec::new();
4949        let mut seats_at = Vec::new();
4950        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4951            if self
4952                .state
4953                .judgements
4954                .get(j)
4955                .is_some_and(|r| r.failed.is_some())
4956            {
4957                continue;
4958            }
4959            let seat_key = format!("judge-{}", j + 1);
4960            let spec = self.occupant(&seat_key, spec);
4961            let seat = self.seat(&seat_key, &spec.id);
4962            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4963            let text = if has_context(&spec, &seat, sessions) {
4964                prompt::final_vote(&viable, &language)
4965            } else {
4966                full.clone()
4967            };
4968            jobs.push(SeatJob {
4969                spec,
4970                seat,
4971                prompt: text,
4972                cwd: root.join(format!("judge-{}", j + 1)),
4973                timeout,
4974                allow_write: false,
4975                sessions,
4976                artifacts: artifacts.clone(),
4977                stem: format!("vote-judge-{}", j + 1),
4978                handover: Some(full),
4979            });
4980            seats_at.push(j);
4981        }
4982
4983        self.state.event(
4984            "vote",
4985            format!(
4986                "collecting {} final votes one by one, privately",
4987                jobs.len()
4988            ),
4989        );
4990        let allowed = viable.clone();
4991        let mut quota_losses = Vec::new();
4992        let cache = self.state.config.cache_dir();
4993        let ctx = WaveCtx {
4994            carry_seats: false,
4995            pauses: Some((&self.pause, &self.interrupt)),
4996            run: &run_id,
4997            node: "vote",
4998            prompts: &prompts,
4999            cache: cache.as_deref(),
5000            round: None,
5001        };
5002        let results = ask_json_wave::<FinalVote>(
5003            jobs,
5004            Arc::clone(&self.sem),
5005            self.state.config.graph.retries,
5006            &self.roles.judge_roster,
5007            &ctx,
5008            &mut quota_losses,
5009            &mut self.state,
5010            &move |v: &FinalVote| match v.label() {
5011                Some(c) if allowed.contains(&c) => Ok(()),
5012                other => bail!("vote {other:?} is not one of {allowed:?}"),
5013            },
5014        )
5015        .await;
5016        if self.state.resource_block.is_some() {
5017            return self.stop_for_resource();
5018        }
5019        self.state.quota.extend(quota_losses);
5020
5021        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
5022            let agent_id = seat.agent.clone();
5023            self.state.seats.insert(seat.key.clone(), seat);
5024            let initial = self
5025                .state
5026                .judgements
5027                .get(j)
5028                .and_then(|r| r.ranking.first().copied());
5029            let mut record = VoteRecord {
5030                judge: j + 1,
5031                agent: agent_id,
5032                vote: None,
5033                reason: String::new(),
5034                changed: false,
5035            };
5036            match res {
5037                Ok((v, _)) => {
5038                    record.vote = v.label();
5039                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5040                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
5041                    self.state.event(
5042                        "vote",
5043                        format!(
5044                            "judge {} voted {}{}",
5045                            j + 1,
5046                            record.vote.unwrap_or('?'),
5047                            if record.changed { " (changed)" } else { "" }
5048                        ),
5049                    );
5050                }
5051                Err(e) => {
5052                    self.state
5053                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
5054                }
5055            }
5056            self.state.votes.push(record);
5057            self.state.save()?;
5058        }
5059        Ok(())
5060    }
5061
5062    // --------------------------------------------------------------- tally
5063
5064    fn tally(&mut self) -> Result<()> {
5065        if self.state.tally.is_some() {
5066            return Ok(());
5067        }
5068        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
5069        let tops: Vec<char> = self
5070            .state
5071            .judgements
5072            .iter()
5073            .filter_map(|j| j.ranking.first().copied())
5074            .collect();
5075        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
5076
5077        // A judge whose private vote failed still counted once, in the initial
5078        // ranking; using it beats discarding a whole seat.
5079        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5080        let mut cast: Vec<char> = Vec::new();
5081        for (i, j) in self.state.judgements.iter().enumerate() {
5082            let vote = self
5083                .state
5084                .votes
5085                .iter()
5086                .find(|v| v.judge == i + 1)
5087                .and_then(|v| v.vote)
5088                .or_else(|| j.ranking.first().copied());
5089            if let Some(v) = vote {
5090                *first_choice.entry(v).or_insert(0) += 1;
5091                cast.push(v);
5092            }
5093        }
5094
5095        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5096        for j in &self.state.judgements {
5097            let n = j.ranking.len();
5098            for (pos, label) in j.ranking.iter().enumerate() {
5099                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
5100            }
5101        }
5102
5103        let best = first_choice.values().copied().max().unwrap_or(0);
5104        let mut leaders: Vec<char> = first_choice
5105            .iter()
5106            .filter(|(_, v)| **v == best)
5107            .map(|(k, _)| *k)
5108            .collect();
5109        let mut tie_break = None;
5110        if leaders.len() > 1 {
5111            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
5112            let borda_leaders: Vec<char> = leaders
5113                .iter()
5114                .copied()
5115                .filter(|l| borda[l] == top_borda)
5116                .collect();
5117            tie_break = Some(if borda_leaders.len() == 1 {
5118                format!(
5119                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
5120                    leaders.len()
5121                )
5122            } else {
5123                format!(
5124                    "{} way tie on both first-choice votes and Borda points, broken by label order",
5125                    leaders.len()
5126                )
5127            });
5128            leaders = borda_leaders;
5129            leaders.sort_unstable();
5130        }
5131        let winner = *leaders
5132            .first()
5133            .or(viable.first())
5134            .context("no candidate to declare a winner from")?;
5135
5136        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
5137        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
5138        let deliberated = !self.state.deliberation.is_empty();
5139
5140        // Whose verdict is this? A rate-limited seat is absent even if it
5141        // ranked before the limit hit, so presence is measured against the
5142        // recorded losses, not just "did a ranking ever appear".
5143        let quota_seats: std::collections::BTreeSet<&str> =
5144            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5145        let mut present = 0usize;
5146        for (i, j) in self.state.judgements.iter().enumerate() {
5147            if quota_seats.contains(j.seat.as_str()) {
5148                continue;
5149            }
5150            let ranked = !j.ranking.is_empty() && j.failed.is_none();
5151            let voted = self
5152                .state
5153                .votes
5154                .iter()
5155                .any(|v| v.judge == i + 1 && v.vote.is_some());
5156            if ranked || voted {
5157                present += 1;
5158            }
5159        }
5160        // Strict majority of the configured panel. A bare majority is real
5161        // signal we can act on, while a minority verdict must never stand in
5162        // for a healthy one. A one-candidate run needs no panel at all, and
5163        // `judges` stays `0` rather than the roster size a panel that never
5164        // sat would otherwise be credited with.
5165        let needs_quorum = viable.len() > 1;
5166        let judges_total = if needs_quorum {
5167            self.roles.judges.len()
5168        } else {
5169            0
5170        };
5171        let quorum = if needs_quorum {
5172            judges_total / 2 + 1
5173        } else {
5174            0
5175        };
5176        let met_quorum = !needs_quorum || present >= quorum;
5177        let uncontested = (!needs_quorum).then(|| {
5178            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5179        });
5180
5181        self.state.event(
5182            "tally",
5183            match &uncontested {
5184                Some(reason) => format!("winner {winner} — {reason}"),
5185                None => format!(
5186                    "winner {winner} — votes {} | initial {} | {} changed | \
5187                     {present}/{judges_total} judges{}",
5188                    first_choice
5189                        .iter()
5190                        .map(|(k, v)| format!("{k}:{v}"))
5191                        .collect::<Vec<_>>()
5192                        .join(" "),
5193                    if unanimous_initial {
5194                        "unanimous"
5195                    } else {
5196                        "split"
5197                    },
5198                    changed_votes,
5199                    if met_quorum {
5200                        String::new()
5201                    } else {
5202                        format!(" — below quorum ({quorum} required)")
5203                    },
5204                ),
5205            },
5206        );
5207        if !met_quorum {
5208            self.state.event(
5209                "stall",
5210                format!(
5211                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5212                     the run stops here, resumable"
5213                ),
5214            );
5215        }
5216        self.state.tally = Some(Tally {
5217            first_choice,
5218            borda,
5219            winner,
5220            rankings: tops.len(),
5221            unanimous_initial,
5222            deliberated,
5223            changed_votes,
5224            unanimous_final,
5225            tie_break,
5226            judges: judges_total,
5227            present,
5228            quorum,
5229            met_quorum,
5230            uncontested,
5231        });
5232        self.state.status = if met_quorum {
5233            RunStatus::Reviewing
5234        } else {
5235            RunStatus::Stalled
5236        };
5237        self.state.save()?;
5238        Ok(())
5239    }
5240
5241    // ------------------------------------------------------------- recover
5242
5243    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5244    /// resumed toward completion once the transient cause clears.
5245    ///
5246    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5247    /// it toward the quorum, which is exactly the set of seats whose absence
5248    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5249    /// not depend on which node happened to hit the limit), or an ordinary
5250    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5251    /// seat is never disturbed.
5252    ///
5253    /// A seat that now answers with a usable ranking is "recovered": its
5254    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5255    /// `tally` counts it present again), and its vote re-collected. A seat that
5256    /// still fails keeps its loss and stays absent.
5257    ///
5258    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5259    /// to review/gate/merge), `false` when it is still below quorum (the run
5260    /// stays `Stalled`, still resumable for a later retry).
5261    #[allow(clippy::too_many_lines)]
5262    async fn recover_stall(&mut self) -> Result<bool> {
5263        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5264        // agent files with `magi task add` name the run that paid for it. The
5265        // prompt overlay is cloned alongside it because the waves borrow it
5266        // while `self` is mutably borrowed by the node's own bookkeeping.
5267        let run_id = self.state.id.clone();
5268        let prompts = self.state.config.prompts.clone();
5269        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5270        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5271        // is what keeps a non-quota collapse — or a quota loss recorded at the
5272        // deliberate node — from being a permanent dead-end on `--resume`.
5273        let quota_seats: BTreeSet<&str> =
5274            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5275        let absent: Vec<String> = self
5276            .state
5277            .judgements
5278            .iter()
5279            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5280            .map(|j| j.seat.clone())
5281            .collect();
5282        if absent.is_empty() {
5283            return Ok(false);
5284        }
5285        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5286        if viable.len() <= 1 {
5287            return Ok(false);
5288        }
5289        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5290        let language = self.state.config.graph.language.clone();
5291        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5292        let sessions = self.state.config.graph.sessions;
5293        let artifacts = agent::artifacts_dir(&self.state.dir());
5294        let root = self.state.worktree_root();
5295        let base_short = short(&self.state.base_commit);
5296        let candidates: Vec<Candidate> = viable.clone();
5297
5298        // Map each absent seat key to its 0-based position in `roles.judges`.
5299        let mut positions: Vec<usize> = absent
5300            .iter()
5301            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5302            .collect();
5303        if positions.is_empty() {
5304            return Ok(false);
5305        }
5306        positions.sort_unstable();
5307        positions.dedup();
5308
5309        // Re-rank the lost seats, one blind prompt each.
5310        let mut judge_jobs = Vec::new();
5311        for &j in &positions {
5312            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5313            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5314            let seat_key = format!("judge-{}", j + 1);
5315            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5316            let seat = self.seat(&seat_key, &spec.id);
5317            judge_jobs.push(SeatJob {
5318                spec,
5319                seat,
5320                prompt: prompt::judge(
5321                    &self.state.instruction,
5322                    &views,
5323                    self.roles.judges.len(),
5324                    &base_short,
5325                    &language,
5326                ),
5327                cwd: root.join(seat_key),
5328                timeout,
5329                allow_write: false,
5330                sessions,
5331                artifacts: artifacts.clone(),
5332                stem: format!("judge-{}-recover", j + 1),
5333                handover: None,
5334            });
5335        }
5336
5337        let labels_for_check = labels.clone();
5338        let mut judge_losses = Vec::new();
5339        let retries = self.state.config.graph.retries;
5340        let cache = self.state.config.cache_dir();
5341        let ctx = WaveCtx {
5342            carry_seats: false,
5343            pauses: Some((&self.pause, &self.interrupt)),
5344            run: &run_id,
5345            node: "judge",
5346            prompts: &prompts,
5347            cache: cache.as_deref(),
5348            round: None,
5349        };
5350        let results = ask_json_wave::<Ranking>(
5351            judge_jobs,
5352            Arc::clone(&self.sem),
5353            retries,
5354            &self.roles.judge_roster,
5355            &ctx,
5356            &mut judge_losses,
5357            &mut self.state,
5358            &move |r: &Ranking| r.validate(&labels_for_check),
5359        )
5360        .await;
5361        if self.state.resource_block.is_some() {
5362            self.stop_for_resource()?;
5363            return Ok(false);
5364        }
5365
5366        // Refresh the judgement of every seat that ranked again.
5367        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5368        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5369            let agent_id = seat.agent.clone();
5370            self.state.seats.insert(seat.key.clone(), seat);
5371            let record = &mut self.state.judgements[j];
5372            match res {
5373                Ok((ranking, out)) => {
5374                    record.agent = agent_id;
5375                    record.ranking = ranking.normalized();
5376                    record.reasons = ranking.reasons;
5377                    record.strengths = ranking.strengths;
5378                    record.confidence = ranking.confidence;
5379                    record.failed = None;
5380                    record.duration_ms = out.duration_ms;
5381                    recovered.insert(j);
5382                    self.state.event(
5383                        "recover",
5384                        format!("judge {} ranked again after the limit", j + 1),
5385                    );
5386                }
5387                Err(e) => {
5388                    self.state
5389                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5390                }
5391            }
5392        }
5393
5394        // Re-ask the votes of the seats that recovered a ranking.
5395        let mut vote_jobs = Vec::new();
5396        let mut vote_pos: Vec<usize> = Vec::new();
5397        for &j in &recovered {
5398            let seat_key = format!("judge-{}", j + 1);
5399            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5400            let seat = self.seat(&seat_key, &spec.id);
5401            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5402            let text = if has_context(&spec, &seat, sessions) {
5403                prompt::final_vote(&labels, &language)
5404            } else {
5405                full.clone()
5406            };
5407            vote_jobs.push(SeatJob {
5408                spec,
5409                seat,
5410                prompt: text,
5411                cwd: root.join(seat_key),
5412                timeout,
5413                allow_write: false,
5414                sessions,
5415                artifacts: artifacts.clone(),
5416                stem: format!("vote-judge-{}-recover", j + 1),
5417                handover: Some(full),
5418            });
5419            vote_pos.push(j);
5420        }
5421        let allowed = labels.clone();
5422        let mut vote_losses = Vec::new();
5423        let vote_retries = self.state.config.graph.retries;
5424        let vote_cache = self.state.config.cache_dir();
5425        let ctx = WaveCtx {
5426            carry_seats: false,
5427            pauses: Some((&self.pause, &self.interrupt)),
5428            run: &run_id,
5429            node: "vote",
5430            prompts: &prompts,
5431            cache: vote_cache.as_deref(),
5432            round: None,
5433        };
5434        let votes = ask_json_wave::<FinalVote>(
5435            vote_jobs,
5436            Arc::clone(&self.sem),
5437            vote_retries,
5438            &self.roles.judge_roster,
5439            &ctx,
5440            &mut vote_losses,
5441            &mut self.state,
5442            &move |v: &FinalVote| match v.label() {
5443                Some(c) if allowed.contains(&c) => Ok(()),
5444                other => bail!("vote {other:?} is not one of {allowed:?}"),
5445            },
5446        )
5447        .await;
5448        if self.state.resource_block.is_some() {
5449            self.stop_for_resource()?;
5450            return Ok(false);
5451        }
5452        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5453            let agent_id = seat.agent.clone();
5454            self.state.seats.insert(seat.key.clone(), seat);
5455            match res {
5456                Ok((v, _)) => {
5457                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5458                        rec.vote = v.label();
5459                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5460                    } else {
5461                        self.state.votes.push(VoteRecord {
5462                            judge: j + 1,
5463                            agent: agent_id,
5464                            vote: v.label(),
5465                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5466                            changed: false,
5467                        });
5468                    }
5469                    self.state.event(
5470                        "recover",
5471                        format!("judge {} voted again after the limit", j + 1),
5472                    );
5473                }
5474                Err(e) => {
5475                    self.state
5476                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5477                }
5478            }
5479        }
5480
5481        // A seat that ranked again is present even if its re-vote failed —
5482        // `tally` falls back to the initial ranking's first choice — so clear
5483        // its quota loss. Seats that still fail keep theirs and stay absent.
5484        let recovered_keys: BTreeSet<String> = recovered
5485            .iter()
5486            .map(|&j| format!("judge-{}", j + 1))
5487            .collect();
5488        self.state
5489            .quota
5490            .retain(|q| !recovered_keys.contains(&q.seat));
5491        // A seat that hit the limit again is a fresh loss, not the old one:
5492        // replace the stale entry so the history stays one-per-seat and the
5493        // daemon can tell this attempt's loss from a previous session's.
5494        for loss in judge_losses.into_iter().chain(vote_losses) {
5495            if recovered_keys.contains(&loss.seat) {
5496                continue;
5497            }
5498            self.state.quota.retain(|q| q.seat != loss.seat);
5499            self.state.quota.push(loss);
5500        }
5501
5502        // Recompute the verdict from the refreshed panel.
5503        self.state.tally = None;
5504        self.tally()?;
5505        Ok(self
5506            .state
5507            .tally
5508            .as_ref()
5509            .map(|t| t.met_quorum)
5510            .unwrap_or(false))
5511    }
5512
5513    // ---------------------------------------------------------------- graft
5514
5515    /// Port the strengths the judges attributed to the losing candidates onto
5516    /// the winner, once, between the tally and the review loop.
5517    ///
5518    /// Best-effort by construction: it returns nothing and fails nothing. A
5519    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5520    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5521    /// the run carries on as if the phase were off. See [`graft`] for the
5522    /// decisions and `AGENTS.md` for the invariants.
5523    ///
5524    /// The one exception is a rollback that could not be confirmed: the
5525    /// rejected commit may still be the winner's tip, so the run is blocked
5526    /// (resumable; the record stays `Running`, which makes a resume retry the
5527    /// restore) instead of reviewing, gating and merging it.
5528    async fn graft(&mut self) -> Result<()> {
5529        let Err(e) = self.graft_inner().await else {
5530            return Ok(());
5531        };
5532        if e.is::<crate::repo_lock::ResourceBlocked>() {
5533            return Err(e);
5534        }
5535        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5536            self.state.status = RunStatus::Blocked;
5537            self.state.event("graft", format!("blocked: {e:#}"));
5538            self.state.save()?;
5539            return Err(e);
5540        }
5541        // An error after the `Running` record was saved may have left the
5542        // fixer's work in the tree: the record must not stay unsettled
5543        // (a later resume would reset past the review fixes), so confirm the
5544        // restore now, or block.
5545        if let Some(rec) = self.state.graft.clone()
5546            && !rec.outcome.settled()
5547        {
5548            if let Some(winner) = self.state.winner().cloned() {
5549                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5550                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5551                        return Err(re);
5552                    }
5553                    self.state.status = RunStatus::Blocked;
5554                    self.state.event("graft", format!("blocked: {re:#}"));
5555                    self.state.save()?;
5556                    return Err(re);
5557                }
5558            }
5559            if let Some(g) = self.state.graft.as_mut() {
5560                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5561            }
5562        }
5563        self.state.event("graft", format!("skipped: {e:#}"));
5564        if let Err(e) = self.state.save() {
5565            tracing::warn!("save after graft: {e:#}");
5566        }
5567        Ok(())
5568    }
5569
5570    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5571    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5572    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5573        let _coordination = self.coordinate(wt).await?;
5574        crate::recovery::restore_repair(wt, pre)
5575            .await
5576            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5577    }
5578
5579    /// A skip is a run event, recorded once however often the node is re-entered.
5580    fn graft_skipped(&mut self, why: &str) {
5581        let message = format!("skipped: {why}");
5582        if !self
5583            .state
5584            .events
5585            .iter()
5586            .any(|e| e.node == "graft" && e.message == message)
5587        {
5588            self.state.event("graft", message);
5589        }
5590    }
5591
5592    async fn graft_inner(&mut self) -> Result<()> {
5593        // A round that was started and never finished (crash, kill): the
5594        // fixer may have left anything in the tree, so put the winner back.
5595        if let Some(rec) = self.state.graft.clone()
5596            && !rec.outcome.settled()
5597        {
5598            // Reviews exist only if the graft ended without its record being
5599            // settled (a swallowed error): the tree has moved on since, and
5600            // a reset to `pre` would discard the review fixes.
5601            if self.state.reviews.is_empty()
5602                && let Some(winner) = self.state.winner().cloned()
5603            {
5604                self.graft_restore(&winner.worktree, &rec.pre).await?;
5605            }
5606            if rec.outcome == GraftOutcome::WaitingForRestore {
5607                self.state.graft = None;
5608                self.state.save()?;
5609            } else {
5610                if let Some(g) = self.state.graft.as_mut() {
5611                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5612                }
5613                self.state.event(
5614                    "graft",
5615                    "rolled back: the previous round was interrupted; the winner is untouched",
5616                );
5617                self.state.save()?;
5618                return Ok(());
5619            }
5620        }
5621        let plan = match graft::plan(&self.state) {
5622            Ok(plan) => plan,
5623            Err(skip) => {
5624                if skip != graft::Skip::AlreadyDone {
5625                    self.graft_skipped(skip.reason());
5626                    self.state.save()?;
5627                }
5628                return Ok(());
5629            }
5630        };
5631        let Some(winner) = self.state.winner().cloned() else {
5632            return Ok(());
5633        };
5634        let wt = winner.worktree.clone();
5635        if !git::is_clean(&wt).await? {
5636            self.graft_skipped("the winner's worktree has uncommitted changes");
5637            self.state.save()?;
5638            return Ok(());
5639        }
5640        let pre = git::rev_parse(&wt, "HEAD").await?;
5641        // Saved before the fixer is called: a stop from here on is repaired
5642        // by the branch above on the next entry.
5643        self.state.graft = Some(GraftRecord {
5644            pre: pre.clone(),
5645            post: None,
5646            lines: None,
5647            limit: None,
5648            agent: None,
5649            outcome: GraftOutcome::Running,
5650            requested: graft::requested(&plan),
5651            adoption: None,
5652            adoption_error: None,
5653        });
5654        self.state.event(
5655            "graft",
5656            format!(
5657                "porting strengths of candidate(s) {} onto {}",
5658                plan.strengths
5659                    .iter()
5660                    .map(|(l, _, _)| l.to_string())
5661                    .collect::<Vec<_>>()
5662                    .join(", "),
5663                plan.winner
5664            ),
5665        );
5666        self.state.save()?;
5667
5668        let fix_prompt = prompt::graft(
5669            &self.state.instruction,
5670            plan.winner,
5671            &plan.strengths,
5672            &self.state.config.graph.language,
5673        );
5674        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5675        let sessions = self.state.config.graph.sessions;
5676        let artifacts = agent::artifacts_dir(&self.state.dir());
5677        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5678        let (_, seat, out) = self
5679            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5680                SeatJob {
5681                    prompt: fix_prompt.clone(),
5682                    spec,
5683                    seat,
5684                    cwd: wt.clone(),
5685                    timeout,
5686                    allow_write: true,
5687                    sessions,
5688                    artifacts: artifacts.clone(),
5689                    stem: "graft".to_owned(),
5690                    handover: None,
5691                }
5692            })
5693            .await;
5694        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5695            // Preserve the need to restore earlier fallback edits without
5696            // confusing an unstarted seat with an interrupted invocation.
5697            self.state.graft.as_mut().expect("graft record").outcome =
5698                GraftOutcome::WaitingForRestore;
5699            return self.stop_for_resource();
5700        }
5701        let mut why: Option<String> = None;
5702        match &out {
5703            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5704                why = Some("the fixer produced nothing usable".to_owned());
5705            }
5706            AgentOutcome::Ok(_) => {}
5707            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5708            AgentOutcome::Quota(o) => {
5709                self.state.quota.push(QuotaLoss::from_report(
5710                    seat.key.clone(),
5711                    "graft",
5712                    o.quota.as_ref(),
5713                ));
5714                why = Some("rate limited (quota)".to_owned());
5715            }
5716            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5717                why = Some(format!(
5718                    "the fixer failed: {}",
5719                    e.lines()
5720                        .next()
5721                        .unwrap_or("")
5722                        .chars()
5723                        .take(160)
5724                        .collect::<String>()
5725                ));
5726            }
5727        }
5728        let agent_id = seat.agent.clone();
5729        self.state.seats.insert(seat.key.clone(), seat);
5730
5731        let mut post = None;
5732        let mut lines = None;
5733        let _coordination = self.coordinate(&wt).await?;
5734        if why.is_none() {
5735            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5736            if let Ok(r) = &rescued {
5737                self.state.note_withheld("graft", &r.withheld);
5738            }
5739            let head = git::rev_parse(&wt, "HEAD").await?;
5740            // What is measured must be what gets reviewed and gated: a failed
5741            // rescue, or anything still uncommitted (withheld lockfiles
5742            // aside, which are never part of the tree), rejects the graft.
5743            let dirty = match &rescued {
5744                Ok(r) => git::status_porcelain(&wt)
5745                    .await
5746                    .map(|st| {
5747                        st.lines().any(|l| {
5748                            !r.withheld
5749                                .iter()
5750                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5751                        })
5752                    })
5753                    .unwrap_or(true),
5754                Err(_) => true,
5755            };
5756            if dirty {
5757                why = Some("the fixer left changes that could not be committed".to_owned());
5758            } else if head == pre {
5759                why = Some("the fixer changed nothing".to_owned());
5760            } else {
5761                lines = git::changed_lines(&wt, &pre, &head).await;
5762                post = Some(head);
5763            }
5764        }
5765        let (adoption, adoption_error) = match &out {
5766            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5767            _ => (None, None),
5768        };
5769        let requested = graft::requested(&plan);
5770        let outcome = match why {
5771            None => {
5772                self.state.event(
5773                    "graft",
5774                    format!(
5775                        "applied: {}",
5776                        lines.map_or_else(
5777                            || "changed lines unavailable".to_owned(),
5778                            |n| format!("{n} changed lines")
5779                        )
5780                    ),
5781                );
5782                GraftOutcome::Applied
5783            }
5784            Some(why) => {
5785                // Not settled until the restore is confirmed: the record
5786                // stays `Running`, so a resume retries it.
5787                crate::recovery::restore_repair(&wt, &pre)
5788                    .await
5789                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5790                self.state.event(
5791                    "graft",
5792                    format!("rolled back: {why}; the winner is untouched"),
5793                );
5794                GraftOutcome::RolledBack(why)
5795            }
5796        };
5797        self.state.graft = Some(GraftRecord {
5798            pre,
5799            post,
5800            lines,
5801            limit: None,
5802            agent: Some(agent_id),
5803            outcome,
5804            requested,
5805            adoption,
5806            adoption_error,
5807        });
5808        self.state.save()?;
5809        Ok(())
5810    }
5811
5812    // ----------------------------------------------------------------- fold
5813
5814    async fn fold_losers(&mut self) -> Result<()> {
5815        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5816            return Ok(());
5817        };
5818        if !self.state.candidate_preservation.is_empty() {
5819            bail!("candidate preservation incomplete; refusing cleanup");
5820        }
5821        let repo = self.state.repo.clone();
5822        let _coordination = self.coordinate(&repo).await?;
5823        let home = crate::run::home();
5824        let root = self.state.worktree_root();
5825        let isolated = crate::build_target::isolated(&self.state.config);
5826        let mut folded = Vec::new();
5827        for i in 0..self.state.candidates.len() {
5828            let c = &self.state.candidates[i];
5829            if c.label == winner || c.folded {
5830                continue;
5831            }
5832            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5833            let target = fold_target(&home, &root, &wt, isolated);
5834            remove_preserved_worktree(&repo, &wt).await?;
5835            reclaim_fold_target(&home, target);
5836            if git::branch_exists(&repo, &branch).await?
5837                && !git::branch_delete(&repo, &branch).await?
5838            {
5839                bail!("candidate branch removal refused");
5840            }
5841            self.state.candidates[i].folded = true;
5842            self.state.save()?;
5843            folded.push(label.to_string());
5844        }
5845        // The judges are finished; their checkouts are pure cost from here.
5846        for j in 1..=self.roles.judges.len() {
5847            let wt = root.join(format!("judge-{j}"));
5848            if wt.exists() {
5849                let target = fold_target(&home, &root, &wt, isolated);
5850                remove_read_seat_worktree(&mut self.state, &wt).await?;
5851                reclaim_fold_target(&home, target);
5852                self.state.save()?;
5853            }
5854        }
5855        // The design-deliberation stage is finished by the time a tally
5856        // exists — same reasoning as the judges above.
5857        if self.state.config.graph.advise {
5858            for k in 1..=self.state.config.graph.advisors {
5859                let wt = root.join(format!("advisor-{k}"));
5860                if wt.exists() {
5861                    let target = fold_target(&home, &root, &wt, isolated);
5862                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5863                    reclaim_fold_target(&home, target);
5864                    self.state.save()?;
5865                }
5866            }
5867        }
5868        if !folded.is_empty() {
5869            self.state
5870                .event("fold", format!("folded candidates {}", folded.join(", ")));
5871            self.state.save()?;
5872        }
5873        Ok(())
5874    }
5875
5876    // ------------------------------------------------------------ base sync
5877
5878    async fn hold_base_sync(&mut self) -> Result<bool> {
5879        self.hold_base_sync_as(None).await
5880    }
5881
5882    async fn hold_base_sync_kind(
5883        &mut self,
5884        kind: crate::base_sync_recovery::StopKind,
5885    ) -> Result<()> {
5886        self.hold_base_sync_as(Some(kind)).await?;
5887        Ok(())
5888    }
5889
5890    async fn hold_base_sync_as(
5891        &mut self,
5892        kind: Option<crate::base_sync_recovery::StopKind>,
5893    ) -> Result<bool> {
5894        if !self.state.base_sync_blocked() {
5895            self.state.base_sync_recovery.stop = None;
5896            return Ok(false);
5897        }
5898        let head = match self.state.winner() {
5899            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5900                .await
5901                .unwrap_or_default(),
5902            None => String::new(),
5903        };
5904        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5905            && !authorization.consumed
5906            && authorization.stop.head != head
5907        {
5908            authorization.refuse(format!(
5909                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5910                authorization.stop.head
5911            ));
5912        }
5913        self.state.record_base_sync_stop(&head);
5914        if let Some(kind) = kind {
5915            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5916            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5917                stop.kind = kind;
5918            }
5919        }
5920        self.state.save()?;
5921        Ok(true)
5922    }
5923
5924    async fn resume_legacy_sequencer_stop(
5925        &mut self,
5926        winner: &Candidate,
5927        scratch: &Path,
5928        head: &str,
5929    ) -> Result<()> {
5930        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5931
5932        if !resumable_sequencer_stop(&self.state)
5933            || legacy_sequencer_head(&self.state) != Some(head)
5934            || self.state.base_recovery_pending()
5935            || self
5936                .state
5937                .repair_grants
5938                .iter()
5939                .any(|grant| !grant.succeeded)
5940        {
5941            return Ok(());
5942        }
5943        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5944            return Ok(());
5945        };
5946        let owner = crate::queue::Queue::open().get(task)?;
5947        if owner.execution_runs().last() != Some(&self.state.id)
5948            || owner.status == crate::queue::TaskStatus::Done
5949            || owner.fresh_start
5950            || owner.review_branch.is_some()
5951            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5952        {
5953            return Ok(());
5954        }
5955
5956        let repo = self.state.repo.clone();
5957        let wait = repository_wait(&self.state, None);
5958        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5959        let common = crate::repo_lock::common_dir(&repo).await?;
5960        let op = self.state.base_sync_recovery.operations.last().unwrap();
5961        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5962            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5963            || git::current_branch(&winner.worktree).await?.as_deref()
5964                != Some(winner.branch.as_str())
5965            || common.is_none()
5966            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5967            || crate::repo_lock::common_dir(&owner.repo).await? != common
5968            || !git::is_clean(&winner.worktree).await?
5969        {
5970            return Ok(());
5971        }
5972        if scratch.try_exists()? {
5973            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5974            if admin.join("locked").try_exists()?
5975                || !git::git(
5976                    scratch,
5977                    &[
5978                        "status",
5979                        "--porcelain",
5980                        "--untracked-files=all",
5981                        "--ignored",
5982                    ],
5983                )
5984                .await?
5985                .is_empty()
5986            {
5987                return Ok(());
5988            }
5989            if git::checked_rebase_in_progress(scratch).await? {
5990                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5991                    || crate::rebase::rebase_target(scratch).await? != op.tip
5992                    || !git::unmerged_paths(scratch).await?.is_empty()
5993                {
5994                    return Ok(());
5995                }
5996            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5997                || git::rev_parse(scratch, "HEAD").await? != head
5998            {
5999                return Ok(());
6000            }
6001        }
6002
6003        self.state
6004            .base_sync_recovery
6005            .operations
6006            .last_mut()
6007            .unwrap()
6008            .finished = false;
6009        let diagnostic = self
6010            .state
6011            .base_sync
6012            .as_mut()
6013            .unwrap()
6014            .conflict
6015            .take()
6016            .unwrap();
6017        self.state.base_sync_recovery.stop = None;
6018        self.state.event(
6019            "rebase",
6020            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
6021        );
6022        self.state.save()
6023    }
6024
6025    /// Land the winner's tree on the current tip of `<remote>/<base>` before
6026    /// anything verifies it.
6027    ///
6028    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
6029    /// read whatever is checked out in the winner's worktree. Left alone that
6030    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
6031    /// it when the run *branched* - and a run takes long enough that the base
6032    /// has usually moved by the time it gets here. A gate that ran there
6033    /// answers "green on the commit this run started from", not "green on
6034    /// what is about to land", and the difference showed up three times in
6035    /// one day as a green run whose merge would have reverted a file another
6036    /// pull request had already landed.
6037    ///
6038    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
6039    /// `land::Step::Rebase` calls, rather than a second implementation of the
6040    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
6041    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
6042    /// doc warns about ("two answers to a question nobody notices until a
6043    /// diff is wrong").
6044    ///
6045    /// Foreign-checkout reviews instead merge the base into the owned shadow
6046    /// worktree, preserving the ancestry required for fast-forward delivery.
6047    /// A conflicting merge is aborted and held for operator resolution.
6048    ///
6049    /// A conflict is not the end of the road: the standing rebase is handed
6050    /// to the fixer seat, at most `graph.review_rounds` times, counted in
6051    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
6052    /// land). Once it finishes, review and the gate run as usual on the
6053    /// rebased tree, which is where a breakage the new base caused is caught
6054    /// by the ordinary gate-fix round. magi resolves nothing itself.
6055    ///
6056    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
6057    /// the current durable recovery interval, bounds how often the base is
6058    /// synchronized during active recovery (lifetime attempts remain evidence).
6059    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
6060    /// rebase the branch is restored, `state.base_sync.conflict` is set with
6061    /// what was tried (rounds spent, paths still conflicted) and the branch
6062    /// and worktree stay exactly as they were - untouched, for a person to
6063    /// look at - which is also what makes re-entering this function
6064    /// afterwards a no-op instead of a second attempt at the same wall. A
6065    /// push failure ends the same way.
6066    async fn sync_to_base(&mut self) -> Result<()> {
6067        if self.state.status == RunStatus::AlreadyInBase {
6068            return Ok(());
6069        }
6070        self.hold_base_sync().await?;
6071        let Some(winner) = self.state.winner().cloned() else {
6072            return Ok(());
6073        };
6074
6075        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
6076
6077        let repo = self.state.repo.clone();
6078        let remote = self.state.config.merge.remote.clone();
6079        let base_branch = self.state.base_branch.clone();
6080        let tracking = format!("{remote}/{base_branch}");
6081
6082        let fetched_base =
6083            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
6084        if !fetched_base
6085            && self
6086                .state
6087                .base_sync_recovery
6088                .stop
6089                .as_ref()
6090                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
6091        {
6092            self.state.event(
6093                "land",
6094                "cannot recheck recorded public branch divergence without a fresh base",
6095            );
6096            self.state.save()?;
6097            return Ok(());
6098        }
6099        // No network, or the remote never had this branch: the run already
6100        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
6101        // otherwise), and one that got this far is not blocked by a fetch
6102        // that fails now. It just has no newer tip to compare against.
6103        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
6104            return Ok(());
6105        };
6106
6107        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
6108        self.state.ensure_base_episode();
6109        let scratch = self.state.dir().join("base-sync");
6110        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
6111            .await?;
6112        let conflicted = self
6113            .state
6114            .base_sync
6115            .as_ref()
6116            .is_some_and(|s| s.conflict.is_some());
6117        let mut pending = self.state.pending_base_operation().cloned();
6118        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
6119        {
6120            Ok(active) => active,
6121            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
6122            Err(error) => return Err(error),
6123        };
6124        if in_progress {
6125            // Older resource stops predate operation reservations. Import the
6126            // standing Git operation, never retarget it to today's main.
6127            if pending.is_none()
6128                && self.state.base_sync_recovery.operations.is_empty()
6129                && !conflicted
6130                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
6131                    .await
6132                    .ok()
6133                    .as_deref()
6134                    == Some(head.as_str())
6135                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6136                && git::is_clean(&winner.worktree).await?
6137            {
6138                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
6139                if self.state.base_sync.is_none() {
6140                    self.state.base_sync = Some(BaseSync {
6141                        tip: saved_tip.clone(),
6142                        behind: 0,
6143                        attempts: 0,
6144                        conflict: None,
6145                        already_in: None,
6146                    });
6147                }
6148                self.state.reserve_base_operation(&head, &saved_tip);
6149                self.state.event(
6150                    "base-recovery",
6151                    "imported standing legacy rebase as a spent synchronization reservation",
6152                );
6153                self.state.save()?;
6154                pending = self.state.base_sync_recovery.operations.last().cloned();
6155            }
6156            let expected = pending.as_ref().map(|op| op.tip.as_str());
6157            if expected.is_none()
6158                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
6159            {
6160                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
6161                if self.state.base_sync.is_none() {
6162                    self.state.base_sync = Some(BaseSync {
6163                        tip: tip.clone(),
6164                        behind: 0,
6165                        attempts: 0,
6166                        conflict: None,
6167                        already_in: None,
6168                    });
6169                }
6170                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
6171                self.state.event("land", why);
6172                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6173                    .await?;
6174                return Ok(());
6175            }
6176        }
6177        if let Some(op) = &pending {
6178            // A replay may add the pinned base's commits, never foreign work.
6179            let mut replay_proven =
6180                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6181            if !replay_proven && !in_progress && scratch.try_exists()? {
6182                let wait = repository_wait(&self.state, None);
6183                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6184                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6185                    Ok(true) => {
6186                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6187                        self.state.save()?;
6188                        git::worktree_remove(&repo, &scratch).await.ok();
6189                        replay_proven = true;
6190                    }
6191                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6192                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6193                }
6194            }
6195            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6196                if self.state.foreign_checkout.is_some() {
6197                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6198                        .await
6199                        .ok()
6200                        .as_deref()
6201                        == Some(op.head.as_str())
6202                        && git::rev_parse(&repo, &format!("{head}^2"))
6203                            .await
6204                            .ok()
6205                            .as_deref()
6206                            == Some(op.tip.as_str());
6207                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6208                    .await
6209                    .is_ok_and(|m| m.is_empty())
6210                    && let Ok(added) =
6211                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6212                {
6213                    replay_proven = true;
6214                    for commit in added {
6215                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6216                            replay_proven = false;
6217                            break;
6218                        }
6219                    }
6220                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6221                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6222                }
6223            }
6224            // Never retarget an operation across a crash, even if main moved.
6225            // sync_to_head resets and cleans with -x, so even ignored untracked
6226            // files must stop recovery independently of the old tracked tree.
6227            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6228                || (head != op.head
6229                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6230                        .await?
6231                        .is_empty())
6232                || (!git::is_clean(&winner.worktree).await?
6233                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6234                        .await
6235                        .is_ok_and(|o| o.ok()))
6236                || !replay_proven
6237            {
6238                let why = format!(
6239                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6240                    op.id
6241                );
6242                let sync = self
6243                    .state
6244                    .base_sync
6245                    .as_mut()
6246                    .context("reserved synchronization has no lifetime accounting")?;
6247                sync.conflict = Some(why.clone());
6248                self.state.event("land", why);
6249                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6250                    .await?;
6251                return Ok(());
6252            }
6253            if head != op.head {
6254                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6255            }
6256            tip = op.tip.clone();
6257        }
6258        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6259        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6260        if pending.is_none()
6261            && !conflicted
6262            && fetched_base
6263            && self
6264                .state
6265                .base_sync_recovery
6266                .episodes
6267                .last()
6268                .is_some_and(|e| e.boundary.is_some())
6269            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6270            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6271            && owner.execution_runs().last() == Some(&self.state.id)
6272            && owner.status != crate::queue::TaskStatus::Done
6273            && !owner.fresh_start
6274            && owner.review_branch.is_none()
6275            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6276            && let Some(approval) = owner.resumption.as_ref()
6277            && approval.instruction == owner.instruction
6278            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6279            && git::is_clean(&winner.worktree).await?
6280            && self.state.renew_base_episode(&task, approval, &head, &tip)
6281        {
6282            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6283            self.state.save()?;
6284        }
6285
6286        // Before any rebase, and before a recorded conflict is honoured: a
6287        // branch whose change reached the base under other commit ids has
6288        // nothing to rebase and nothing to conflict with, and a run that
6289        // already stopped on that phantom conflict recovers here on resume.
6290        // `behind == 0` with head == tip is a branch the base has since taken
6291        // in whole, whether or not a conflict was ever recorded: the ancestry
6292        // proof must still run (`classify` ignores a head still on the start
6293        // commit).
6294        if (behind > 0 || conflicted || head == tip)
6295            && self
6296                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6297                .await?
6298        {
6299            return Ok(());
6300        }
6301        if conflicted && self.state.base_recovery_pending() {
6302            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6303            let owner =
6304                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6305            let owner_valid = owner.as_ref().is_ok_and(|t| {
6306                t.execution_runs().last() == Some(&self.state.id)
6307                    && t.assignment_accepts(&self.state)
6308                    && t.status != crate::queue::TaskStatus::Done
6309                    && !t.fresh_start
6310                    && t.review_branch.is_none()
6311            });
6312            let invalidation = if !owner_valid {
6313                Some("latest task ownership changed")
6314            } else if !owner.as_ref().is_ok_and(|t| {
6315                authorization
6316                    .generation
6317                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6318            }) {
6319                Some("owner approval generation changed")
6320            } else if authorization.question.as_ref().is_some_and(|question| {
6321                !crate::base_recovery_control::decision_current(
6322                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6323                    &self.state,
6324                    &authorization.task,
6325                    question,
6326                )
6327            }) {
6328                Some("recovery decision ownership, routing or stop evidence changed")
6329            } else if authorization.request.is_some()
6330                && !owner
6331                    .as_ref()
6332                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6333            {
6334                Some("owner decision changed")
6335            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6336                && !authorization.scope.as_ref().is_some_and(|scope| {
6337                    scope.preparation_digest.is_some()
6338                        && scope.preparation_digest == self.state.preparation_digest(&head)
6339                })
6340            {
6341                Some("scratch preparation stop evidence changed")
6342            } else if let Some(scope) = &authorization.scope {
6343                if scope.tip != tip {
6344                    Some("fetched base changed")
6345                } else if !self
6346                    .state
6347                    .base_sync_recovery
6348                    .episodes
6349                    .last()
6350                    .is_some_and(|e| e.id == scope.episode)
6351                {
6352                    Some("active synchronization interval changed")
6353                } else if !owner
6354                    .as_ref()
6355                    .is_ok_and(|t| t.instruction == scope.instruction)
6356                {
6357                    Some("task instruction changed")
6358                } else {
6359                    None
6360                }
6361            } else {
6362                None
6363            };
6364            if let Some(reason) = invalidation {
6365                let authorization = self
6366                    .state
6367                    .base_sync_recovery
6368                    .authorizations
6369                    .last_mut()
6370                    .unwrap();
6371                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6372                self.state.save()?;
6373                return Ok(());
6374            }
6375            if !fetched_base
6376                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6377                || !git::is_clean(&winner.worktree).await?
6378                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6379            {
6380                return Ok(());
6381            }
6382            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6383                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6384            }
6385        }
6386        let recovery = conflicted && self.state.consume_base_recovery(&head);
6387        if conflicted {
6388            // Consumption (including a refused changed HEAD) is durable before Git.
6389            self.state.save()?;
6390            if !recovery {
6391                return Ok(());
6392            }
6393        }
6394
6395        if behind == 0 {
6396            // A fixer-finished rebase moves the branch ref before the
6397            // winner's worktree is told (`sync_to_head` below). A run that
6398            // died in between resumes here with `behind == 0` and a tree still
6399            // holding the pre-rebase files, which review and the gate would
6400            // then read. That state is exactly: HEAD moved off the tip the
6401            // rebase started from, yet the tree is still identical to that
6402            // tip. A tree with edits of its own differs from it, so nothing
6403            // is thrown away.
6404            if let Some(from) = self
6405                .state
6406                .rebase_fixes
6407                .iter()
6408                .rev()
6409                .find_map(|r| r.from.clone())
6410                && from != head
6411                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6412                    .await
6413                    .is_ok_and(|o| o.ok())
6414            {
6415                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6416            }
6417            // An earlier attempt may have rebased the branch locally and died
6418            // before pushing it (only the fresh-rebase arm below pushes).
6419            // Publish it now, so the plain push at PR time is not refused as
6420            // a non-fast-forward. A run already holding a recorded conflict
6421            // never reaches here; that case is out of scope.
6422            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6423            if let Some(why) = &conflict {
6424                self.state.status = RunStatus::Blocked;
6425                self.state.event("land", why.clone());
6426            }
6427            self.state.base_sync = Some(BaseSync {
6428                tip,
6429                behind: 0,
6430                attempts,
6431                conflict,
6432                already_in: None,
6433            });
6434            if pending.is_some() {
6435                self.state.finish_base_operation(Some(&head));
6436            }
6437            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6438                .await?;
6439            self.state.save()?;
6440            return Ok(());
6441        }
6442
6443        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6444            let why = format!(
6445                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6446                 synchronization(s); synchronizing again would only race it",
6447                winner.branch
6448            );
6449            self.state.status = RunStatus::Blocked;
6450            self.state.base_sync = Some(BaseSync {
6451                tip,
6452                behind,
6453                attempts,
6454                conflict: Some(why.clone()),
6455                already_in: None,
6456            });
6457            self.state.event("land", why);
6458            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6459                .await?;
6460            self.state.save()?;
6461            return Ok(());
6462        }
6463
6464        if self.state.foreign_checkout.is_some() {
6465            // Delivery to the operator's checkout is fast-forward only. A
6466            // rebase here would discard its saved head from our ancestry.
6467            let wait = repository_wait(&self.state, None);
6468            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6469            if self.state.base_sync.is_none() {
6470                self.state.base_sync = Some(BaseSync {
6471                    tip: tip.clone(),
6472                    behind,
6473                    attempts: 0,
6474                    conflict: None,
6475                    already_in: None,
6476                });
6477            }
6478            self.state.reserve_base_operation(&head, &tip);
6479            self.state.save()?;
6480            let merged = git::git_raw(
6481                &winner.worktree,
6482                &[
6483                    "-c",
6484                    "core.hooksPath=/dev/null",
6485                    "merge",
6486                    "--no-ff",
6487                    "--no-autostash",
6488                    "--no-edit",
6489                    "-m",
6490                    &format!("Merge {tracking} before verifying"),
6491                    &tip,
6492                ],
6493            )
6494            .await?;
6495            let conflict = if merged.ok() {
6496                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6497                self.state.event(
6498                    "land",
6499                    format!("merged {tracking} into {} before verifying", winner.branch),
6500                );
6501                None
6502            } else {
6503                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6504                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6505                }
6506                let why = format!(
6507                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6508                    winner.branch,
6509                    merged.stderr.chars().take(600).collect::<String>()
6510                );
6511                self.state.status = RunStatus::Blocked;
6512                self.state.event("land", &why);
6513                Some(why)
6514            };
6515            let synced = conflict.is_none();
6516            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6517            self.state
6518                .finish_base_operation(synced.then_some(fresh.as_str()));
6519            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6520            self.state.base_sync = Some(BaseSync {
6521                tip,
6522                behind: if synced { 0 } else { behind },
6523                attempts,
6524                conflict,
6525                already_in: None,
6526            });
6527            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6528                .await?;
6529            self.state.save()?;
6530            return Ok(());
6531        }
6532
6533        self.state.event(
6534            "land",
6535            format!(
6536                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6537                winner.branch
6538            ),
6539        );
6540        self.state.save()?;
6541
6542        // The remote's copy of the branch, read now and only if the fetch
6543        // really succeeded (a stale tracking ref must never pin a lease). It is
6544        // pushed over after a rebase only when it is a commit this branch
6545        // already contains, by ancestry or by patch (an earlier rebase of ours
6546        // that never reached the remote): anything else is somebody else's work.
6547        let branch_tracking = format!("{remote}/{}", winner.branch);
6548        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6549        let remote_tip = if self.state.task_pr_branch().is_none()
6550            && matches!(&fetched_branch, Ok(o) if o.ok())
6551        {
6552            git::rev_parse(&repo, &branch_tracking).await.ok()
6553        } else {
6554            None
6555        };
6556        // A remote tip this branch does not contain is somebody else's work:
6557        // rebasing would leave a local tip that can never be pushed. Stop
6558        // before touching anything and say so.
6559        if let Some(theirs) = &remote_tip
6560            && !git::is_ancestor(&repo, theirs, &head).await
6561            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6562                .await
6563                .is_ok_and(|missing| missing.is_empty())
6564        {
6565            let why = format!(
6566                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6567                 them",
6568                short(theirs),
6569                winner.branch
6570            );
6571            self.state.status = RunStatus::Blocked;
6572            self.state.base_sync = Some(BaseSync {
6573                tip,
6574                behind,
6575                attempts,
6576                conflict: Some(why.clone()),
6577                already_in: None,
6578            });
6579            self.state.event("land", why);
6580            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6581                .await?;
6582            self.state.save()?;
6583            return Ok(());
6584        }
6585
6586        if self.state.base_sync.is_none() {
6587            self.state.base_sync = Some(BaseSync {
6588                tip: tip.clone(),
6589                behind,
6590                attempts: 0,
6591                conflict: None,
6592                already_in: None,
6593            });
6594        }
6595        let scratch = self.state.dir().join("base-sync");
6596        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6597        {
6598            if error.is::<crate::repo_lock::ResourceBlocked>() {
6599                return Ok(());
6600            }
6601            return Err(error);
6602        }
6603        self.state.reserve_base_operation(&head, &tip);
6604        self.state.save()?;
6605        let rebased =
6606            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6607                .await
6608            {
6609                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6610                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6611                Err(e) => Err(e),
6612            };
6613        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6614        let stop_kind = match &rebased {
6615            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6616            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6617            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6618        };
6619        match rebased {
6620            Ok(None) => {
6621                // The branch ref moved, but a worktree that already had it
6622                // checked out (the winner's) was not told; sync its index and
6623                // files before anything reads them.
6624                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6625                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6626                self.state.finish_base_operation(Some(&fresh));
6627                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6628                let mut conflict = None;
6629                if let Some(pinned) = &remote_tip {
6630                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6631                    match pushed {
6632                        Ok(o) if o.ok() => self.state.event(
6633                            "land",
6634                            format!("pushed rebased {} to {remote}", winner.branch),
6635                        ),
6636                        Ok(o) => {
6637                            conflict = Some(format!(
6638                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6639                                winner.branch,
6640                                short(pinned),
6641                                o.stderr.chars().take(600).collect::<String>()
6642                            ));
6643                        }
6644                        Err(e) => {
6645                            conflict = Some(format!(
6646                                "rebased {} locally but could not push it: {e:#}",
6647                                winner.branch
6648                            ));
6649                        }
6650                    }
6651                }
6652                if let Some(why) = &conflict {
6653                    self.state.status = RunStatus::Blocked;
6654                    self.state.event("land", why.clone());
6655                }
6656                self.state.base_sync = Some(BaseSync {
6657                    tip: tip.clone(),
6658                    behind: 0,
6659                    attempts,
6660                    conflict,
6661                    already_in: None,
6662                });
6663                self.state
6664                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6665            }
6666            Ok(Some(conflict)) => {
6667                self.state.finish_base_operation(None);
6668                let why = format!(
6669                    "{} conflicts with {tracking} and did not rebase: {}",
6670                    winner.branch,
6671                    conflict.chars().take(600).collect::<String>()
6672                );
6673                self.state.status = RunStatus::Blocked;
6674                self.state.base_sync = Some(BaseSync {
6675                    tip,
6676                    behind,
6677                    attempts,
6678                    conflict: Some(why.clone()),
6679                    already_in: None,
6680                });
6681                self.state.event("land", why);
6682            }
6683            // A refused Git write or a busy repository: nothing is wrong with
6684            // the branch. The scratch rebase stays standing and the run
6685            // resumes into it (`base_sync` must not claim a conflict).
6686            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6687                self.state.save()?;
6688                return Ok(());
6689            }
6690            Err(e) => {
6691                self.state.finish_base_operation(None);
6692                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6693                self.state.status = RunStatus::Blocked;
6694                self.state.base_sync = Some(BaseSync {
6695                    tip,
6696                    behind,
6697                    attempts,
6698                    conflict: Some(why.clone()),
6699                    already_in: None,
6700                });
6701                self.state.event("land", why);
6702            }
6703        }
6704        if !self.state.base_sync_blocked() {
6705            self.state.base_sync_recovery.stop = None;
6706        }
6707        self.hold_base_sync_kind(stop_kind).await?;
6708        self.state.save()?;
6709        Ok(())
6710    }
6711
6712    /// Push a branch an earlier attempt rebased locally but never published,
6713    /// pinned to the remote tip read right after a successful fetch. Returns
6714    /// the reason when the run must stop; `None` when there was nothing to do
6715    /// (no remote copy, the same tip, or a remote copy this branch already
6716    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6717    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6718        // Task competitions publish only after the PR text gate, to their
6719        // public head; never resurrect a candidate branch on the remote.
6720        if self.state.task_pr_branch().is_some() {
6721            return None;
6722        }
6723        let repo = self.state.repo.clone();
6724        let remote = self.state.config.merge.remote.clone();
6725        let fetched = git::fetch(&repo, &remote, branch).await;
6726        if !matches!(&fetched, Ok(o) if o.ok()) {
6727            return None;
6728        }
6729        let branch_tracking = format!("{remote}/{branch}");
6730        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6731        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6732            return None;
6733        }
6734        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6735            .await
6736            .is_ok_and(|missing| missing.is_empty())
6737        {
6738            return Some(format!(
6739                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6740                 them",
6741                short(&theirs)
6742            ));
6743        }
6744        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6745            Ok(o) if o.ok() => {
6746                self.state
6747                    .event("land", format!("pushed rebased {branch} to {remote}"));
6748                None
6749            }
6750            Ok(o) => Some(format!(
6751                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6752                 someone may have pushed): {}",
6753                short(&theirs),
6754                o.stderr.chars().take(600).collect::<String>()
6755            )),
6756            Err(e) => Some(format!(
6757                "{branch} is rebased locally but could not be pushed: {e:#}"
6758            )),
6759        }
6760    }
6761
6762    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6763    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6764    /// whether it did.
6765    ///
6766    /// Checked only when the base is ahead of the branch. A failing check is
6767    /// "not proven" - the ordinary rebase path then decides - never a reason to
6768    /// stop the run.
6769    ///
6770    /// The remote copy of the branch is held to the same standard as the local
6771    /// one: if it carries a tip this worktree does not, that tip must itself be
6772    /// proven in the base, or nothing is settled (a pull request would
6773    /// otherwise be closed over commits nobody checked). The pull request is
6774    /// closed *before* the terminal status is saved; if that fails for a
6775    /// reason other than a refusal (no network, a `gh` error) the run is left
6776    /// `Blocked` with the reason as its conflict, which a resume retries -
6777    /// the same recovery a phantom conflict gets.
6778    async fn settle_already_in(
6779        &mut self,
6780        branch: &str,
6781        tip: &str,
6782        head: &str,
6783        attempts: usize,
6784        behind: usize,
6785    ) -> Result<bool> {
6786        let repo = self.state.repo.clone();
6787        let remote = self.state.config.merge.remote.clone();
6788        let start = self.state.base_commit.clone();
6789        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6790            Ok(Some(e)) => e,
6791            Ok(None) => return Ok(false),
6792            Err(e) => {
6793                tracing::warn!("already-in-base check for {branch}: {e:#}");
6794                return Ok(false);
6795            }
6796        };
6797        let mut verified = vec![head.to_owned()];
6798        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6799        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6800        let divergence = self
6801            .state
6802            .base_sync_recovery
6803            .stop
6804            .as_ref()
6805            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6806        if matches!(&fetched, Ok(o) if o.ok()) {
6807            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6808                Ok(theirs) if theirs != head => {
6809                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6810                        Ok(Some(_)) => verified.push(theirs),
6811                        _ => return Ok(false),
6812                    }
6813                }
6814                Err(_) if divergence => return Ok(false),
6815                _ => {}
6816            }
6817        } else if divergence
6818            && !matches!(
6819                git::remote_has_branch(&repo, &remote, &public_branch).await,
6820                Ok(false)
6821            )
6822        {
6823            // A failed fetch cannot discharge a recorded divergence.
6824            return Ok(false);
6825        }
6826        let base_branch = self.state.base_branch.clone();
6827        let message = format!(
6828            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6829             land",
6830            evidence.names(),
6831            evidence.proof.as_str()
6832        );
6833        let closed =
6834            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6835                .await;
6836        match closed {
6837            Ok(Ok(url)) => self
6838                .state
6839                .event("land", format!("closed {url}: superseded on {base_branch}")),
6840            Ok(Err(why)) => self
6841                .state
6842                .event("land", format!("did not close a pull request: {why}")),
6843            Err(e) => {
6844                let why = format!(
6845                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6846                     not be closed ({e:#}); resume to retry"
6847                );
6848                self.state.status = RunStatus::Blocked;
6849                self.state.base_sync = Some(BaseSync {
6850                    tip: tip.to_owned(),
6851                    behind,
6852                    attempts,
6853                    conflict: Some(why.clone()),
6854                    already_in: None,
6855                });
6856                self.state.event("land", why);
6857                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6858                    .await?;
6859                self.state.save()?;
6860                return Ok(true);
6861            }
6862        }
6863        self.state.status = RunStatus::AlreadyInBase;
6864        self.state.base_sync_recovery.stop = None;
6865        self.state.base_sync = Some(BaseSync {
6866            tip: tip.to_owned(),
6867            behind,
6868            attempts,
6869            conflict: None,
6870            already_in: Some(evidence),
6871        });
6872        self.state.event("land", message);
6873        self.state.save()?;
6874        self.settle_questions();
6875        Ok(true)
6876    }
6877
6878    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6879    /// last landed the winner on, once it has run, else the commit the run
6880    /// branched from.
6881    ///
6882    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6883    /// and `vote` all happen before there is a winner to rebase, so they
6884    /// compare every candidate against the branch point on purpose, and a
6885    /// base that moves after they are already done cannot change an answer
6886    /// they already gave.
6887    fn landing_base(&self) -> String {
6888        self.state
6889            .base_sync
6890            .as_ref()
6891            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6892    }
6893
6894    // ------------------------------------------------------- operator fix
6895
6896    /// Route specific, already-recorded review findings to a fixer for a
6897    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6898    /// entry point.
6899    ///
6900    /// Distinct from `review_loop`'s own fix step in three ways: it never
6901    /// runs a reviewer wave, it never spends review-round budget, and what
6902    /// happened is recorded as an [`OperatorFixRequest`] appended to
6903    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6904    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6905    /// and vote must never be rewritten to look like a manufactured blocking
6906    /// verdict.
6907    ///
6908    /// Only meaningful once review has actually concluded: `Ready` (handed
6909    /// off with findings still open, or simply concluded clean while minor
6910    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6911    /// gate failed). Everything else is refused: a run still in progress
6912    /// should simply be resumed, and a `Merged` run's branch has already
6913    /// landed — reopening *this* run's own record cannot change that, so the
6914    /// answer there is a fresh `magi review <branch>`.
6915    ///
6916    /// A real commit here re-verifies through a fresh, ordinary review-only
6917    /// run on the same branch ([`Self::review`]) rather than reopening this
6918    /// run's own `review_loop`: once any round in this run's history went
6919    /// clean, `review_conclusion` treats that as permanent by design (the
6920    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6921    /// way to force one more genuine reviewer wave out of *this* run without
6922    /// either rewriting history or weakening that guarantee for every other
6923    /// caller. A review-only run costs nothing extra — no implementation, no
6924    /// judging, no vote — and exercises the exact same review → verify →
6925    /// gate → (human) merge path, unmodified.
6926    pub async fn fix_selected(
6927        &mut self,
6928        ids: &[String],
6929        reason: &str,
6930        allow_stale: bool,
6931    ) -> Result<()> {
6932        let reason = reason.trim();
6933        if reason.is_empty() {
6934            bail!("a fix request needs a reason — that is the operator's own record of why");
6935        }
6936        if ids.is_empty() {
6937            bail!("no finding id given");
6938        }
6939        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6940            bail!(
6941                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6942                 has already concluded — can be given a targeted fix. A run still \
6943                 in progress should simply be resumed; a `merged` run's branch has \
6944                 already landed, so its answer is a fresh `magi review <branch>`, \
6945                 not reopening this run's own record",
6946                self.state.id,
6947                self.state.status.as_str()
6948            );
6949        }
6950        // Reassignment shares this claim through its atomic task save. Check
6951        // the canonical run identity inside it, before preflight or any await.
6952        let _claim = FixClaim::acquire(&self.state.dir())?;
6953        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6954        let home = crate::run::home();
6955        // The ordinary driver takes these same locks at admission. Keep the
6956        // execution lease through the fix, but never the owner lock across Git
6957        // or agent awaits.
6958        let execution = {
6959            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6960            let disk = RunState::load(&self.state.id)?;
6961            crate::pr_head::ensure_owner(&disk)?;
6962            anyhow::ensure!(
6963                disk.status == self.state.status && disk.released_to.is_none(),
6964                "run changed since it was loaded; reload before fixing"
6965            );
6966            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6967            anyhow::ensure!(
6968                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6969                "run {} is currently being worked on or its ownership is unknown",
6970                disk.id
6971            );
6972            let lease = crate::driver::maintenance(&home, &disk.id).context(
6973                "run is currently being worked on or its execution lease is unavailable",
6974            )?;
6975            self.state = disk;
6976            lease
6977        };
6978        let Some(winner) = self.state.winner().cloned() else {
6979            bail!("run {} has no winning candidate to fix", self.state.id);
6980        };
6981        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6982            bail!(
6983                "branch `{}` no longer exists; this run cannot be extended",
6984                winner.branch
6985            );
6986        }
6987        // Resolve every id before spending anything — an unknown id refuses
6988        // the whole request rather than silently dropping it — and dedup
6989        // while keeping the operator's own order.
6990        let mut seen = BTreeSet::new();
6991        let mut findings = Vec::new();
6992        let mut missing = Vec::new();
6993        for id in ids {
6994            if !seen.insert(id.clone()) {
6995                continue;
6996            }
6997            match self.state.finding(id) {
6998                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6999                    id: f.id.clone(),
7000                    severity: f.severity,
7001                    reviewer_vote: rec.vote,
7002                    round: round.round,
7003                    round_head: round.head.clone(),
7004                    reviewer: rec.reviewer,
7005                    agent: rec.agent.clone(),
7006                    file: f.file.clone(),
7007                    line: f.line,
7008                    title: f.title.clone(),
7009                    detail: f.detail.clone(),
7010                    outcome: OperatorFixOutcome::Pending,
7011                }),
7012                None => missing.push(id.clone()),
7013            }
7014        }
7015        if !missing.is_empty() {
7016            bail!(
7017                "unknown finding id(s): {}; nothing was changed",
7018                missing.join(", ")
7019            );
7020        }
7021
7022        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
7023        let stale_details: Vec<(String, String)> = findings
7024            .iter()
7025            .filter(|f| f.round_head != head_at_request)
7026            .map(|f| (f.id.clone(), f.round_head.clone()))
7027            .collect();
7028        let stale = !stale_details.is_empty();
7029        if stale && !allow_stale {
7030            bail!(
7031                "the branch has moved since some finding(s) were raised — {} — now \
7032                 at {}; pass --allow-stale to fix anyway, or re-run review first",
7033                stale_details
7034                    .iter()
7035                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
7036                    .collect::<Vec<_>>()
7037                    .join(", "),
7038                short(&head_at_request)
7039            );
7040        }
7041
7042        let request = OperatorFixRequest {
7043            requested_at: Timestamp::now(),
7044            reason: reason.to_owned(),
7045            findings,
7046            head_at_request: head_at_request.clone(),
7047            allow_stale,
7048            stale,
7049            fix: None,
7050            result_head: None,
7051            follow_up_review_run: None,
7052        };
7053        self.state.event(
7054            "fix",
7055            format!(
7056                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
7057                request.findings.len(),
7058                request
7059                    .findings
7060                    .iter()
7061                    .map(|f| f.id.as_str())
7062                    .collect::<Vec<_>>()
7063                    .join(", "),
7064            ),
7065        );
7066        // Recorded now, before any worktree work or the fixer call itself —
7067        // and re-saved at each checkpoint below: a crash at any point after
7068        // this (mid fixer call, mid follow-up review) must not lose the fact
7069        // that this was requested, for which findings, and why. Everything
7070        // past this point reads and writes through `request_index` rather
7071        // than a local variable, since `request` itself is moved here.
7072        self.state.operator_fixes.push(request);
7073        self.state.save()?;
7074        let request_index = self.state.operator_fixes.len() - 1;
7075
7076        // A fresh, dedicated worktree for this one call, never the winner's
7077        // own worktree in place: that one may already be gone (folded away),
7078        // and reusing it in place would leave the branch checked out there
7079        // when the follow-up review below tries to check it out again. Freed
7080        // immediately after, either way — but only once confirmed clean:
7081        // `worktree_remove` is a `git worktree remove --force`, which would
7082        // otherwise discard uncommitted work left there by the operator or
7083        // another process before this had a chance to even look at it.
7084        let repo = self.state.repo.clone();
7085        let coordination = self.coordinate(&repo).await?;
7086        if winner.worktree.exists() {
7087            // Lockfiles a rescue commit withheld stay untracked on purpose and
7088            // are already recorded; they are not the operator's work to protect.
7089            let dirty = git::git(
7090                &winner.worktree,
7091                &["status", "--porcelain", "--untracked-files=all"],
7092            )
7093            .await?;
7094            let only_withheld = dirty.lines().all(|l| {
7095                l.strip_prefix("?? ")
7096                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
7097            });
7098            if !only_withheld {
7099                bail!(
7100                    "`{}` has uncommitted changes; refusing to touch it — commit or \
7101                     discard them first",
7102                    winner.worktree.display()
7103                );
7104            }
7105            git::worktree_remove(&self.state.repo, &winner.worktree)
7106                .await
7107                .ok();
7108        }
7109        let fix_worktree = self.state.worktree_root().join("operator-fix");
7110        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
7111        git::git(
7112            &self.state.repo,
7113            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
7114        )
7115        .await
7116        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
7117        if !git::is_clean(&fix_worktree).await? {
7118            git::worktree_remove(&self.state.repo, &fix_worktree)
7119                .await
7120                .ok();
7121            bail!(
7122                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
7123                winner.branch
7124            );
7125        }
7126        let repo_for_setup = self.state.repo.clone();
7127        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
7128            Ok(()) => {
7129                worktree_setup::prepare_with(
7130                    &self.state.config,
7131                    &repo_for_setup,
7132                    &fix_worktree,
7133                    crate::build_target::Coordination::Held(coordination.as_ref()),
7134                )
7135                .await
7136            }
7137            Err(e) => Err(e),
7138        };
7139        if let Err(e) = setup {
7140            git::worktree_remove(&self.state.repo, &fix_worktree)
7141                .await
7142                .ok();
7143            return Err(e);
7144        }
7145
7146        // This explicit operator request retries availability independently
7147        // of execute(); the previous call has already saved and cleaned up.
7148        self.state.resource_block = None;
7149
7150        let run_id = self.state.id.clone();
7151        let prompts = self.state.config.prompts.clone();
7152        let language = self.state.config.graph.language.clone();
7153        let sessions = self.state.config.graph.sessions;
7154        let artifacts = agent::artifacts_dir(&self.state.dir());
7155        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
7156            .findings
7157            .iter()
7158            .map(|f| Finding {
7159                id: f.id.clone(),
7160                severity: f.severity,
7161                file: f.file.clone(),
7162                line: f.line,
7163                title: f.title.clone(),
7164                detail: f.detail.clone(),
7165            })
7166            .collect();
7167        let fix_prompt = prompt::operator_fix_in(
7168            &self.state.instruction,
7169            &finding_list,
7170            reason,
7171            &stale_details,
7172            &head_at_request,
7173            &language,
7174            &self.state.config.graph.github_language,
7175        );
7176        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7177        drop(coordination);
7178        let (job, seat, out) = self
7179            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7180                prompt: fix_prompt.clone(),
7181                spec,
7182                seat,
7183                cwd: fix_worktree.clone(),
7184                timeout,
7185                allow_write: true,
7186                sessions,
7187                artifacts: artifacts.clone(),
7188                stem: "operator-fix".to_owned(),
7189                handover: None,
7190            })
7191            .await;
7192        let agent_id = seat.agent.clone();
7193
7194        let mut fix = FixRecord {
7195            agent: agent_id,
7196            addressed: Vec::new(),
7197            rejected: Vec::new(),
7198            notes: String::new(),
7199            committed: false,
7200            failed: None,
7201            duration_ms: 0,
7202            continuation: None,
7203        };
7204        let mut final_seat = seat.clone();
7205        match out {
7206            AgentOutcome::Ok(o) => {
7207                fix.duration_ms = o.duration_ms;
7208                let parsed = verdict::extract_json::<FixReport>(&o.text);
7209                let incomplete_reason = match &parsed {
7210                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7211                        "the reply parsed, but it reported a command whose own CLI \
7212                         never confirmed an exit status"
7213                            .to_owned(),
7214                    ),
7215                    Ok(_) => None,
7216                    Err(e) => Some(e.to_string()),
7217                };
7218                match incomplete_reason {
7219                    None => {
7220                        let report = parsed.expect("checked Ok above");
7221                        fix.addressed = report.addressed;
7222                        fix.rejected = report.rejected;
7223                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7224                    }
7225                    Some(reason) => {
7226                        let (resumed_seat, resolved, failure, cont) = self
7227                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7228                            .await;
7229                        fix.duration_ms += cont.cumulative_wait_ms;
7230                        fix.continuation = Some(cont);
7231                        final_seat = resumed_seat;
7232                        match resolved {
7233                            Some(report) => {
7234                                fix.addressed = report.addressed;
7235                                fix.rejected = report.rejected;
7236                                fix.notes =
7237                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7238                            }
7239                            None => fix.failed = failure,
7240                        }
7241                    }
7242                }
7243            }
7244            AgentOutcome::Dropped(o) => {
7245                fix.duration_ms = o.duration_ms;
7246                let why = o
7247                    .dropped
7248                    .as_ref()
7249                    .map(|d| d.why.as_str())
7250                    .unwrap_or("the CLI ended the stream without delivering its answer");
7251                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7252            }
7253            AgentOutcome::Quota(o) => {
7254                self.state.quota.push(QuotaLoss::from_report(
7255                    final_seat.key.clone(),
7256                    "fix",
7257                    o.quota.as_ref(),
7258                ));
7259                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7260            }
7261            AgentOutcome::Failed(e) => fix.failed = Some(e),
7262            AgentOutcome::ResourceBlocked(e) => {
7263                fix.failed = Some(format!("the fixer was not started: {e}"));
7264            }
7265        }
7266        // Even a deferred call must rescue edits, release the worktree and
7267        // finalize its record below so an explicit `magi fix` can retry.
7268        if fix.continuation.is_none() {
7269            fix.continuation = Some(ContinuationRecord::not_needed());
7270        }
7271        self.state.seats.insert(final_seat.key.clone(), final_seat);
7272
7273        let rescue_message = format!(
7274            "magi: operator-selected fix ({}) (uncommitted work)",
7275            self.state.operator_fixes[request_index]
7276                .findings
7277                .iter()
7278                .map(|f| f.id.as_str())
7279                .collect::<Vec<_>>()
7280                .join(", ")
7281        );
7282        let repo = self.state.repo.clone();
7283        let coordination = self.coordinate(&repo).await?;
7284        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7285            self.state.note_withheld("fix", &r.withheld);
7286        }
7287        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7288        fix.committed = after != head_at_request;
7289        git::worktree_remove(&self.state.repo, &fix_worktree)
7290            .await
7291            .ok();
7292        drop(coordination);
7293
7294        self.state.event(
7295            "fix",
7296            match &fix.failed {
7297                Some(reason) => format!(
7298                    "operator fix: adoption report was lost ({reason}); {}",
7299                    if fix.committed {
7300                        "committed"
7301                    } else {
7302                        "NO new commit"
7303                    }
7304                ),
7305                None => format!(
7306                    "operator fix: {} addressed, {} rejected, {}",
7307                    fix.addressed.len(),
7308                    fix.rejected.len(),
7309                    if fix.committed {
7310                        "committed"
7311                    } else {
7312                        "NO new commit"
7313                    }
7314                ),
7315            },
7316        );
7317
7318        // Every selected finding gets an outcome — never left `Pending` once
7319        // the fixer's own turn is over. A report that never came back at all
7320        // marks every one of them `Unreported`, not silently "not addressed":
7321        // quota, a dropped stream, or an exhausted continuation are gaps in
7322        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7323        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7324        for f in &mut self.state.operator_fixes[request_index].findings {
7325            f.outcome = if fix.failed.is_some() {
7326                OperatorFixOutcome::Unreported
7327            } else if fix.addressed.contains(&f.id) {
7328                OperatorFixOutcome::Addressed
7329            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7330                OperatorFixOutcome::Rejected { why: r.why.clone() }
7331            } else {
7332                OperatorFixOutcome::Unreported
7333            };
7334        }
7335
7336        let committed = fix.committed;
7337        if committed {
7338            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7339        }
7340        self.state.operator_fixes[request_index].fix = Some(fix);
7341        // Saved again now that the fixer's own outcome is final, on top of
7342        // the save right after the request was first pushed above.
7343        self.state.save()?;
7344        if self.state.resource_block.is_some() {
7345            return self.stop_for_resource();
7346        }
7347
7348        if committed {
7349            self.state.event(
7350                "fix",
7351                format!(
7352                    "operator fix committed {}; opening a follow-up review-only run",
7353                    short(&after)
7354                ),
7355            );
7356            self.state.save()?;
7357            drop(execution);
7358            // The new review owns its own execution. Update only its audit link
7359            // afterwards, since publication may have changed the old record.
7360            let event_count = self.state.events.len();
7361            let save_follow_up = |state: &mut RunState| -> Result<()> {
7362                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7363                let _execution = crate::driver::maintenance(&home, &state.id)?;
7364                let mut disk = RunState::load(&state.id)?;
7365                disk.events.extend(state.events.drain(event_count..));
7366                let follow_up = state.operator_fixes[request_index]
7367                    .follow_up_review_run
7368                    .clone();
7369                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7370                disk.save()?;
7371                *state = disk;
7372                Ok(())
7373            };
7374            // The operator asked for the fix, and the follow-up serves whatever
7375            // task the run it follows served.
7376            let origin =
7377                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7378            match Self::review(
7379                &self.state.repo,
7380                &winner.branch,
7381                self.state.config.clone(),
7382                origin,
7383            )
7384            .await
7385            {
7386                Ok(mut follow_up) => {
7387                    follow_up.state.event(
7388                        "start",
7389                        format!(
7390                            "requested by an operator fix on run {} for finding(s) {}",
7391                            self.state.id,
7392                            self.state.operator_fixes[request_index]
7393                                .findings
7394                                .iter()
7395                                .map(|f| f.id.as_str())
7396                                .collect::<Vec<_>>()
7397                                .join(", "),
7398                        ),
7399                    );
7400                    // A follow-up reviews the predecessor's work, not a new
7401                    // task instruction. Preserve its authored generation even
7402                    // if the queue instruction has since been edited.
7403                    if let Some(id) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) {
7404                        let authored = crate::queue::Queue::open()
7405                            .get(id)
7406                            .ok()
7407                            .filter(|task| {
7408                                crate::daemon::compatible_run_instruction(&self.state, task)
7409                            })
7410                            .map(|task| task.instruction);
7411                        follow_up.state.task_instruction = authored
7412                            .or_else(|| self.state.task_instruction.clone())
7413                            .or_else(|| Some(self.state.instruction.clone()));
7414                        follow_up.state.task_instruction_rev =
7415                            Some(self.state.task_instruction_rev.unwrap_or(0));
7416                    }
7417                    follow_up.state.save()?;
7418                    let follow_up_id = follow_up.state.id.clone();
7419                    // The follow-up is a run like any other: it belongs to the
7420                    // task of the run it follows, or to one filed for it.
7421                    let adopted = match crate::direct::adopt(
7422                        &follow_up.state,
7423                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7424                    ) {
7425                        Ok(a) => a,
7426                        Err(e) => {
7427                            // An ownerless run must not spend agent calls; it
7428                            // stays saved, and `magi run --resume` adopts it.
7429                            self.state.event(
7430                                "fix",
7431                                format!(
7432                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7433                                ),
7434                            );
7435                            save_follow_up(&mut self.state)?;
7436                            return Ok(());
7437                        }
7438                    };
7439                    let executed = follow_up.execute().await;
7440                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7441                    if let Some(a) = adopted {
7442                        a.finish(&follow_up.state, executed);
7443                    }
7444                    if let Some(e) = failure {
7445                        self.state.event(
7446                            "fix",
7447                            format!(
7448                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7449                            ),
7450                        );
7451                    }
7452                    self.state.operator_fixes[request_index].follow_up_review_run =
7453                        Some(follow_up_id);
7454                }
7455                Err(e) => {
7456                    self.state.event(
7457                        "fix",
7458                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7459                    );
7460                }
7461            }
7462            save_follow_up(&mut self.state)?;
7463        }
7464
7465        Ok(())
7466    }
7467
7468    // --------------------------------------------------------------- review
7469
7470    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7471    /// names, in order, each at most once, moving on only when the call
7472    /// advances (an error, a quota hit or nothing usable - the same decision
7473    /// point `agent::chain_advances` is for the other chained roles).
7474    ///
7475    /// Each agent gets its own seat from `Runner::seat`: the same agent
7476    /// continues its conversation (the winner's own implementer seat when it
7477    /// is the winner's author, now that the competition is over), another
7478    /// takes a fresh one so the full prompt is sent again. A handover is
7479    /// recorded under `node`, which is what makes the fallback stick for the
7480    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7481    /// is returned, so an exhausted chain reads exactly like a single failed
7482    /// fixer: one quota loss, the same wording, the same refund. An earlier
7483    /// attempt's edits are left in the tree and judged, with the final
7484    /// attempt's, by what git says afterwards.
7485    ///
7486    /// Returns the job that produced the outcome, for `continue_fix_report`.
7487    async fn ask_fixer(
7488        &mut self,
7489        winner: &Candidate,
7490        node: &'static str,
7491        round: Option<usize>,
7492        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7493    ) -> (SeatJob, SeatState, AgentOutcome) {
7494        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7495        self.ask_fixer_among(attempts, node, round, None, build)
7496            .await
7497    }
7498
7499    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7500    /// worktree and a commit: before the next agent is asked after one that
7501    /// did not satisfy the call, the worktree is put back on that commit, so
7502    /// a failed agent's partial edits are not carried into the next one.
7503    async fn ask_fixer_among(
7504        &mut self,
7505        attempts: Vec<(AgentSpec, String)>,
7506        node: &'static str,
7507        round: Option<usize>,
7508        restore: Option<(&Path, &str)>,
7509        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7510    ) -> (SeatJob, SeatState, AgentOutcome) {
7511        let run_id = self.state.id.clone();
7512        let prompts = self.state.config.prompts.clone();
7513        let cache = self.state.config.cache_dir();
7514        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7515        let mut last = None;
7516        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7517            let seat = self.seat(&key, &spec.id);
7518            let mut job = build(spec.clone(), seat);
7519            if i > 0 {
7520                job.stem = format!("{}-{}", job.stem, spec.id);
7521            }
7522            let ctx = WaveCtx {
7523                carry_seats: false,
7524                pauses: Some((&self.pause, &self.interrupt)),
7525                run: &run_id,
7526                node,
7527                prompts: &prompts,
7528                cache: cache.as_deref(),
7529                round,
7530            };
7531            let (seat, out) =
7532                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7533            // A resource block never advances the chain: the chosen agent
7534            // was not asked, so it must be the one asked again on resume.
7535            let advances = match &out {
7536                AgentOutcome::Ok(o) => agent::output_advances(o),
7537                AgentOutcome::ResourceBlocked(_) => false,
7538                _ => true,
7539            };
7540            if let Some(next) = ids.get(i + 1)
7541                && advances
7542            {
7543                self.state.seats.insert(seat.key.clone(), seat.clone());
7544                let class =
7545                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7546                let reason = match &out {
7547                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7548                    other => fail_reason(other),
7549                };
7550                // A failed agent's edits must not reach the next one, and a
7551                // restore that did not work ends the chain: the call fails
7552                // and the caller's own (confirmed) restore decides.
7553                if let Some((wt, rev)) = restore
7554                    && let Err(e) = self.graft_restore(wt, rev).await
7555                {
7556                    let why =
7557                        format!("could not restore the worktree before the next fixer: {e:#}");
7558                    tracing::warn!("{why}");
7559                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7560                        AgentOutcome::ResourceBlocked(why)
7561                    } else {
7562                        AgentOutcome::Failed(why)
7563                    };
7564                    last = Some((job, seat, out));
7565                    break;
7566                }
7567                record_handover(
7568                    &mut self.state,
7569                    node,
7570                    &seat.key,
7571                    &spec.id,
7572                    next,
7573                    &class,
7574                    &reason,
7575                );
7576                continue;
7577            }
7578            last = Some((job, seat, out));
7579            break;
7580        }
7581        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7582        if let AgentOutcome::Quota(output) = &out
7583            && node != "graft"
7584        {
7585            // Graft is best effort: its caller records the loss and restores
7586            // the pre-graft tree, then proceeds to review and gate.
7587            // Every fallback was tried. Machine outages cannot be repaired by
7588            // spending a fix round; use each caller's resumable resource path.
7589            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7590            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7591            self.state.quota.push(loss);
7592            self.state.seats.insert(seat.key.clone(), seat.clone());
7593            self.state.status = RunStatus::Blocked;
7594            return (
7595                job,
7596                seat,
7597                AgentOutcome::ResourceBlocked(
7598                    "fixer unavailable; restore agent availability and resume".into(),
7599                ),
7600            );
7601        }
7602        (job, seat, out)
7603    }
7604
7605    /// The one repair a verification-only failure earns (see
7606    /// [`crate::recovery`]), before the first review round of a run that took
7607    /// a branch over.
7608    ///
7609    /// Saved as started *before* the fixer is called, so a resume never
7610    /// repairs twice; a start found on re-entry is rolled back to the commit
7611    /// it began from. A failed or unusable fixer leaves the tree as it was and
7612    /// the review goes on over it, so the first round's own verification
7613    /// reports the failure again. The failure is never carried into a round as
7614    /// a result: verification is re-run on whatever commit this leaves.
7615    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7616        use crate::recovery::{Mode, Repair};
7617        if !self.state.reviews.is_empty() {
7618            return Ok(());
7619        }
7620        let Some(mut rec) = self.state.recovery.clone() else {
7621            return Ok(());
7622        };
7623        if rec.mode != Mode::VerifyRepair {
7624            return Ok(());
7625        }
7626        let wt = winner.worktree.clone();
7627        let mut head = git::rev_parse(&wt, "HEAD").await?;
7628        match rec.repair.clone() {
7629            Repair::Done { .. } => return Ok(()),
7630            Repair::WaitingForRestore { before } => {
7631                self.graft_restore(&wt, &before).await?;
7632                head = before;
7633                rec.repair = Repair::NotStarted;
7634                self.state.recovery = Some(rec.clone());
7635                self.state.save()?;
7636            }
7637            Repair::Started { before } => {
7638                // Interrupted: the unfinished edits are not trusted.
7639                // An unconfirmed rollback blocks the run with `Started` kept,
7640                // so a resume retries it; the tree is never reviewed as is.
7641                if let Err(e) = self.graft_restore(&wt, &before).await {
7642                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7643                        return Err(e);
7644                    }
7645                    return self
7646                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7647                        .await;
7648                }
7649                rec.repair = Repair::Done {
7650                    before: before.clone(),
7651                    after: before,
7652                    committed: false,
7653                    failed: Some("interrupted; rolled back".to_owned()),
7654                };
7655                self.state
7656                    .event("recovery", "the repair was interrupted and rolled back");
7657                self.state.recovery = Some(rec);
7658                self.state.save()?;
7659                return Ok(());
7660            }
7661            Repair::NotStarted => {}
7662        }
7663        if crate::recovery::recheck(&mut rec, &head) {
7664            self.state.event("recovery", rec.summary());
7665            self.state.recovery = Some(rec);
7666            self.state.save()?;
7667            return Ok(());
7668        }
7669        rec.repair = Repair::Started {
7670            before: head.clone(),
7671        };
7672        self.state.recovery = Some(rec.clone());
7673        self.state.save()?;
7674
7675        let language = self.state.config.graph.language.clone();
7676        let sessions = self.state.config.graph.sessions;
7677        let artifacts = agent::artifacts_dir(&self.state.dir());
7678        let fix_prompt = prompt::recovery_fix(
7679            &self.state.instruction,
7680            &rec,
7681            self.state.config.graph.review_rounds,
7682            &language,
7683        );
7684        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7685        self.state.event(
7686            "recovery",
7687            format!(
7688                "repair: the fixer starts from the failed verification on {}",
7689                short(&head)
7690            ),
7691        );
7692        let (_job, seat, out) = self
7693            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7694                prompt: fix_prompt.clone(),
7695                spec,
7696                seat,
7697                cwd: wt.clone(),
7698                timeout,
7699                allow_write: true,
7700                sessions,
7701                artifacts: artifacts.clone(),
7702                stem: "fix-recovery".to_owned(),
7703                handover: None,
7704            })
7705            .await;
7706        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7707            rec.repair = Repair::WaitingForRestore { before: head };
7708            self.state.recovery = Some(rec);
7709            return self.stop_for_resource();
7710        }
7711        let failed = match &out {
7712            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7713            AgentOutcome::Quota(o) => {
7714                self.state.quota.push(QuotaLoss::from_report(
7715                    seat.key.clone(),
7716                    "fix",
7717                    o.quota.as_ref(),
7718                ));
7719                Some("rate limited (quota); the fixer could not run".to_owned())
7720            }
7721            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7722            AgentOutcome::Failed(e) => Some(e.clone()),
7723        };
7724        self.state.seats.insert(seat.key.clone(), seat);
7725        let coordination = self.coordinate(&wt).await?;
7726        let failed = match failed {
7727            // The agent's partial edits are not kept.
7728            Some(why) => {
7729                if let Err(e) = git::restore_to(&wt, &head).await {
7730                    return self
7731                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7732                        .await;
7733                }
7734                Some(why)
7735            }
7736            None => {
7737                if let Ok(r) = git::rescue_commit(
7738                    &wt,
7739                    "magi: recovery repair of the failed verification (uncommitted work)",
7740                )
7741                .await
7742                {
7743                    self.state.note_withheld("fix", &r.withheld);
7744                }
7745                None
7746            }
7747        };
7748        let after = git::rev_parse(&wt, "HEAD").await?;
7749        drop(coordination);
7750        self.state.event(
7751            "recovery",
7752            match &failed {
7753                Some(why) => format!("repair: nothing kept ({why})"),
7754                None if after != head => {
7755                    format!("repair: committed {}", short(&after))
7756                }
7757                None => "repair: the fixer made no commit".to_owned(),
7758            },
7759        );
7760        rec.repair = Repair::Done {
7761            before: head.clone(),
7762            committed: after != head,
7763            after,
7764            failed,
7765        };
7766        self.state.recovery = Some(rec);
7767        self.state.save()?;
7768        Ok(())
7769    }
7770
7771    /// A repair whose rollback could not be confirmed: the run is blocked and
7772    /// resumable, and the unconfirmed state is never reviewed.
7773    async fn stop_recovery(
7774        &mut self,
7775        mut rec: crate::recovery::RecoveryRecord,
7776        head: &str,
7777        why: String,
7778    ) -> Result<()> {
7779        // `Started` stays recorded: a resume retries the restore.
7780        rec.repair = crate::recovery::Repair::Started {
7781            before: head.to_owned(),
7782        };
7783        self.state.recovery = Some(rec);
7784        self.state
7785            .event("recovery", format!("repair could not be undone: {why}"));
7786        self.state.status = RunStatus::Blocked;
7787        self.state.save()?;
7788        bail!("recovery repair could not be rolled back: {why}")
7789    }
7790
7791    async fn review_loop(&mut self) -> Result<()> {
7792        if self.hold_base_sync().await? {
7793            return Ok(());
7794        }
7795        loop {
7796            if self
7797                .state
7798                .base_sync
7799                .as_ref()
7800                .is_some_and(|s| s.conflict.is_some())
7801            {
7802                return Ok(());
7803            }
7804            if self.catchup_repairable() {
7805                let record = self.state.reviews.last().expect("repairable round").clone();
7806                let winner = self
7807                    .state
7808                    .winner()
7809                    .cloned()
7810                    .context("catch-up repair has no winner")?;
7811                if !self.fix_review_round(&winner, record).await? {
7812                    return Ok(());
7813                }
7814            }
7815            self.review_loop_pass().await?;
7816            if !self.catchup_repairable() {
7817                return Ok(());
7818            }
7819        }
7820    }
7821
7822    /// Derive an owed catch-up repair from durable round evidence, including
7823    /// reentry after a crash before the fixer was dispatched.
7824    fn catchup_repairable(&self) -> bool {
7825        self.state.reviews.len() < self.state.config.graph.review_rounds
7826            && self.state.reviews.last().is_some_and(|r| {
7827                !r.clean
7828                    && r.blocking == 0
7829                    && r.fix.is_none()
7830                    && r.e2e_status() == E2eStatus::Failed
7831            })
7832    }
7833
7834    async fn review_loop_pass(&mut self) -> Result<()> {
7835        // A base that would not rebase is a person's decision, not a review
7836        // round: nothing here would change the answer, and reviewers and a
7837        // fixer would be spending real budget on a tree that cannot land
7838        // regardless of what they find.
7839        if self
7840            .state
7841            .base_sync
7842            .as_ref()
7843            .is_some_and(|s| s.conflict.is_some())
7844        {
7845            return Ok(());
7846        }
7847        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7848        // agent files with `magi task add` name the run that paid for it. The
7849        // prompt overlay is cloned alongside it because the waves borrow it
7850        // while `self` is mutably borrowed by the node's own bookkeeping.
7851        let run_id = self.state.id.clone();
7852        let prompts = self.state.config.prompts.clone();
7853        let Some(winner) = self.state.winner().cloned() else {
7854            return Ok(());
7855        };
7856        let granted_review = self
7857            .state
7858            .repair_grants
7859            .last()
7860            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7861            .cloned();
7862        let fresh_review = granted_review
7863            .as_ref()
7864            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7865        let max_rounds = granted_review
7866            .as_ref()
7867            .map_or(self.state.config.graph.review_rounds, |g| {
7868                g.review_start.saturating_add(1)
7869            });
7870        // A clean round, an exhausted round budget, or a stalled tree (see
7871        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7872        // they are recorded — recomputed here, not read off `status`, so a
7873        // reentry into a run that already stopped restates the identical
7874        // verdict instead of silently handing back whatever an earlier node
7875        // in this same walk clobbered `status` to (a solo-candidate
7876        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7877        // below runs an empty range once the budget is spent, and would
7878        // otherwise fall through without touching `status` at all.
7879        if let Some(status) =
7880            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7881        {
7882            // A reentry after a crash between the last round's save and
7883            // `stop_reviewing` reaches the hand-off here, not there.
7884            if status == RunStatus::Gating {
7885                self.record_contested_handoff();
7886            }
7887            self.state.status = status;
7888            self.state.save()?;
7889            return Ok(());
7890        }
7891        self.state.status = RunStatus::Reviewing;
7892        // A last recorded round whose own verification never resolved
7893        // (`ResourceBlocked` — the shared build cache, not the patch) is
7894        // never a concluded round, whatever the round budget says: starting
7895        // a fresh round on top of it would spend a whole new reviewer wave
7896        // re-reading an unchanged patch instead of just retrying the one
7897        // check that actually needs it, and once the budget is spent the
7898        // loop below has nothing left to do at all (its range is empty).
7899        // Retry that check directly instead, exactly the same retry
7900        // `stop_reviewing` already does for its own catch-up case.
7901        if !fresh_review
7902            && self.state.reviews.last().is_some_and(|r| {
7903                r.e2e_status() == E2eStatus::ResourceBlocked
7904                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7905            })
7906        {
7907            let shell = self.state.config.shell();
7908            return self
7909                .stop_unresolved_review(
7910                    "the last round's own verification never resolved",
7911                    &shell,
7912                    &winner.worktree,
7913                )
7914                .await;
7915        }
7916
7917        if granted_review.is_none() {
7918            self.recovery_repair(&winner).await?;
7919        }
7920        if self.resource_halt()? {
7921            return Ok(());
7922        }
7923
7924        let repo = self.state.repo.clone();
7925        let root = self.state.worktree_root();
7926        let language = self.state.config.graph.language.clone();
7927        let sessions = self.state.config.graph.sessions;
7928        let artifacts = self.merge_repair_artifacts();
7929        let base = self.landing_base();
7930        let base_short = short(&base);
7931        let reviewers = self.roles.reviewers.clone();
7932        let shell = self.state.config.shell();
7933
7934        for round in (self.state.reviews.len() + 1)..=max_rounds {
7935            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7936            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7937            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7938            // The prior round's own record, already persisted — never a
7939            // hand-carried variable of just its failing output: that is
7940            // exactly what let a round's e2e result drift out of sync with
7941            // which commit it was actually about (see `SCHEMA`'s doc for
7942            // schema 8). Judged against `head`, the commit reviewers are
7943            // about to look at now, so the summary always reads as "an
7944            // earlier head" here — this round's own patch has not been
7945            // checked yet.
7946            let prev_verification = self
7947                .state
7948                .reviews
7949                .last()
7950                .and_then(|r| r.verification_summary(&head));
7951            // Only the first round of a run that took a branch over: later
7952            // rounds have this run's own history.
7953            let prior_section = match (&self.state.recovery, round) {
7954                (Some(rec), 1) if self.state.reviews.is_empty() => {
7955                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7956                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7957                            Some(crate::recovery::head_of(
7958                                &git::diff(&winner.worktree, reviewed, "HEAD")
7959                                    .await
7960                                    .unwrap_or_default(),
7961                                crate::recovery::SINCE_DIFF_MAX,
7962                            ))
7963                        }
7964                        _ => None,
7965                    };
7966                    Some(prompt::recovery_review(rec, since.as_deref()))
7967                }
7968                _ => None,
7969            };
7970
7971            // Each reviewer gets its own detached checkout of exactly this
7972            // commit: nobody can perturb the winner's tree, and the fixer can
7973            // keep working without racing a reviewer.
7974            let mut jobs = Vec::new();
7975            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7976                self.coordinate(&repo).await?
7977            } else {
7978                None
7979            };
7980            for (r, spec) in reviewers.iter().cloned().enumerate() {
7981                let wt = root.join(format!("review-{}", r + 1));
7982                // `clean -fdx` in a reset wipes setup's products, so every
7983                // round sets the seat up again.
7984                if wt.exists() {
7985                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7986                } else {
7987                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7988                        None
7989                    } else {
7990                        self.coordinate(&repo).await?
7991                    };
7992                    git::worktree_add_detached(&repo, &wt, &head).await?;
7993                }
7994                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7995                    None
7996                } else {
7997                    self.coordinate(&repo).await?
7998                };
7999                self.setup_seat_worktree(
8000                    &repo,
8001                    &wt,
8002                    false,
8003                    coordination.as_ref().or(_setup_lease.as_ref()),
8004                )
8005                .await?;
8006                let seat_key = format!("review-{}", r + 1);
8007                // The seat starts the round on whoever answered it last, not
8008                // on the agent the spec names, so a failure is not re-paid.
8009                let spec = pick_start_spec(
8010                    &self.roles.reviewer_roster,
8011                    spec,
8012                    self.state.seat_history.get(&seat_key),
8013                );
8014                let seat = self.seat(&seat_key, &spec.id);
8015                jobs.push(SeatJob {
8016                    prompt: prompt::review(&prompt::ReviewCtx {
8017                        instruction: &self.state.instruction,
8018                        branch: &winner.branch,
8019                        base_short: &base_short,
8020                        stat: &stat,
8021                        patch: &patch,
8022                        verification: prev_verification.as_ref(),
8023                        prior: prior_section.as_deref(),
8024                        reviewers: reviewers.len(),
8025                        round,
8026                        rounds: max_rounds,
8027                        // A review-only run has no rankings, so nothing
8028                        // competed for this patch and the reviewer is told so.
8029                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
8030                        lens: Lens::for_seat(r),
8031                        language: &language,
8032                        github_language: &self.state.config.graph.github_language,
8033                    }),
8034                    spec,
8035                    seat,
8036                    cwd: wt,
8037                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8038                    allow_write: false,
8039                    sessions,
8040                    artifacts: artifacts.clone(),
8041                    stem: format!("review-{round}-{}", r + 1),
8042                    handover: None,
8043                });
8044            }
8045
8046            drop(coordination);
8047            self.state.event(
8048                "review",
8049                format!(
8050                    "round {round}: {} reviewers on {}",
8051                    jobs.len(),
8052                    short(&head)
8053                ),
8054            );
8055            let mut quota_losses = Vec::new();
8056            let review_retries = self.state.config.graph.retries;
8057            let review_cache = self.state.config.cache_dir();
8058            let ctx = WaveCtx {
8059                carry_seats: true,
8060                pauses: Some((&self.pause, &self.interrupt)),
8061                run: &run_id,
8062                node: "review",
8063                prompts: &prompts,
8064                cache: review_cache.as_deref(),
8065                round: Some(round),
8066            };
8067            let results = ask_json_wave::<Review>(
8068                jobs,
8069                Arc::clone(&self.sem),
8070                review_retries,
8071                &self.roles.reviewer_roster,
8072                &ctx,
8073                &mut quota_losses,
8074                &mut self.state,
8075                &|_: &Review| Ok(()),
8076            )
8077            .await;
8078            if self.state.resource_block.is_some() {
8079                return self.stop_for_resource();
8080            }
8081            // Counted before the move below: how many of *this* round's
8082            // reviewer seats were lost to their own rate limit, as opposed to
8083            // a crash, a timeout, or unparsable output — see `round_is_clean`.
8084            let round_quota_missing = quota_losses.len();
8085            self.state.quota.extend(quota_losses);
8086
8087            let mut records = Vec::new();
8088            let mut all_findings = Vec::new();
8089            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
8090                let agent_id = seat.agent.clone();
8091                self.state.seats.insert(seat.key.clone(), seat);
8092                let mut record = ReviewRecord {
8093                    reviewer: r + 1,
8094                    agent: agent_id,
8095                    summary: String::new(),
8096                    findings: Vec::new(),
8097                    vote: None,
8098                    failed: None,
8099                    duration_ms: 0,
8100                    // Set for both outcomes: `failed: Some(_)` with
8101                    // `attempts > 0` is a seat every retry still lost, not a
8102                    // recovered one — only `failed: None` with `attempts > 0`
8103                    // reads as "answered after a nudge" (see this field's own
8104                    // doc).
8105                    attempts,
8106                };
8107                match res {
8108                    Ok((review, out)) => {
8109                        // Sanitized here, at the point every other piece of
8110                        // agent prose in this file is (candidate summaries,
8111                        // deliberation turns, vote reasons): a reviewer's own
8112                        // words are the one thing about it that could name
8113                        // it, and reconsideration below broadcasts this same
8114                        // summary and these same findings to every other
8115                        // seat on the panel.
8116                        record.summary =
8117                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
8118                        record.vote = Some(review.vote);
8119                        record.duration_ms = out.duration_ms;
8120                        for (n, mut f) in review.findings.into_iter().enumerate() {
8121                            // ids are magi's, never the agent's: the fixer's
8122                            // adoption report is keyed by them.
8123                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
8124                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
8125                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
8126                            // `file` is agent-supplied prose too, never
8127                            // checked against the real tree — the same
8128                            // exposure `title`/`detail` above have, just in
8129                            // a field easy to forget because it looks like a
8130                            // path rather than free text.
8131                            f.file = f
8132                                .file
8133                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
8134                            all_findings.push(f.clone());
8135                            record.findings.push(f);
8136                        }
8137                        self.state.event(
8138                            "review",
8139                            format!(
8140                                "round {round}: reviewer {} voted {} with {} finding(s)",
8141                                r + 1,
8142                                review.vote.label(),
8143                                record.findings.len()
8144                            ),
8145                        );
8146                    }
8147                    Err(e) => {
8148                        record.failed = Some(e.to_string());
8149                        self.state.event(
8150                            "review",
8151                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
8152                        );
8153                    }
8154                }
8155                records.push(record);
8156            }
8157
8158            // Tally the round's votes and, if they split, spend the one
8159            // round of reconsideration the split -> deliberate -> revote
8160            // shape `judge`/`vote` use for the panel, sized down to what a
8161            // read-only review round can afford: one round, and a revote
8162            // rather than an argument, because the panel already wrote its
8163            // reasoning down as findings the first time around.
8164            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
8165            let vote_split =
8166                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
8167            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
8168            if vote_split {
8169                self.state.event(
8170                    "review",
8171                    format!(
8172                        "round {round}: votes split ({}) — one round of reconsideration",
8173                        initial_votes
8174                            .iter()
8175                            .map(|v| v.label())
8176                            .collect::<Vec<_>>()
8177                            .join(", ")
8178                    ),
8179                );
8180                // Seats read every seat's findings and votes, still numbered
8181                // and never named — the same anonymity `review` itself keeps.
8182                let panel: Vec<ReviewSeatReport<'_>> = records
8183                    .iter()
8184                    .filter_map(|r| {
8185                        r.vote.map(|vote| ReviewSeatReport {
8186                            reviewer: r.reviewer,
8187                            vote,
8188                            summary: &r.summary,
8189                            findings: &r.findings,
8190                        })
8191                    })
8192                    .collect();
8193
8194                let mut jobs = Vec::new();
8195                let mut seats_at = Vec::new();
8196                for (r, spec) in reviewers.iter().cloned().enumerate() {
8197                    // A seat with no initial vote has nothing to reconsider
8198                    // from and stays absent, the same as it stayed absent
8199                    // from `panel` above.
8200                    if records[r].vote.is_none() {
8201                        continue;
8202                    }
8203                    let wt = root.join(format!("review-{}", r + 1));
8204                    let seat_key = format!("review-{}", r + 1);
8205                    let spec = self.occupant(&seat_key, spec);
8206                    let seat = self.seat(&seat_key, &spec.id);
8207                    // A seat with no live session has already forgotten the
8208                    // initial review's prompt — restate the patch it is
8209                    // voting on, the same as `deliberate`/`vote` do for a
8210                    // judge in the same position.
8211                    // The panel already carries this seat's own review and
8212                    // vote, so restating the patch makes the prompt whole for
8213                    // a seat handed to another agent.
8214                    let build = |with_patch: bool| {
8215                        prompt::review_reconsider(&ReviewReconsiderCtx {
8216                            instruction: &self.state.instruction,
8217                            reviewer: r + 1,
8218                            lens: Lens::for_seat(r),
8219                            panel: &panel,
8220                            patch: with_patch.then_some(ReviewPatch {
8221                                branch: &winner.branch,
8222                                base_short: &base_short,
8223                                stat: &stat,
8224                                patch: &patch,
8225                            }),
8226                            round,
8227                            rounds: max_rounds,
8228                            language: &language,
8229                        })
8230                    };
8231                    let full = build(true);
8232                    let prompt = if has_context(&spec, &seat, sessions) {
8233                        build(false)
8234                    } else {
8235                        full.clone()
8236                    };
8237                    jobs.push(SeatJob {
8238                        prompt,
8239                        spec,
8240                        seat,
8241                        cwd: wt,
8242                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8243                        allow_write: false,
8244                        sessions,
8245                        artifacts: artifacts.clone(),
8246                        stem: format!("review-{round}-reconsider-{}", r + 1),
8247                        handover: Some(full),
8248                    });
8249                    seats_at.push(r);
8250                }
8251
8252                let mut recon_quota_losses = Vec::new();
8253                let recon_cache = self.state.config.cache_dir();
8254                let recon_ctx = WaveCtx {
8255                    carry_seats: true,
8256                    pauses: Some((&self.pause, &self.interrupt)),
8257                    run: &run_id,
8258                    node: "review",
8259                    prompts: &prompts,
8260                    cache: recon_cache.as_deref(),
8261                    round: Some(round),
8262                };
8263                let recon_results = ask_json_wave::<ReviewRevote>(
8264                    jobs,
8265                    Arc::clone(&self.sem),
8266                    review_retries,
8267                    &self.roles.reviewer_roster,
8268                    &recon_ctx,
8269                    &mut recon_quota_losses,
8270                    &mut self.state,
8271                    &|_: &ReviewRevote| Ok(()),
8272                )
8273                .await;
8274                if self.state.resource_block.is_some() {
8275                    return self.stop_for_resource();
8276                }
8277                self.state.quota.extend(recon_quota_losses);
8278
8279                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8280                    let agent_id = seat.agent.clone();
8281                    self.state.seats.insert(seat.key.clone(), seat);
8282                    let mut rec = ReviewRevoteRecord {
8283                        reviewer: r + 1,
8284                        agent: agent_id,
8285                        vote: None,
8286                        reason: String::new(),
8287                        failed: None,
8288                    };
8289                    match res {
8290                        Ok((rv, _)) => {
8291                            rec.vote = Some(rv.vote);
8292                            rec.reason =
8293                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8294                            self.state.event(
8295                                "review",
8296                                format!(
8297                                    "round {round}: reviewer {} revoted {}",
8298                                    r + 1,
8299                                    rv.vote.label()
8300                                ),
8301                            );
8302                        }
8303                        Err(e) => {
8304                            rec.failed = Some(e.to_string());
8305                            self.state.event(
8306                                "review",
8307                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8308                            );
8309                        }
8310                    }
8311                    reconsideration.push(rec);
8312                }
8313            } else if initial_votes.len() > 1 {
8314                self.state.event(
8315                    "review",
8316                    format!(
8317                        "round {round}: votes agreed ({}) — no reconsideration",
8318                        initial_votes[0].label()
8319                    ),
8320                );
8321            }
8322
8323            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8324            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8325            // A round that already has a blocking finding and a round left to
8326            // try is going back to the fixer no matter what `verify.e2e`
8327            // says, so running it first only spends the loop's slowest step
8328            // (minutes, for a Rust repo's full test suite) on a head about
8329            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8330            // runs once a round has no blocking findings left (see
8331            // `round_is_clean`, which a deferred — empty — `e2e` can never
8332            // satisfy since `blocking` is nonzero whenever this branch is
8333            // taken), and `stop_reviewing` forces a real run before it will
8334            // ever read a deferred round as green.
8335            let defer_e2e =
8336                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8337            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8338                let reason =
8339                    format!("{blocking} blocking finding(s) already required a fix this round");
8340                self.state.event(
8341                    "verify",
8342                    format!(
8343                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8344                         {}); it will run once a round has none left",
8345                        short(&head)
8346                    ),
8347                );
8348                (Vec::new(), false, true, Some(reason))
8349            } else {
8350                let e2e_commands = self.state.config.verify.e2e.clone();
8351                let cache_dir = self.state.config.cache_dir();
8352                let context = format!("round {round}");
8353                let wait = self.repository_wait();
8354                let (e2e, verify_retried) = with_cache_lease(
8355                    &mut self.state,
8356                    cache_dir.as_deref(),
8357                    "e2e",
8358                    "e2e",
8359                    &winner.worktree,
8360                    &head,
8361                    verify_timeout,
8362                    &context,
8363                    &wait,
8364                    |state, budget| {
8365                        let shell = shell.clone();
8366                        let e2e_commands = e2e_commands.clone();
8367                        let worktree = winner.worktree.clone();
8368                        let context = context.clone();
8369                        let winner = winner.clone();
8370                        async move {
8371                            if !e2e_commands.is_empty() {
8372                                // The suite certifies one SHA. Format before it
8373                                // runs, or the commit `pre_gate` makes at the
8374                                // gate owes the whole suite again.
8375                                Self::run_pre_gate(state, &winner).await;
8376                            }
8377                            run_e2e_with_retry(
8378                                state,
8379                                &shell,
8380                                &e2e_commands,
8381                                &worktree,
8382                                budget,
8383                                &context,
8384                                Some(round),
8385                            )
8386                            .await
8387                        }
8388                    },
8389                )
8390                .await?;
8391                (e2e, verify_retried, false, None)
8392            };
8393
8394            let expected = records.len();
8395            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8396            let incomplete = answered < expected;
8397            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8398            let policy = self.state.config.graph.incomplete_review;
8399            let clean = round_is_clean(
8400                blocking,
8401                e2e_ok,
8402                answered,
8403                expected,
8404                round_quota_missing,
8405                policy,
8406            );
8407
8408            let mut round_record = ReviewRound {
8409                round,
8410                head: head.clone(),
8411                verified_head: None,
8412                verified_at: None,
8413                reviews: records,
8414                e2e,
8415                verify_retried,
8416                e2e_deferred,
8417                e2e_defer_reason,
8418                fix: None,
8419                blocking,
8420                answered,
8421                expected,
8422                clean,
8423                progressed: false,
8424                vote_split,
8425                reconsideration,
8426                verdict: None,
8427            };
8428            // The final vote per seat is its revote where reconsideration
8429            // ran and answered, its initial vote otherwise — the same
8430            // fallback `tally` uses for a judge whose private vote failed.
8431            round_record.verdict = ReviewVote::worst(
8432                round_record
8433                    .final_votes()
8434                    .into_iter()
8435                    .map(|(_, _, vote)| vote),
8436            );
8437            // Which commit and when magi actually attempted to check —
8438            // known the moment a command was dispatched against `head`,
8439            // whether or not it finished: a resource-blocked attempt still
8440            // targeted a specific commit at a specific time, and leaving
8441            // that unrecorded is exactly what made `verification_summary`
8442            // report a fresh attempt as "commit unknown ... recorded before
8443            // this was tracked", indistinguishable from a genuinely old,
8444            // untracked record. Only a deferred or unconfigured round never
8445            // ran at all and has nothing to record — see
8446            // `ReviewRound::verified_head`'s own doc.
8447            if !matches!(
8448                round_record.e2e_status(),
8449                E2eStatus::Deferred | E2eStatus::NotConfigured
8450            ) {
8451                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8452                // mechanical fixes before the commands ran.
8453                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8454                round_record.verified_at = Some(Timestamp::now());
8455            }
8456
8457            if incomplete {
8458                let missing: Vec<String> = round_record
8459                    .reviews
8460                    .iter()
8461                    .filter(|r| r.failed.is_some())
8462                    .map(|r| format!("review-{}", r.reviewer))
8463                    .collect();
8464                self.state.event(
8465                    "review",
8466                    format!(
8467                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8468                        missing.join(", ")
8469                    ),
8470                );
8471            }
8472
8473            if clean {
8474                self.state.event(
8475                    "review",
8476                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8477                        format!(
8478                            "round {round}: clean (warn policy, incomplete panel) — no \
8479                             blocking findings from the seats that answered, verification green"
8480                        )
8481                    } else if incomplete {
8482                        format!(
8483                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8484                             quorum) — no blocking findings from the seats that answered, \
8485                             verification green",
8486                            expected - answered
8487                        )
8488                    } else {
8489                        format!("round {round}: clean — no blocking findings, verification green")
8490                    },
8491                );
8492                self.state.reviews.push(round_record);
8493                self.state.status = RunStatus::Gating;
8494                self.state.save()?;
8495                return Ok(());
8496            }
8497
8498            // Nothing was raised and verification passed, but not every seat
8499            // answered and `round_is_clean` still refused to call it clean —
8500            // either a seat is missing for a reason other than its own quota
8501            // (a crash, a timeout, unparsable output — worth another try), or
8502            // every seat that could have answered lost its quota and nobody
8503            // is left to decide on: re-review rather than send the fixer
8504            // after a round with nothing to fix.
8505            if incomplete && blocking == 0 && e2e_ok {
8506                self.state.reviews.push(round_record);
8507                self.state.save()?;
8508                if round == max_rounds {
8509                    self.state.status = RunStatus::Blocked;
8510                    self.state.event(
8511                        "review",
8512                        format!(
8513                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8514                             refusing to call it clean",
8515                            expected - answered
8516                        ),
8517                    );
8518                    return Ok(());
8519                }
8520                continue;
8521            }
8522
8523            // Nothing for the fixer to act on (`blocking == 0`) and the only
8524            // reason this round is not clean is that magi itself never got
8525            // a command to run — the shared build cache, not the patch (see
8526            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8527            // the fixer would invite a change to appease contention that has
8528            // nothing to do with the diff, and would leave this attempt
8529            // sitting in the next round's prompt as if it were about an
8530            // earlier, superseded commit rather than what it actually is:
8531            // the same head, still waiting to be checked. Wait for it the
8532            // same way the final round's own contention is already handled,
8533            // whatever round this happens to be.
8534            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8535                self.state.reviews.push(round_record);
8536                return self
8537                    .stop_unresolved_review(
8538                        "the round's own verification could not run",
8539                        &shell,
8540                        &winner.worktree,
8541                    )
8542                    .await;
8543            }
8544
8545            if round == max_rounds {
8546                self.state.reviews.push(round_record);
8547                return self
8548                    .stop_reviewing(
8549                        &format!(
8550                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8551                        ),
8552                        &shell,
8553                        &winner.worktree,
8554                    )
8555                    .await;
8556            }
8557
8558            if !self.fix_review_round(&winner, round_record).await? {
8559                return Ok(());
8560            }
8561        }
8562        Ok(())
8563    }
8564
8565    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8566    /// False means admission or continuation policy stopped the review loop.
8567    async fn fix_review_round(
8568        &mut self,
8569        winner: &Candidate,
8570        mut round_record: ReviewRound,
8571    ) -> Result<bool> {
8572        let round = round_record.round;
8573        let shell = self.state.config.shell();
8574        let step = self.run_fix_round(winner, &mut round_record).await?;
8575        if matches!(step, FixStep::Resource) {
8576            self.stop_for_resource()?;
8577            return Ok(false);
8578        }
8579        if self.state.reviews.len() < round {
8580            self.state.reviews.push(round_record);
8581        } else {
8582            self.state.reviews[round - 1] = round_record;
8583        }
8584        self.state.save()?;
8585
8586        // The fixer's own report never came back this round, even after
8587        // `continue_fix_report`'s own budget was spent on it — not an
8588        // ordinary "no report" (dropped stream, quota, plain failure),
8589        // which already reads that way and is left to the existing round
8590        // budget. Stopping here, rather than opening another round, is
8591        // what keeps a next reviewer/fixer wave from ever being
8592        // dispatched onto `winner.worktree` while whatever the seat's
8593        // last call may still have running there is unaccounted for: no
8594        // process liveness check exists (and none is being added — see
8595        // AGENTS.md/this task's own scope), so the only way to honour
8596        // "nothing starts before a valid report returns" is to not start
8597        // anything further on this worktree from this run at all.
8598        if matches!(step, FixStep::Recorded { report_lost: true }) {
8599            self.stop_reviewing(
8600                "the fixer's adoption report never came back, even after resuming its \
8601                         own seat; refusing to start another round against the same worktree \
8602                         while that is unresolved",
8603                &shell,
8604                &winner.worktree,
8605            )
8606            .await?;
8607            return Ok(false);
8608        }
8609
8610        let streak = self
8611            .state
8612            .reviews
8613            .iter()
8614            .rev()
8615            .take_while(|r| !r.progressed)
8616            .count();
8617        if streak >= STAGNANT_LIMIT {
8618            self.stop_reviewing(
8619                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8620                &shell,
8621                &winner.worktree,
8622            )
8623            .await?;
8624            return Ok(false);
8625        }
8626        Ok(true)
8627    }
8628
8629    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8630    async fn run_fix_round(
8631        &mut self,
8632        winner: &Candidate,
8633        round_record: &mut ReviewRound,
8634    ) -> Result<FixStep> {
8635        let round = round_record.round;
8636        let max_rounds = self.state.config.graph.review_rounds;
8637        let run_id = self.state.id.clone();
8638        let prompts = self.state.config.prompts.clone();
8639        let language = self.state.config.graph.language.clone();
8640        let sessions = self.state.config.graph.sessions;
8641        let artifacts = self.merge_repair_artifacts();
8642        let base = self.landing_base();
8643        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8644        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8645        let this_round_verification = round_record.verification_summary(&head);
8646        let all_findings: Vec<_> = round_record
8647            .reviews
8648            .iter()
8649            .flat_map(|r| r.findings.iter().cloned())
8650            .collect();
8651        // Fix. The winner's own implementer seat continues its conversation:
8652        // the competition is over, so context is pure benefit now.
8653        let blocking_findings: Vec<_> = all_findings
8654            .iter()
8655            .filter(|f| f.severity.blocks())
8656            .cloned()
8657            .collect();
8658        let fix_prompt = prompt::fix_in(
8659            &self.state.instruction,
8660            &blocking_findings,
8661            this_round_verification.as_ref(),
8662            round,
8663            max_rounds,
8664            &language,
8665            &self.state.config.graph.github_language,
8666        );
8667        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8668        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8669        let (job, seat, out) = self
8670            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8671                prompt: fix_prompt.clone(),
8672                spec,
8673                seat,
8674                cwd: winner.worktree.clone(),
8675                timeout,
8676                allow_write: true,
8677                sessions,
8678                artifacts: artifacts.clone(),
8679                stem: format!("fix-{round}"),
8680                handover: None,
8681            })
8682            .await;
8683        // Not asked: the round is not recorded (so a resume repeats it),
8684        // no fixer was handed over to, and the seat is left as it was.
8685        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8686            return Ok(FixStep::Resource);
8687        }
8688        let agent_id = seat.agent.clone();
8689
8690        let mut fix = FixRecord {
8691            agent: agent_id,
8692            addressed: Vec::new(),
8693            rejected: Vec::new(),
8694            notes: String::new(),
8695            committed: false,
8696            failed: None,
8697            duration_ms: 0,
8698            continuation: None,
8699        };
8700        let mut continuation = ContinuationRecord::not_needed();
8701        let mut final_seat = seat.clone();
8702        match out {
8703            AgentOutcome::Ok(o) => {
8704                fix.duration_ms = o.duration_ms;
8705                let parsed = verdict::extract_json::<FixReport>(&o.text);
8706                // A parsed report standing next to a command this same
8707                // reply's own CLI never confirmed the exit status of is
8708                // not a resolved answer — the identical `CommandEvidence`
8709                // `state.jobs` renders, read here instead of only on
8710                // display, per the completion judgment and the shown
8711                // record needing to agree.
8712                let incomplete_reason = match &parsed {
8713                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8714                        "the reply parsed, but it reported a command whose own CLI never \
8715                             confirmed an exit status"
8716                            .to_owned(),
8717                    ),
8718                    Ok(_) => None,
8719                    Err(e) => Some(e.to_string()),
8720                };
8721                match incomplete_reason {
8722                    None => {
8723                        let report = parsed.expect("checked Ok above");
8724                        fix.addressed = report.addressed;
8725                        fix.rejected = report.rejected;
8726                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8727                    }
8728                    Some(reason) => {
8729                        let (resumed_seat, resolved, failure, cont) = self
8730                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8731                            .await;
8732                        fix.duration_ms += cont.cumulative_wait_ms;
8733                        continuation = cont;
8734                        final_seat = resumed_seat;
8735                        match resolved {
8736                            Some(report) => {
8737                                fix.addressed = report.addressed;
8738                                fix.rejected = report.rejected;
8739                                fix.notes =
8740                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8741                            }
8742                            None => fix.failed = failure,
8743                        }
8744                    }
8745                }
8746            }
8747            // The CLI's raw error JSON is not a fix report to parse.
8748            AgentOutcome::Dropped(o) => {
8749                fix.duration_ms = o.duration_ms;
8750                let why = o
8751                    .dropped
8752                    .as_ref()
8753                    .map(|d| d.why.as_str())
8754                    .unwrap_or("the CLI ended the stream without delivering its answer");
8755                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8756            }
8757            AgentOutcome::Quota(o) => {
8758                self.state.quota.push(QuotaLoss::from_report(
8759                    final_seat.key.clone(),
8760                    "fix",
8761                    o.quota.as_ref(),
8762                ));
8763                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8764            }
8765            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8766        }
8767        if self.state.resource_block.is_some() {
8768            self.state.seats.insert(final_seat.key.clone(), final_seat);
8769            return Ok(FixStep::Resource);
8770        }
8771        fix.continuation = Some(continuation);
8772        self.state.seats.insert(final_seat.key.clone(), final_seat);
8773        let coordination = self.coordinate(&winner.worktree).await?;
8774        if let Ok(r) = git::rescue_commit(
8775            &winner.worktree,
8776            &format!("magi: review round {round} fixes (uncommitted work)"),
8777        )
8778        .await
8779        {
8780            self.state.note_withheld("fix", &r.withheld);
8781        }
8782        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8783        fix.committed = after != before;
8784        // Judged by what `git` says moved against base, never by the
8785        // fixer's own `addressed`/`rejected` count — see
8786        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8787        // `patch` snapshot above: swallowing this error would default
8788        // `diff_after` to empty, which almost always differs from a
8789        // non-empty `patch` and reads as "progressed" — exactly backwards
8790        // for a `git` failure the stagnation check cannot see through.
8791        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8792        drop(coordination);
8793        let progressed = diff_after != patch;
8794        let commit_note = if fix.committed {
8795            "committed"
8796        } else {
8797            "NO new commit"
8798        };
8799        let tree_note = if progressed {
8800            "changed vs base"
8801        } else {
8802            "unchanged vs base"
8803        };
8804        self.state.event(
8805            "fix",
8806            match &fix.failed {
8807                // Distinct on purpose from "0 addressed, 0 rejected": the
8808                // fixer's own diff still landed (blocking counts do keep
8809                // falling round over round), only its adoption report did
8810                // not come back, so this must never read like every
8811                // finding was reviewed and declined.
8812                Some(reason) => {
8813                    format!(
8814                        "round {round}: fixer's adoption report was lost ({reason}); \
8815                             {commit_note}, tree {tree_note}"
8816                    )
8817                }
8818                None => format!(
8819                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8820                         {tree_note}{}",
8821                    fix.addressed.len(),
8822                    fix.rejected.len(),
8823                    if continuation.outcome == ContinuationOutcome::Resumed {
8824                        format!(
8825                            " (adoption report recovered after {} continuation(s))",
8826                            continuation.attempts
8827                        )
8828                    } else {
8829                        String::new()
8830                    },
8831                ),
8832            },
8833        );
8834        round_record.fix = Some(fix);
8835        round_record.progressed = progressed;
8836        Ok(FixStep::Recorded {
8837            report_lost: matches!(
8838                continuation.outcome,
8839                ContinuationOutcome::Exhausted
8840                    | ContinuationOutcome::QuotaLost
8841                    | ContinuationOutcome::NoSession
8842            ),
8843        })
8844    }
8845
8846    /// Decide, from the last recorded round's own verification, whether
8847    /// stopping the review loop is a hand-off or a genuine block.
8848    ///
8849    /// Called once the loop has given up trying — the round budget is spent,
8850    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8851    /// findings still open, never while a round is still clean or the
8852    /// incomplete-panel case handled inline above. Gate and e2e are facts
8853    /// about the tree; a lingering review finding is an opinion, and this
8854    /// workload's own `magi stats` puts reviewer precision low enough
8855    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8856    /// must not by itself stand between a green, verified change and the
8857    /// human who decides what to do with it. A red e2e is not an opinion, so
8858    /// that case still blocks, with the failing command and a tail of its
8859    /// output recorded here rather than left in `run.json` for someone to go
8860    /// find.
8861    ///
8862    /// A round that deferred its own e2e (see [`Config::graph`]'s
8863    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8864    /// only because nothing ran, and treating an empty list as a passing one
8865    /// here is exactly the "deferred painted green" bug this function exists
8866    /// to not have. When the last round's own verification never resolved —
8867    /// deferred on purpose, or a real attempt the shared build cache blocked
8868    /// — this makes (or retries) the real run, on the actual worktree this
8869    /// loop is about to stop touching, before deciding anything. A
8870    /// resource-blocked attempt is likewise never read as either green or
8871    /// red: it is evidence about the machine, not the patch (see
8872    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8873    /// blocked cache leaves this call without deciding rather than guessing
8874    /// — the caller retries on a later reentry.
8875    /// Record, once, that the review loop handed off over a blocking finding
8876    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8877    /// `land` asks the owner even with `land_approval` off. Called from every
8878    /// path that concludes `Gating`; a reentry keeps the first record.
8879    fn record_contested_handoff(&mut self) {
8880        if self.state.contested_handoff.is_some() {
8881            return;
8882        }
8883        let Some(contested) = self
8884            .state
8885            .reviews
8886            .last()
8887            .and_then(ReviewRound::contested_handoff)
8888        else {
8889            return;
8890        };
8891        self.state.event(
8892            "review",
8893            format!(
8894                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8895                 wait for the owner's approval",
8896                contested.findings.len(),
8897                contested.rejecters.len()
8898            ),
8899        );
8900        self.state.contested_handoff = Some(contested);
8901    }
8902
8903    async fn stop_unresolved_review(
8904        &mut self,
8905        why: &str,
8906        shell: &[String],
8907        worktree: &Path,
8908    ) -> Result<()> {
8909        self.stop_reviewing_inner(why, shell, worktree, true).await
8910    }
8911
8912    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8913        self.stop_reviewing_inner(why, shell, worktree, false).await
8914    }
8915
8916    async fn stop_reviewing_inner(
8917        &mut self,
8918        why: &str,
8919        shell: &[String],
8920        worktree: &Path,
8921        repairable: bool,
8922    ) -> Result<()> {
8923        let round_idx = self.state.reviews.len() - 1;
8924        // A deferred round and a resource-blocked one are the same shape
8925        // here: neither has a real result yet, and both get one more
8926        // attempt. Read off `e2e_status` — the single source for this —
8927        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8928        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8929        // still retries instead of being read as a settled result the
8930        // instant it stops being empty.
8931        let needs_catchup_run = matches!(
8932            self.state.reviews[round_idx].e2e_status(),
8933            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8934        );
8935        if needs_catchup_run {
8936            let round = self.state.reviews[round_idx].round;
8937            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8938            let commands = self.state.config.verify.e2e.clone();
8939            let before_head = git::rev_parse(worktree, "HEAD").await?;
8940            let winner = self.state.winner().cloned();
8941            let cache_dir = self.state.config.cache_dir();
8942            let context = format!(
8943                "round {round}: verification unresolved, catching up before the final decision"
8944            );
8945            let wait = self.repository_wait();
8946            let (outcomes, verify_retried) = with_cache_lease(
8947                &mut self.state,
8948                cache_dir.as_deref(),
8949                "e2e",
8950                "e2e",
8951                worktree,
8952                &before_head,
8953                timeout,
8954                &context,
8955                &wait,
8956                |state, budget| {
8957                    let shell = shell.to_vec();
8958                    let commands = commands.clone();
8959                    let context = context.clone();
8960                    async move {
8961                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8962                            // Same reason as in the round itself: format before
8963                            // the suite, not after it.
8964                            Self::run_pre_gate(state, &winner).await;
8965                        }
8966                        run_e2e_with_retry(
8967                            state,
8968                            &shell,
8969                            &commands,
8970                            worktree,
8971                            budget,
8972                            &context,
8973                            Some(round),
8974                        )
8975                        .await
8976                    }
8977                },
8978            )
8979            .await?;
8980            // After `pre_gate`: the commit the commands actually ran against.
8981            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8982            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8983                self.state.record_base_progress(&attempted_head);
8984            }
8985            let last = &mut self.state.reviews[round_idx];
8986            last.e2e = outcomes;
8987            last.verify_retried = verify_retried;
8988            // Always the commit and time this attempt actually targeted,
8989            // whether or not it happens to equal the reviewed `head` and
8990            // whether or not a command finished — see
8991            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8992            // attempt is recorded too, so a later reader sees "attempted
8993            // again at T2" rather than silence.
8994            last.verified_head = Some(attempted_head);
8995            last.verified_at = Some(Timestamp::now());
8996            if verify_inconclusive(&last.e2e) {
8997                // Still not a real result: `e2e_deferred` is left exactly
8998                // as it was, so `needs_catchup_run` above reads
8999                // `ResourceBlocked` (via `e2e_status`, which checks
9000                // `resource_blocked` before `e2e_deferred`) and retries
9001                // again on the next reentry, rather than recording
9002                // contention as a red e2e and blocking the run on it.
9003                self.state.save()?;
9004                return Ok(());
9005            }
9006            last.e2e_deferred = false;
9007            // A complete panel may have been saved as unclean solely because
9008            // verification could not run. Refresh that verdict with the new
9009            // outcomes before a granted repair consumes the round's result.
9010            // Incomplete panels retain their original policy/quota decision.
9011            if last.answered == last.expected {
9012                last.clean = round_is_clean(
9013                    last.blocking,
9014                    last.e2e.iter().all(CommandOutcome::ok),
9015                    last.answered,
9016                    last.expected,
9017                    0,
9018                    self.state.config.graph.incomplete_review,
9019                );
9020            }
9021        }
9022        let last = &self.state.reviews[round_idx];
9023        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
9024
9025        match last.e2e_status() {
9026            E2eStatus::Failed => {
9027                let red: Vec<String> = last
9028                    .e2e
9029                    .iter()
9030                    .filter(|o| !o.ok())
9031                    .map(|o| {
9032                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
9033                            .map(|c| format!(" ({c})"))
9034                            .unwrap_or_default();
9035                        format!(
9036                            "`{}` -> {:?}{comparison}\n{}",
9037                            o.command,
9038                            o.code,
9039                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9040                        )
9041                    })
9042                    .collect();
9043                let can_repair = last.blocking == 0 && last.fix.is_none();
9044                self.state.reviews[round_idx].clean = false;
9045                self.state
9046                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
9047                self.state.status = RunStatus::Blocked;
9048                if repairable
9049                    && can_repair
9050                    && self.state.reviews.len() < self.state.config.graph.review_rounds
9051                {
9052                    self.state.status = RunStatus::Reviewing;
9053                }
9054            }
9055            // `needs_catchup_run` above already retried once this call; if
9056            // it is still blocked, this is magi's own admission it could
9057            // not get a command to run, never a verdict on the patch — the
9058            // run is left exactly where a later reentry can retry again.
9059            E2eStatus::ResourceBlocked => {
9060                self.state.event(
9061                    "review",
9062                    format!(
9063                        "{why}; e2e could not run (resource unavailable); not \
9064                         deciding yet"
9065                    ),
9066                );
9067            }
9068            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
9069                self.state.event(
9070                    "review",
9071                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
9072                );
9073                self.record_contested_handoff();
9074                self.state.status = RunStatus::Gating;
9075            }
9076        }
9077        self.state.save()?;
9078        Ok(())
9079    }
9080
9081    // ----------------------------------------------------------------- gate
9082
9083    async fn gate(&mut self) -> Result<()> {
9084        if self.hold_base_sync().await? {
9085            return Ok(());
9086        }
9087        // Judged by the review record itself, not by `status`: a solo
9088        // candidate's `judge`/`deliberate` skip rewrites `status` on every
9089        // reentry (see `judge`), and trusting it here is exactly how a run
9090        // that exhausted its review budget got gated and merged a second
9091        // time around. `review_conclusion` recomputes the review loop's own
9092        // verdict from the round records themselves — `Gating` for a clean
9093        // round or a hand-off (see `stop_reviewing`), anything else means the
9094        // loop is still going or genuinely blocked.
9095        // A base the winner could not be replayed onto is a decision, not a
9096        // round: there is no landing tree to gate. Read as its own record for
9097        // the same reason the review verdict is.
9098        if self.state.status == RunStatus::Failed
9099            || self
9100                .state
9101                .base_sync
9102                .as_ref()
9103                .is_some_and(|s| s.conflict.is_some())
9104            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9105                != Some(RunStatus::Gating)
9106        {
9107            return Ok(());
9108        }
9109        let Some(winner) = self.state.winner().cloned() else {
9110            return Ok(());
9111        };
9112        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9113        self.state.reconcile_verification_head(&head);
9114        self.state.save()?;
9115        let wait = self.repository_wait();
9116        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9117            return Ok(());
9118        }
9119        if self.state.gate_ran {
9120            // `review_loop` derives its conclusion from the clean review
9121            // record on every reentry and therefore puts a completed run back
9122            // in `Gating`. A recorded gate is a stronger, terminal fact:
9123            // retain its original command output (or lack of any, for a repo
9124            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
9125            // doc) and restore `Blocked` on a real failure rather than
9126            // pretending the command is still running or running it a second
9127            // time. `gate_ran == false` remains the only shape — unattempted,
9128            // or a resource-blocked retry — that may still need to execute a
9129            // command.
9130            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
9131                self.state.status = RunStatus::Blocked;
9132                self.state.save()?;
9133            }
9134            return Ok(());
9135        }
9136        self.state.status = RunStatus::Gating;
9137        let mut outcomes = self.run_gate(&winner).await?;
9138        let mut attempted_head = self.state.gate_head.clone();
9139        loop {
9140            // A resource-blocked outcome means the gate command never actually
9141            // ran - the shared build cache could not be acquired or confirmed
9142            // fresh in time - which is evidence about the machine, not about
9143            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
9144            // Recording it as a red gate would mark a run `Blocked` on nothing
9145            // but contention magi has already logged; leaving `self.state.gate`
9146            // empty and `self.state.gate_ran` false instead keeps the shape
9147            // this function already treats as "still needs to run" (see the
9148            // early-return above), so the next call retries the command
9149            // rather than concluding anything.
9150            if verify_inconclusive(&outcomes) {
9151                self.state.save()?;
9152                return Ok(());
9153            }
9154            if outcomes.iter().all(CommandOutcome::ok) {
9155                break;
9156            }
9157            let fixes_before = self.state.gate_fixes.len();
9158            match self.gate_fix_round(&winner, &outcomes).await? {
9159                GateFix::Retry => {
9160                    outcomes = self.run_gate(&winner).await?;
9161                    attempted_head = self.state.gate_head.clone();
9162                }
9163                GateFix::Stop => {
9164                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
9165                    if self.state.gate_fixes.len() > fixes_before
9166                        && attempted_head.as_deref() != Some(current.as_str())
9167                        && verify_current_head(&mut self.state, &winner, &wait).await?
9168                    {
9169                        // A new SHA owes a gate even when a spent fixer changed only
9170                        // commit metadata. This does not grant another repair round.
9171                        outcomes = self.run_gate(&winner).await?;
9172                        attempted_head = self.state.gate_head.clone();
9173                    } else {
9174                        break;
9175                    }
9176                }
9177                GateFix::Defer => {
9178                    self.state.save()?;
9179                    return Ok(());
9180                }
9181            }
9182        }
9183        let passed = outcomes.iter().all(CommandOutcome::ok);
9184        self.state.gate = outcomes;
9185        self.state.gate_ran = true;
9186        self.state.gate_head = attempted_head;
9187        if !self.state.gate.is_empty()
9188            && !verify_inconclusive(&self.state.gate)
9189            && let Some(head) = self.state.gate_head.clone()
9190        {
9191            self.state.record_base_progress(&head);
9192        }
9193        self.state.save()?;
9194        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9195            return Ok(());
9196        }
9197        if !passed {
9198            self.state.status = RunStatus::Blocked;
9199            let spent = self.state.gate_fixes.len();
9200            self.state.event(
9201                "gate",
9202                if spent == 0 {
9203                    "gate failed; not merging".to_owned()
9204                } else {
9205                    format!("gate failed after {spent} gate-fix round(s); not merging")
9206                },
9207            );
9208        }
9209        self.state.save()?;
9210        Ok(())
9211    }
9212
9213    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9214    /// changed into one commit. Runs before `verify.e2e` in the review loop
9215    /// and again before the gate commands, always on the winner and never on
9216    /// a candidate awaiting judging.
9217    ///
9218    /// Before e2e as well as before the gate because command evidence belongs
9219    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9220    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9221    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9222    /// own call then finds nothing left to change. The commands must be
9223    /// idempotent; one that is not makes a commit per call.
9224    ///
9225    /// Never fails the run: a non-zero exit or timeout is a warning and a
9226    /// recorded outcome, and the gate remains the single arbiter. Nothing
9227    /// configured means nothing happens - no event, no commit. `commit_all`
9228    /// commits any leftover change under the neutral identity and returns
9229    /// `false` when the tree is clean, so no empty commit is ever made.
9230    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9231        let commands = state.config.verify.pre_gate.clone();
9232        if commands.is_empty() {
9233            return;
9234        }
9235        let shell = state.config.shell();
9236        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9237        let (outcomes, _) = run_commands(
9238            state,
9239            "pre_gate",
9240            "pre_gate",
9241            0,
9242            &shell,
9243            &commands,
9244            &winner.worktree,
9245            timeout,
9246        )
9247        .await;
9248        for o in &outcomes {
9249            if !o.ok() {
9250                tracing::warn!(
9251                    "pre_gate `{}` failed ({:?}); the gate decides",
9252                    o.command,
9253                    o.code
9254                );
9255            }
9256            state.event(
9257                "pre_gate",
9258                format!(
9259                    "`{}` -> {}",
9260                    o.command,
9261                    if o.ok() {
9262                        "pass".to_owned()
9263                    } else {
9264                        format!(
9265                            "FAIL ({:?})\n{}",
9266                            o.code,
9267                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9268                        )
9269                    }
9270                ),
9271            );
9272        }
9273        state.pre_gate = outcomes;
9274        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9275            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9276                Ok(head) => {
9277                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9278                    state.pre_gate_commit = Some(head);
9279                }
9280                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9281            },
9282            Ok(false) => {}
9283            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9284        }
9285        if let Err(e) = state.save() {
9286            tracing::warn!("could not persist the pre_gate record: {e:#}");
9287        }
9288    }
9289
9290    /// Run `verify.gate` once against the winner's current tree, logging one
9291    /// event per command. Empty when nothing is configured.
9292    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9293        let wait = self.repository_wait();
9294        run_landing_gate(&mut self.state, winner, &wait).await
9295    }
9296
9297    /// One bounded fix round for a failing gate.
9298    ///
9299    /// The fixer is told the failure came from the gate itself, not from a
9300    /// reviewer, and is shown the failed commands, their exit codes and a tail
9301    /// of their output - whatever `[verify].gate` holds, nothing here knows
9302    /// what those commands run. Only a normal non-zero exit that printed
9303    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9304    /// command or a full disk says nothing about the code, and a fixer sent
9305    /// after it can only appease the machine. The round is judged by what git
9306    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9307    /// again before the gate does, so a fix cannot trade a green gate for a
9308    /// red e2e unnoticed.
9309    async fn gate_fix_round(
9310        &mut self,
9311        winner: &Candidate,
9312        outcomes: &[CommandOutcome],
9313    ) -> Result<GateFix> {
9314        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9315            g.phase == crate::repair_budget::Phase::Fixing
9316                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9317        }) {
9318            self.state.gate_fixes.len().saturating_add(1)
9319        } else {
9320            self.state.config.graph.gate_fix_rounds
9321        };
9322        let spent = self.state.gate_fixes.len();
9323        if spent >= cap {
9324            if cap > 0 {
9325                self.state.event(
9326                    "gate",
9327                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9328                );
9329            }
9330            return Ok(GateFix::Stop);
9331        }
9332        if !gate_fixable(outcomes) {
9333            self.state.event(
9334                "gate",
9335                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9336                 command or similar); not spending a fix round on it",
9337            );
9338            return Ok(GateFix::Stop);
9339        }
9340        let min_free = self.state.config.disk.min_free_bytes;
9341        if min_free > 0 {
9342            match crate::disk::free_bytes(&winner.worktree) {
9343                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9344                Ok(free) => {
9345                    self.state.event(
9346                        "gate",
9347                        format!(
9348                            "only {free} bytes free ({min_free} required by `[disk] \
9349                             min_free_bytes`); not spending a fix round on a failure the disk \
9350                             may explain"
9351                        ),
9352                    );
9353                    return Ok(GateFix::Stop);
9354                }
9355                Err(e) => {
9356                    self.state.event(
9357                        "gate",
9358                        format!("free disk space could not be measured ({e:#}); no fix round"),
9359                    );
9360                    return Ok(GateFix::Stop);
9361                }
9362            }
9363        }
9364
9365        let attempt = spent + 1;
9366        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9367        let base = self.landing_base();
9368        let fix_prompt = prompt::gate_fix_in(
9369            &self.state.instruction,
9370            &failed,
9371            attempt,
9372            cap,
9373            &self.state.config.graph.language,
9374            &self.state.config.graph.github_language,
9375        );
9376        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9377        let sessions = self.state.config.graph.sessions;
9378        let artifacts = self.merge_repair_artifacts();
9379        self.state.event(
9380            "gate",
9381            format!("gate failed; gate-fix round {attempt} of {cap}"),
9382        );
9383        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9384        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9385        // Persist before invoking the fixer: it may commit and then be
9386        // interrupted before its result (or the following e2e) is saved.
9387        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9388            before.clone(),
9389            false,
9390            Vec::new(),
9391        ));
9392        self.state.save()?;
9393        let (_, seat, out) = self
9394            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9395                prompt: fix_prompt.clone(),
9396                spec,
9397                seat,
9398                cwd: winner.worktree.clone(),
9399                timeout,
9400                allow_write: true,
9401                sessions,
9402                artifacts: artifacts.clone(),
9403                stem: format!("gate-fix-{attempt}"),
9404                handover: None,
9405            })
9406            .await;
9407        // The fixer was never asked: no round is spent (nothing is recorded)
9408        // and a later reentry asks the same agent again.
9409        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9410            return Ok(GateFix::Defer);
9411        }
9412        let mut record = GateFixRecord {
9413            agent: seat.agent.clone(),
9414            failed,
9415            notes: String::new(),
9416            committed: false,
9417            error: None,
9418        };
9419        match out {
9420            AgentOutcome::Ok(o) => {
9421                // A missing report is not a failed fix: the round is judged
9422                // by the tree below, and the report only carries prose.
9423                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9424                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9425                }
9426            }
9427            AgentOutcome::Dropped(_) => {
9428                record.error = Some("the CLI dropped the stream".to_owned());
9429            }
9430            AgentOutcome::Quota(o) => {
9431                self.state.quota.push(QuotaLoss::from_report(
9432                    seat.key.clone(),
9433                    "gate-fix",
9434                    o.quota.as_ref(),
9435                ));
9436                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9437            }
9438            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9439        }
9440        self.state.seats.insert(seat.key.clone(), seat);
9441        let coordination = self.coordinate(&winner.worktree).await?;
9442        if let Ok(r) = git::rescue_commit(
9443            &winner.worktree,
9444            &format!("magi: gate fix {attempt} (uncommitted work)"),
9445        )
9446        .await
9447        {
9448            self.state.note_withheld("gate-fix", &r.withheld);
9449        }
9450        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9451        record.committed = after != before;
9452        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9453        let note = record.error.clone();
9454        self.state.gate_fixes.push(record);
9455        self.state.save()?;
9456        if !changed {
9457            self.state.event(
9458                "gate",
9459                match note {
9460                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9461                    None => format!("gate-fix round {attempt}: the tree did not change"),
9462                },
9463            );
9464            return Ok(GateFix::Stop);
9465        }
9466        self.state.event(
9467            "gate",
9468            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9469        );
9470
9471        drop(coordination);
9472        let wait = self.repository_wait();
9473        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9474    }
9475
9476    // ---------------------------------------------------------------- merge
9477
9478    /// One read-only rewrite by the summary's author; a text the gate still
9479    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9480    /// applies on their word or on silence. `None` means the run is parked on
9481    /// that question and nothing may be pushed or opened yet.
9482    async fn guarded_pr_message(
9483        &mut self,
9484        winner: &Candidate,
9485        facts: Option<&BranchFacts>,
9486        posting: bool,
9487    ) -> Result<Option<PrMessage>> {
9488        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9489        let head = match final_head.as_deref() {
9490            Some(h) => crate::pr_outcome::FinalHead::At(h),
9491            None => crate::pr_outcome::FinalHead::Unknown,
9492        };
9493        // Only a pull request that is about to be posted pays for a summary.
9494        let summarized = if posting {
9495            Some(self.summarize_change(winner, final_head.as_deref()).await)
9496        } else {
9497            None
9498        };
9499        // A busy shared resource is not a permanent cause: publishing an
9500        // "unavailable" description would stick (a later head move never
9501        // edits the body). Stop before anything is pushed or opened; the
9502        // run is `Blocked` and a resume asks the summary again.
9503        if self.state.resource_block.is_some() {
9504            self.state.event(
9505                "pr-summary",
9506                "a shared resource was busy; nothing was published, resume to summarize again",
9507            );
9508            return Ok(None);
9509        }
9510        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9511            anyhow::bail!(
9512                "the final commit moved during public description generation; retry before publishing"
9513            );
9514        }
9515        let note = match (&summarized, &self.state.change_summary) {
9516            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9517            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9518            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9519            (None, _) => ChangeNote::NotAsked,
9520        };
9521        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9522        if !posting {
9523            let identity = crate::scrub::Identity::current();
9524            return Ok(Some(PrMessage {
9525                title: crate::scrub::scrub(&pr.title, &identity),
9526                body: crate::scrub::scrub(&pr.body, &identity),
9527            }));
9528        }
9529        // This very text was already rejected and asked about: no second
9530        // judge call, rewrite or question, just carry the record on.
9531        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9532        if let Some(known) = self
9533            .state
9534            .github_text
9535            .clone()
9536            .filter(|g| g.fingerprint == raw_fp)
9537        {
9538            return self.settle_withheld(winner, &pr, known).await;
9539        }
9540        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9541        let mut violations =
9542            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9543        let identity = crate::scrub::Identity::current();
9544        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9545            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9546            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9547        {
9548            violations.push(crate::github_text::Violation::SensitiveData);
9549        }
9550        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9551        // only a language violation starts one; sensitive data alone goes
9552        // straight to the owner, with the redacted text as the fallback.
9553        let has_language = violations
9554            .iter()
9555            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9556        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9557            self.state.event(
9558                "github-text",
9559                if has_language {
9560                    format!("description rejected: {violations:?}; requesting one rewrite")
9561                } else {
9562                    format!("description rejected: {violations:?}; asking the owner")
9563                },
9564            );
9565            let mut rewritten = false;
9566            let mut rejected_rewrite = None;
9567            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9568            {
9569                let output = text;
9570                if let Some(title) = summary_title(&output) {
9571                    // Judge the redacted candidate that will actually be posted.
9572                    // Sensitive data alone must not discard a useful rewrite.
9573                    let raw_body = summary_without_title(&output);
9574                    let clean_title = crate::scrub::scrub(&title, &identity);
9575                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9576                    let redacted = clean_title != title || body != raw_body;
9577                    let title = clean_title;
9578                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9579                    if !complete {
9580                        self.state.event(
9581                            "github-text",
9582                            "description rewrite omitted required findings",
9583                        );
9584                    }
9585                    if !body.trim().is_empty() {
9586                        body.push_str("\n\n");
9587                        body.push_str(&public_pr_evidence(&self.state, head));
9588                    }
9589                    let marker = format!("magi:run/{}", self.state.id);
9590                    if !body.trim().is_empty() && !body.contains(&marker) {
9591                        body.push_str(&format!("\n\n{marker}"));
9592                    }
9593                    let rewrite = PrMessage {
9594                        title: title.clone(),
9595                        body: body.clone(),
9596                    };
9597                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9598                    let mut failed = crate::github_text::check_for(
9599                        &self.state.config.graph,
9600                        &title,
9601                        &body,
9602                        redecision,
9603                    );
9604                    if (!crate::github_text::shareable(&title)
9605                        || !crate::github_text::shareable(&body))
9606                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9607                    {
9608                        failed.push(crate::github_text::Violation::SensitiveData);
9609                    }
9610                    if complete
9611                        && !title.trim().is_empty()
9612                        && !body.trim().is_empty()
9613                        && !failed.is_empty()
9614                    {
9615                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9616                            title: title.clone(),
9617                            body: body.clone(),
9618                            failed: failed
9619                                .iter()
9620                                .map(|v| crate::github_text::category(*v).to_owned())
9621                                .collect(),
9622                        });
9623                    }
9624                    if complete
9625                        && !title.trim().is_empty()
9626                        && !raw_body.trim().is_empty()
9627                        && failed.is_empty()
9628                    {
9629                        decision = redecision;
9630                        pr = PrMessage { title, body };
9631                        rewritten = true;
9632                        self.state
9633                            .event("github-text", "description rewrite passed");
9634                        if redacted {
9635                            self.state.event(
9636                                "github-text",
9637                                "sensitive data removed from description rewrite",
9638                            );
9639                        }
9640                    }
9641                }
9642            }
9643            if !rewritten {
9644                self.state.event(
9645                    "github-text",
9646                    "description rewrite unavailable or rejected; asking the owner",
9647                );
9648                if let Some(w) =
9649                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9650                {
9651                    // A different text than the one asked about before: that
9652                    // question no longer describes anything.
9653                    self.retire_github_text_question("the withheld text changed");
9654                    let record = crate::run::GithubTextAsk {
9655                        rewrite: rejected_rewrite,
9656                        fingerprint: raw_fp,
9657                        title: w.title,
9658                        body: w.body,
9659                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9660                        question: None,
9661                        asks: 0,
9662                        resolved: false,
9663                        chosen_title: None,
9664                        choice: None,
9665                        publication: None,
9666                    };
9667                    return self.settle_withheld(winner, &pr, record).await;
9668                }
9669            }
9670        }
9671        let (title, body) =
9672            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9673        Ok(Some(PrMessage { title, body }))
9674    }
9675
9676    /// Describe the whole change from its final diff in either run mode.
9677    ///
9678    /// The summary is tied to the final commit and to the merge base of the
9679    /// resolved remote base; a record for any other pair is dropped and the
9680    /// agent asked again, so a description never outlives the diff it was
9681    /// written from. The seat is read-only and the prompt tells it to read the
9682    /// diff and the code around it. `[roles] synthesizer` selects the agents
9683    /// (unset: the default pick), each asked at most once, advancing on an
9684    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9685    /// carries the reason it is unavailable; nothing is invented then.
9686    async fn summarize_change(
9687        &mut self,
9688        winner: &Candidate,
9689        head: Option<&str>,
9690    ) -> std::result::Result<(), String> {
9691        let Some(head) = head else {
9692            return Err("the final commit could not be read".to_owned());
9693        };
9694        let remote = self.state.config.merge.remote.clone();
9695        let tracking = format!("{remote}/{}", self.state.base_branch);
9696        if !git::rev_exists(&winner.worktree, &tracking).await {
9697            return Err(format!("the remote base `{tracking}` could not be read"));
9698        }
9699        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9700            Ok(b) if !b.is_empty() => b,
9701            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9702        };
9703        let evidence = crate::pr_outcome::summary_evidence(
9704            &self.state,
9705            crate::pr_outcome::FinalHead::At(head),
9706        );
9707        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9708        if self
9709            .state
9710            .change_summary
9711            .as_ref()
9712            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9713        {
9714            return Ok(());
9715        }
9716        if self.state.change_summary.take().is_some() {
9717            self.state.event(
9718                "pr-summary",
9719                "the final diff or evidence changed; the earlier change summary was discarded",
9720            );
9721        }
9722        // Save the source snapshot even if no generation agent is available.
9723        if let Err(e) = write_artifact(
9724            &self.state,
9725            &format!("public-description-{fingerprint}.md"),
9726            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9727        ) {
9728            tracing::warn!("could not save public description evidence: {e:#}");
9729        }
9730        let chain = match agent::pick_chain(
9731            &self.state.config.agents,
9732            self.state.config.roles.synthesizer.as_ref(),
9733            &agent::installed,
9734            "synthesizer",
9735        ) {
9736            Ok(chain) => chain,
9737            Err(e) => {
9738                tracing::warn!("no agent for the change summary: {e:#}");
9739                self.state.event("pr-summary", "no summary agent available");
9740                return Err("no agent was available to summarize it".to_owned());
9741            }
9742        };
9743        let subjects = git::subjects(&winner.worktree, &base, head)
9744            .await
9745            .unwrap_or_default();
9746        let stat = git::diff_stat(&winner.worktree, &base, head)
9747            .await
9748            .unwrap_or_default();
9749        let stat: String = stat.chars().take(6_000).collect();
9750        let mut prompt = crate::prompt::change_summary_in(
9751            &base,
9752            head,
9753            &subjects,
9754            stat.trim(),
9755            &self.state.config.graph.github_language,
9756        );
9757        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."));
9758        let sessions = self.state.config.graph.sessions;
9759        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9760        let prompts = self.state.config.prompts.clone();
9761        let cache = self.state.config.cache_dir();
9762        let run = self.state.id.clone();
9763        for (i, spec) in chain.into_iter().enumerate() {
9764            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9765            let github_spec = match agent::for_github_text(
9766                &spec,
9767                &self.state.config.graph.github_language,
9768                &winner.worktree,
9769            ) {
9770                Ok(spec) => spec,
9771                Err(e) => {
9772                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9773                    continue;
9774                }
9775            };
9776            let job = SeatJob {
9777                spec: github_spec,
9778                seat,
9779                cwd: winner.worktree.clone(),
9780                prompt: prompt.clone(),
9781                timeout,
9782                allow_write: false,
9783                sessions,
9784                artifacts: agent::artifacts_dir(&self.state.dir()),
9785                stem: if i == 0 {
9786                    "change-summary".to_owned()
9787                } else {
9788                    format!("change-summary-{}", spec.id)
9789                },
9790                handover: None,
9791            };
9792            let ctx = WaveCtx {
9793                run: &run,
9794                node: "pr-summary",
9795                prompts: &prompts,
9796                cache: cache.as_deref(),
9797                round: None,
9798                carry_seats: false,
9799                pauses: Some((&self.pause, &self.interrupt)),
9800            };
9801            let (seat, outcome) =
9802                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9803            self.state.seats.insert(seat.key.clone(), seat);
9804            let text = match outcome {
9805                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9806                AgentOutcome::ResourceBlocked(why) => {
9807                    // No agent was asked: the run stops resumably before
9808                    // anything is published (see `guarded_pr_message`).
9809                    if self.state.resource_block.is_none() {
9810                        self.state.resource_block = Some(crate::run::ResourceBlock {
9811                            cause: crate::run::ResourceBlockCause::Other,
9812                            node: "pr-summary".to_owned(),
9813                            kind: "shared resource".to_owned(),
9814                            detail: why,
9815                            at: Timestamp::now(),
9816                        });
9817                    }
9818                    return Err("a shared resource was busy".to_owned());
9819                }
9820                _ => continue,
9821            };
9822            let blind = &self.state.config.blind;
9823            let Some(title) = summary_title(&text) else {
9824                continue;
9825            };
9826            let body: String = summary_without_title(&text)
9827                .lines()
9828                .filter(|l| !l.contains("magi:run/"))
9829                .collect::<Vec<_>>()
9830                .join("\n");
9831            let body = blind::sanitize_prose(body.trim(), blind);
9832            let title = blind::sanitize_prose(&title, blind);
9833            if body.trim().is_empty() || title.trim().is_empty() {
9834                continue;
9835            }
9836            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9837                continue;
9838            }
9839            // The branch must still be the one the agent was shown.
9840            if git::rev_parse(&winner.worktree, "HEAD")
9841                .await
9842                .ok()
9843                .as_deref()
9844                != Some(head)
9845            {
9846                return Err("the branch moved while the summary was written".to_owned());
9847            }
9848            if git::merge_base(&winner.worktree, &tracking, head)
9849                .await
9850                .ok()
9851                .as_deref()
9852                != Some(base.as_str())
9853                || crate::pr_outcome::summary_evidence(
9854                    &self.state,
9855                    crate::pr_outcome::FinalHead::At(head),
9856                ) != evidence
9857            {
9858                return Err("the summary evidence changed while it was written".to_owned());
9859            }
9860            self.state.change_summary = Some(crate::run::ChangeSummary {
9861                head: head.to_owned(),
9862                base,
9863                evidence: fingerprint,
9864                title,
9865                body,
9866            });
9867            self.state.event(
9868                "pr-summary",
9869                format!("change summary written by {} for the final diff", spec.id),
9870            );
9871            if let Err(e) = self.state.save() {
9872                tracing::warn!("could not save the change summary: {e:#}");
9873            }
9874            return Ok(());
9875        }
9876        self.state
9877            .event("pr-summary", "no agent produced a change summary");
9878        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9879    }
9880
9881    /// One read-only rewrite request for a withheld description. The
9882    /// implementer's own conversation is tried first when it exists and can be
9883    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9884    /// writes it in a separate conversation, skipping the implementer's agent.
9885    /// The prompt carries the whole text, so no agent needs any memory. Each
9886    /// agent is asked at most once and the chain advances on an error, quota,
9887    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9888    /// that has run out of quota must not end the rewrite. Nothing is recorded
9889    /// as a handover.
9890    async fn rewrite_pr_text(
9891        &mut self,
9892        winner: &Candidate,
9893        pr: &PrMessage,
9894        violations: &[crate::github_text::Violation],
9895    ) -> Option<String> {
9896        let prompt = format!(
9897            "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{}",
9898            pr.title, pr.body
9899        );
9900        let sessions = self.state.config.graph.sessions;
9901        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9902        // (spec, the resumed implementer's seat). A fallback seat is created
9903        // only when its turn comes, so an unused fallback leaves no record.
9904        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9905        let key = format!("impl-{}", winner.label);
9906        if let Some(spec) = self
9907            .state
9908            .config
9909            .agents
9910            .iter()
9911            .find(|a| a.id == winner.agent)
9912            .cloned()
9913            && let Some(existing) = self.state.seats.get(&key)
9914            && existing.agent == spec.id
9915            && agent::has_session(spec.kind, existing, sessions)
9916        {
9917            attempts.push((spec, Some(existing.clone())));
9918        }
9919        match agent::pick_chain(
9920            &self.state.config.agents,
9921            self.state.config.roles.language_judge.as_ref(),
9922            &agent::installed,
9923            "language_judge",
9924        ) {
9925            Ok(chain) => {
9926                for spec in chain {
9927                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9928                        continue;
9929                    }
9930                    attempts.push((spec, None));
9931                }
9932            }
9933            Err(e) if attempts.is_empty() => {
9934                tracing::warn!("no agent for the description rewrite: {e:#}");
9935                self.state
9936                    .event("github-text", "no rewrite agent available");
9937                return None;
9938            }
9939            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9940        }
9941        let prompts = self.state.config.prompts.clone();
9942        let cache = self.state.config.cache_dir();
9943        let run = self.state.id.clone();
9944        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9945            let resumed = resumed_seat.is_some();
9946            let seat = resumed_seat.unwrap_or_else(|| {
9947                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9948            });
9949            let github_spec = match agent::for_github_text(
9950                &spec,
9951                &self.state.config.graph.github_language,
9952                &winner.worktree,
9953            ) {
9954                Ok(spec) => spec,
9955                Err(e) => {
9956                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9957                    continue;
9958                }
9959            };
9960            let job = SeatJob {
9961                spec: github_spec,
9962                seat,
9963                cwd: winner.worktree.clone(),
9964                prompt: prompt.clone(),
9965                timeout: retry_budget(timeout_full, resumed),
9966                allow_write: false,
9967                sessions,
9968                artifacts: agent::artifacts_dir(&self.state.dir()),
9969                stem: if i == 0 {
9970                    "github-text-rewrite".to_owned()
9971                } else {
9972                    format!("github-text-rewrite-{}", spec.id)
9973                },
9974                handover: None,
9975            };
9976            let ctx = WaveCtx {
9977                run: &run,
9978                node: "github-text",
9979                prompts: &prompts,
9980                cache: cache.as_deref(),
9981                round: None,
9982                carry_seats: false,
9983                pauses: Some((&self.pause, &self.interrupt)),
9984            };
9985            let (seat, outcome) =
9986                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9987            self.state.seats.insert(seat.key.clone(), seat);
9988            match outcome {
9989                AgentOutcome::Ok(o)
9990                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9991                {
9992                    return Some(o.text);
9993                }
9994                AgentOutcome::ResourceBlocked(_) => return None,
9995                _ => {}
9996            }
9997        }
9998        None
9999    }
10000
10001    /// Abandon the standing posting-gate question, if any.
10002    fn retire_github_text_question(&mut self, why: &str) {
10003        let Some(id) = self
10004            .state
10005            .github_text
10006            .as_ref()
10007            .and_then(|g| g.question.clone())
10008        else {
10009            return;
10010        };
10011        let _ = ask::Questions::open().update(&id, |q| {
10012            q.abandon(why);
10013            Ok(())
10014        });
10015    }
10016
10017    /// Carry a withheld text to its end: file the question, park while it is
10018    /// open, and on an answer, silence or timeout pick the text to post. The
10019    /// decision is saved before it is used, so it applies once.
10020    async fn settle_withheld(
10021        &mut self,
10022        winner: &Candidate,
10023        pr: &PrMessage,
10024        mut g: crate::run::GithubTextAsk,
10025    ) -> Result<Option<PrMessage>> {
10026        use crate::github_text as gt;
10027        let store = ask::Questions::open();
10028        let timeout = self.state.config.graph.answer_timeout;
10029        if !g.resolved {
10030            let mut standing = g
10031                .question
10032                .as_ref()
10033                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
10034            if let Some(q) = standing.as_ref()
10035                && q.status.open()
10036                && !store.held_reply(&q.id)
10037                && gt::expired(q, timeout)
10038            {
10039                let why = format!("no answer within {}s of asking", timeout.max(1));
10040                standing = store
10041                    .update(&q.id, |q| {
10042                        q.abandon(&why);
10043                        Ok(())
10044                    })
10045                    .ok()
10046                    .map(|(q, ())| q);
10047            }
10048            let mut ask_again: Option<Option<Vec<String>>> = None;
10049            match standing {
10050                // Recorded but never written (a stop between the two saves),
10051                // or removed: ask again without spending the retry.
10052                None if g.asks <= 1 => {
10053                    g.asks = 0;
10054                    ask_again = Some(None);
10055                }
10056                None => {
10057                    g.resolved = true;
10058                    g.chosen_title = None;
10059                    g.choice = Some(GithubTextChoice::Fallback);
10060                }
10061                Some(q) if q.status.open() => {
10062                    self.park_on_github_text(&g)?;
10063                    return Ok(None);
10064                }
10065                Some(q) => match gt::read_reply(&q) {
10066                    gt::Reply::Fallback => {
10067                        g.resolved = true;
10068                        g.chosen_title = None;
10069                        g.choice = Some(GithubTextChoice::Fallback);
10070                    }
10071                    gt::Reply::Original => {
10072                        g.resolved = true;
10073                        g.chosen_title = None;
10074                        g.choice = Some(GithubTextChoice::Original);
10075                    }
10076                    gt::Reply::Rewrite => {
10077                        g.resolved = true;
10078                        g.chosen_title = None;
10079                        g.choice = Some(if g.rewrite.is_some() {
10080                            GithubTextChoice::Rewrite
10081                        } else {
10082                            GithubTextChoice::Fallback
10083                        });
10084                    }
10085                    gt::Reply::Title(text) => {
10086                        let first = text
10087                            .lines()
10088                            .map(str::trim)
10089                            .find(|l| !l.is_empty())
10090                            .unwrap_or("");
10091                        let decision = if first.is_empty() {
10092                            None
10093                        } else {
10094                            let candidate = PrMessage {
10095                                title: first.to_owned(),
10096                                body: String::new(),
10097                            };
10098                            self.judge_pr_language(&winner.worktree, &candidate).await
10099                        };
10100                        match gt::vet_title(
10101                            &text,
10102                            decision,
10103                            self.state.config.graph.github_english(),
10104                        ) {
10105                            Ok(title) => {
10106                                g.resolved = true;
10107                                g.chosen_title = Some(title);
10108                                g.choice = Some(GithubTextChoice::MyTitle);
10109                            }
10110                            Err(cats) if g.asks < 2 => {
10111                                ask_again = Some(Some(
10112                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
10113                                ))
10114                            }
10115                            Err(_) => {
10116                                g.resolved = true;
10117                                g.chosen_title = None;
10118                                g.choice = Some(GithubTextChoice::Fallback);
10119                            }
10120                        }
10121                    }
10122                },
10123            }
10124            if let Some(rejected) = ask_again {
10125                // A retry (after a rejected replacement title) is still about
10126                // the original text: the same ORIGINAL / FALLBACK comparison.
10127                let w = gt::Withheld {
10128                    title: g.title,
10129                    body: g.body,
10130                    categories: g.categories.clone(),
10131                };
10132                // Named by the original text's fingerprint alone, so a resume
10133                // rewrites the same file and the detail stays identical.
10134                let artifact = match crate::run::write_artifact(
10135                    &self.state,
10136                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
10137                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
10138                ) {
10139                    Ok(p) => Some(p),
10140                    Err(e) => {
10141                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
10142                        None
10143                    }
10144                };
10145                let (detail, comparison) = gt::question_content(
10146                    &w,
10147                    &pr.title,
10148                    &pr.body,
10149                    &self.state.id,
10150                    rejected.as_deref(),
10151                    artifact.as_deref(),
10152                    g.rewrite.as_ref(),
10153                );
10154                let mut q = ask::Question::new(
10155                    self.state.id.clone(),
10156                    gt::ASK_NODE.to_owned(),
10157                    gt::ASK_SEAT.to_owned(),
10158                    gt::question_summary(&self.state.config.graph.language, &w),
10159                    detail,
10160                    gt::question_choices(&w, g.rewrite.as_ref()),
10161                );
10162                q.posting_comparison = Some(comparison);
10163                q.answer_timeout = timeout;
10164                // Recorded before it is written: a stop in between leaves a
10165                // record naming a question the resume then files again.
10166                g.question = Some(q.id.clone());
10167                g.asks += 1;
10168                self.state.github_text = Some(g.clone());
10169                self.state.event(
10170                    "github-text",
10171                    format!("asking the owner about the withheld text ({})", q.short()),
10172                );
10173                self.state.save()?;
10174                store
10175                    .put_executable(&mut q)
10176                    .context("file the posting-gate question")?;
10177                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
10178                    tracing::warn!(
10179                        "could not notify about posting-gate question {}: {e:#}",
10180                        q.short()
10181                    );
10182                }
10183                self.park_on_github_text(&g)?;
10184                return Ok(None);
10185            }
10186        }
10187        let resolved = g.chosen_title.clone();
10188        let original = g.choice == Some(GithubTextChoice::Original);
10189        // Field names only: the event log never records the text.
10190        self.state.event(
10191            "github-text",
10192            if original {
10193                format!(
10194                    "posting the original text for: {}",
10195                    match (g.title, g.body) {
10196                        (true, true) => "title, description",
10197                        (true, false) => "title",
10198                        _ => "description",
10199                    }
10200                )
10201            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10202                "posting the saved rewrite title and description".to_owned()
10203            } else if resolved.is_some() {
10204                "posting the owner's replacement title".to_owned()
10205            } else {
10206                "posting the neutral text for the withheld fields".to_owned()
10207            },
10208        );
10209        self.state.github_text = Some(g.clone());
10210        self.state.save()?;
10211        if g.choice == Some(GithubTextChoice::Rewrite)
10212            && let Some(r) = g.rewrite.as_ref()
10213        {
10214            return Ok(Some(PrMessage {
10215                title: r.title.clone(),
10216                body: r.body.clone(),
10217            }));
10218        }
10219        let w = gt::Withheld {
10220            title: g.title,
10221            body: g.body,
10222            categories: g.categories.clone(),
10223        };
10224        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10225        if let Some(t) = resolved {
10226            title = t;
10227        }
10228        // Every withheld field is now neutral or vetted English.
10229        let english = gt::LanguageDecision {
10230            title_english: true,
10231            body_english: true,
10232            body_complete: true,
10233        };
10234        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10235        if original {
10236            // The owner's explicit choice overrides the gate for the fields it
10237            // was made for; the others keep what the gate produced.
10238            if g.title {
10239                title = pr.title.clone();
10240            }
10241            if g.body {
10242                body = pr.body.clone();
10243            }
10244        }
10245        Ok(Some(PrMessage { title, body }))
10246    }
10247
10248    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10249        self.state.github_text = Some(g.clone());
10250        self.state.end_pass_parked(ParkCause::Question);
10251        self.state.parked = true;
10252        self.state.event(
10253            "github-text",
10254            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10255        );
10256        self.state.save()
10257    }
10258
10259    /// Ask `[roles] language_judge` about this text and record which source
10260    /// decided; the text itself is never recorded.
10261    async fn judge_pr_language(
10262        &mut self,
10263        cwd: &Path,
10264        pr: &PrMessage,
10265    ) -> Option<crate::github_text::LanguageDecision> {
10266        self.state.config.roles.language_judge.as_ref()?;
10267        if !self.state.config.graph.language_gate() {
10268            return None;
10269        }
10270        let decision =
10271            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10272        self.state.event(
10273            "github-text",
10274            if decision.is_some() {
10275                "language decided by the language judge"
10276            } else {
10277                "language judge unavailable; using built-in heuristics"
10278            },
10279        );
10280        decision
10281    }
10282
10283    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10284        Box::pin(self.merge_inner())
10285    }
10286
10287    async fn merge_inner(&mut self) -> Result<()> {
10288        if self.resource_halt()? || self.hold_base_sync().await? {
10289            return Ok(());
10290        }
10291        // Same reasoning as `gate`: ask the review and gate records directly
10292        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10293        // skip can rewrite on reentry to something that no longer says
10294        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10295        // so a hand-off (open findings, green verification) reaches merge
10296        // exactly like a genuinely clean round does.
10297        //
10298        // A run resumed mid-`land` never reaches here at all: `execute`
10299        // recognises `RunStatus::Landing` before it even calls `prep`, and
10300        // routes straight to `run_land` instead. That has to happen a level
10301        // up from this function, not with a check in here, because
10302        // `review_loop`'s own status recomputation (see its doc) runs
10303        // *before* `merge` on every reentry and would otherwise overwrite
10304        // the `Landing` marker with `Gating` before this node ever saw it.
10305        if self
10306            .state
10307            .base_sync
10308            .as_ref()
10309            .is_some_and(|s| s.conflict.is_some())
10310            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10311                != Some(RunStatus::Gating)
10312            // `gate_ran == false` is not "passed" - `gate` leaves it false
10313            // both before it has ever run and when its last attempt was
10314            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10315            // permission to merge on nothing but the review record. Only a
10316            // gate that actually ran may proceed; an intentional local
10317            // review can also finish with verification explicitly not configured.
10318            // `RunState::gate_status` computes that distinction.
10319            || !self.state.gate_allows_progress()
10320        {
10321            return Ok(());
10322        }
10323        // This node's own record, not `status`: `status == Ready` is not
10324        // unique to the harmless `MergeMode::None` path this line was
10325        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10326        // run's PR was closed without merging — and on that run `mode` is
10327        // still `Pr`, so a reentry that fell through here would push and
10328        // open a second pull request. `self.state.merge` is set exactly once
10329        // this node (or `land`) has already produced a verdict, under every
10330        // mode, which is what "already done" actually means here.
10331        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10332            return Ok(());
10333        }
10334        let Some(winner) = self.state.winner().cloned() else {
10335            return Ok(());
10336        };
10337        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10338        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10339            self.state.status = RunStatus::Blocked;
10340            self.state.event(
10341                "gate",
10342                "winner changed after gate; fresh verification required",
10343            );
10344            self.state.save()?;
10345            return Ok(());
10346        }
10347        let wait = self.repository_wait();
10348        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10349            return Ok(());
10350        }
10351        let repo = self.state.repo.clone();
10352        let base = self.state.base_branch.clone();
10353        let mode = self.state.config.merge.mode;
10354        let style = self.state.config.merge.style;
10355        let facts = if is_review_run(&self.state) {
10356            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10357            let start = review_base(
10358                &repo,
10359                &self.state.config.merge.remote,
10360                &base,
10361                &self.state.base_commit,
10362                &winner.branch,
10363            )
10364            .await;
10365            branch_facts(&repo, &start, &winner.branch).await
10366        } else {
10367            None
10368        };
10369        // `None` when the base could not be freshly read: then an adopted
10370        // pull request's title is left alone.
10371        let leaked = if is_review_run(&self.state) {
10372            leaked_subjects(&self.state, &winner.branch).await
10373        } else {
10374            Some(Vec::new())
10375        };
10376        // `None`: parked on the owner's word about a withheld title or body.
10377        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10378        // the resume arrives here again.
10379        let Some(pr) = self
10380            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10381            .await?
10382        else {
10383            return Ok(());
10384        };
10385        let message = pr.commit_message();
10386
10387        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10388        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10389            return Ok(());
10390        }
10391        let outcome = match mode {
10392            MergeMode::None => MergeOutcome {
10393                mode,
10394                ok: true,
10395                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10396                empty: false,
10397            },
10398            MergeMode::Pr | MergeMode::Local
10399                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10400            {
10401                MergeOutcome {
10402                    mode,
10403                    ok: false,
10404                    detail: empty_candidate_detail(&self.state, &base),
10405                    empty: true,
10406                }
10407            }
10408            MergeMode::Local => {
10409                let on = git::current_branch(&repo).await?;
10410                if on.as_deref() != Some(base.as_str()) {
10411                    MergeOutcome {
10412                        mode,
10413                        ok: false,
10414                        detail: format!(
10415                            "{} has {} checked out, not the base branch {base}",
10416                            repo.display(),
10417                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10418                        ),
10419                        empty: false,
10420                    }
10421                } else if !git::is_clean(&repo).await? {
10422                    MergeOutcome {
10423                        mode,
10424                        ok: false,
10425                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10426                        empty: false,
10427                    }
10428                } else {
10429                    let out = match style {
10430                        MergeStyle::Merge => {
10431                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10432                        }
10433                        MergeStyle::Squash => {
10434                            git::merge_squash(&repo, &winner.branch, &message).await?
10435                        }
10436                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10437                    };
10438                    MergeOutcome {
10439                        mode,
10440                        ok: out.ok(),
10441                        detail: if out.ok() { out.stdout } else { out.stderr },
10442                        empty: false,
10443                    }
10444                }
10445            }
10446            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10447                self.state.pr_publication_pending = true;
10448                self.state.save()?;
10449                let out =
10450                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10451                self.state.pr_publication_pending = out.is_err();
10452                MergeOutcome {
10453                    mode,
10454                    ok: out.is_ok(),
10455                    detail: match out {
10456                        Ok(url) => url,
10457                        Err(e) => format!("{e:#}"),
10458                    },
10459                    empty: false,
10460                }
10461            }
10462            MergeMode::Pr => {
10463                let remote = self.state.config.merge.remote.clone();
10464                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10465                let pushed = if self.state.foreign_checkout.is_some() {
10466                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10467                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10468                } else {
10469                    git::push(&winner.worktree, &remote, &winner.branch).await?
10470                };
10471                if !pushed.ok() {
10472                    MergeOutcome {
10473                        mode,
10474                        ok: false,
10475                        detail: pushed.stderr,
10476                        empty: false,
10477                    }
10478                } else {
10479                    if self.state.foreign_checkout.is_some() {
10480                        self.state.pr_pushed_head = Some(delivery_head.clone());
10481                        self.state.land_sync_checkpoint = None;
10482                    }
10483                    // A retry or resume of a run whose branch already has an
10484                    // open pull request adopts it rather than failing on a
10485                    // duplicate. Only this winner branch into this base:
10486                    // `branch_for` derives the name from the run id, so a
10487                    // different run's pull request never matches.
10488                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10489                    let out = match pr_merge_plan(found) {
10490                        PrPlan::Create => {
10491                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10492                                .await
10493                        }
10494                        PrPlan::Adopt { url, title } => {
10495                            self.state
10496                                .event("merge", format!("Pr: adopted open pull request {url}"));
10497                            if self.state.explicit_github_text_selection() {
10498                                // An explicit publication selection applies the prepared
10499                                // payload; acceptance alone is not publication proof.
10500                                land::set_pr_text_verbatim(
10501                                    &winner.worktree,
10502                                    &url,
10503                                    &pr.title,
10504                                    &pr.body,
10505                                )
10506                                .await
10507                                .map(|()| url)
10508                            } else {
10509                                if title != pr.title
10510                                    && (!is_review_run(&self.state)
10511                                        || leaked
10512                                            .as_deref()
10513                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10514                                    && let Err(e) =
10515                                        if self.state.github_text.as_ref().is_some_and(|g| {
10516                                            g.resolved
10517                                                && g.title
10518                                                && g.choice == Some(GithubTextChoice::Original)
10519                                        }) {
10520                                            // The owner chose to post this title unmodified.
10521                                            land::set_pr_title_verbatim(
10522                                                &winner.worktree,
10523                                                &url,
10524                                                &pr.title,
10525                                            )
10526                                            .await
10527                                        } else {
10528                                            land::set_pr_title(
10529                                                &mut self.state,
10530                                                &winner.worktree,
10531                                                &url,
10532                                                &pr.title,
10533                                            )
10534                                            .await
10535                                        }
10536                                {
10537                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10538                                    self.state
10539                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10540                                }
10541                                Ok(url)
10542                            }
10543                        }
10544                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10545                    };
10546                    match out {
10547                        Ok(url) => MergeOutcome {
10548                            mode,
10549                            ok: true,
10550                            detail: url,
10551                            empty: false,
10552                        },
10553                        Err(e) => MergeOutcome {
10554                            mode,
10555                            ok: false,
10556                            detail: e.to_string(),
10557                            empty: false,
10558                        },
10559                    }
10560                }
10561            }
10562        };
10563
10564        self.state.status = match (mode, outcome.ok) {
10565            (MergeMode::None, _) => RunStatus::Ready,
10566            (_, true) if outcome.empty => RunStatus::Ready,
10567            (MergeMode::Pr, true) => RunStatus::Ready,
10568            (_, true) => RunStatus::Merged,
10569            (_, false) => RunStatus::Blocked,
10570        };
10571        self.state.event(
10572            "merge",
10573            format!(
10574                "{:?}: {}",
10575                mode,
10576                outcome.detail.lines().next().unwrap_or("")
10577            ),
10578        );
10579        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10580            self.state.record_github_text_publication(&outcome.detail);
10581        }
10582        self.state.merge = Some(outcome);
10583        self.state.save()?;
10584
10585        // The PR is open and the run would historically stop here, leaving the
10586        // operator to watch checks, feed review comments back to a fixer, and
10587        // merge. That was done by hand six times in one session before this
10588        // existed. Opt-in, because merging is the one irreversible thing magi
10589        // can do to a repository.
10590        if self.state.config.graph.land
10591            && mode == MergeMode::Pr
10592            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10593        {
10594            self.run_land().await?;
10595        }
10596        // `run_land` may have left `status` at `Landing` - still waiting on
10597        // CI or the owner's approval, not actually settled - so this has to
10598        // read whatever `status` ended up as here, not the `Merged` this
10599        // function set a few lines up.
10600        self.settle_questions();
10601        Ok(())
10602    }
10603
10604    /// Enter `land`.
10605    ///
10606    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10607    /// a resumed run's re-entry. `land::land` itself is what serialises the
10608    /// two git-mutating moments inside the loop — the rebase push and
10609    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10610    /// to hold a lock across the whole call, and doing so would serialise
10611    /// this run's CI wait against a *different* run's land-approval resume
10612    /// in the same repository, which is exactly the "must not wait on
10613    /// another task" property the daemon's slot-freeing exists to give.
10614    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10615        Box::pin(self.run_land_inner())
10616    }
10617
10618    async fn run_land_inner(&mut self) -> Result<()> {
10619        crate::pr_head::ensure_owner(&self.state)?;
10620        let url = self
10621            .state
10622            .pr
10623            .as_ref()
10624            .map(|pr| pr.url.clone())
10625            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10626            .unwrap_or_default();
10627        let url = url.lines().next().unwrap_or("").trim().to_owned();
10628        if !url.starts_with("http") {
10629            return Ok(());
10630        }
10631        // A land failure is not a lost run: the work is on a branch and the
10632        // pull request is open, which is exactly where a human takes over.
10633        loop {
10634            match land::land(&mut self.state, &url).await {
10635                Ok(_)
10636                    if self
10637                        .state
10638                        .merge_repairs
10639                        .last()
10640                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10641                {
10642                    if self.repair_merge_review().await? {
10643                        continue;
10644                    }
10645                }
10646                Ok(_) if self.state.resource_block.is_some() => {
10647                    return self.stop_for_resource();
10648                }
10649                Ok(pr) if self.state.parked => {
10650                    // `land` already saved the parked marker; nothing here
10651                    // overrides `status` back to a terminal value while an
10652                    // approval is still outstanding.
10653                    let _ = pr;
10654                }
10655                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10656                    self.state.status = RunStatus::Superseded;
10657                    self.state.save()?;
10658                }
10659                Ok(pr) => {
10660                    self.state.status = match pr.state {
10661                        land::PrLifecycle::Merged => RunStatus::Merged,
10662                        _ => RunStatus::Blocked,
10663                    };
10664                    // Downstream of a confirmed merge only - see
10665                    // `bump::should_release_bump`'s own doc for why this one
10666                    // check covers all three of `land`'s success paths.
10667                    // Best-effort: the run already landed, so a failure here
10668                    // (the decision call, `gh`, `cargo`) is recorded and never
10669                    // turns a landed run into a failed one.
10670                    if bump::should_release_bump(self.state.status)
10671                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10672                    {
10673                        // The event is the run's own record. Not-eligible cases
10674                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10675                        // `Err` is a bump that was tried and failed:
10676                        // `after_merge` itself raises the operator notice for
10677                        // that, whether or not a release PR exists yet.
10678                        self.state
10679                            .event("bump", format!("release bump skipped: {e:#}"));
10680                    }
10681                    // Independent of the bump, and best-effort in the same way:
10682                    // findings the merge left open become follow-up tasks.
10683                    if self.state.status == RunStatus::Merged {
10684                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10685                    }
10686                    self.state.save()?;
10687                }
10688                Err(e) => {
10689                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10690                        return Err(e);
10691                    }
10692                    self.state.status = RunStatus::Blocked;
10693                    self.state.event("land", format!("gave up: {e}"));
10694                    self.state.save()?;
10695                }
10696            }
10697            break;
10698        }
10699        Ok(())
10700    }
10701
10702    /// One repair cycle stays under the existing driver/task claim. An
10703    /// interrupted fixer is rolled back and held rather than run twice.
10704    async fn repair_merge_review(&mut self) -> Result<bool> {
10705        use crate::run::MergeRepairPhase as Phase;
10706        crate::pr_head::ensure_owner(&self.state)?;
10707        let i = self.state.merge_repairs.len() - 1;
10708        let request = self.state.merge_repairs[i].clone();
10709        if request.phase == Phase::Fixing {
10710            let restored = match self.state.winner().cloned() {
10711                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10712                None => Err(anyhow::anyhow!("repair has no winning branch")),
10713            };
10714            let why = match restored {
10715                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10716                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10717                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10718            };
10719            self.hold_merge_repair(i, why)?;
10720            return Ok(false);
10721        }
10722        // A completed repair gate is a publication checkpoint. On reentry,
10723        // reject external changes before the ordinary gate path can replace
10724        // that evidence by verifying a new head. Requested repairs still
10725        // start their own review generation below.
10726        if request.phase == Phase::Reviewing && self.state.gate_ran {
10727            let winner = self
10728                .state
10729                .winner()
10730                .context("repair has no winning branch")?;
10731            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10732            if self.state.gate_head.as_deref() != Some(head.as_str())
10733                || !git::is_clean(&winner.worktree).await?
10734            {
10735                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())?;
10736                return Ok(false);
10737            }
10738        }
10739        let failure = if i >= self.state.config.graph.land_rounds
10740            || self.state.config.graph.review_rounds == 0
10741        {
10742            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10743        } else {
10744            None
10745        };
10746        if let Some(why) = failure {
10747            self.hold_merge_repair(i, why)?;
10748            return Ok(false);
10749        }
10750        if request.phase == Phase::Requested {
10751            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10752                Ok(pr) => pr,
10753                Err(e) => {
10754                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10755                    return Ok(false);
10756                }
10757            };
10758            self.state.merge_repairs[i].phase = Phase::Fixing;
10759            self.state.land_approval = None;
10760            self.state.land_armed_head = None;
10761            self.state.save()?;
10762            let reason = land::merge_repair_reason(&self.state, &request)?;
10763            let budget = self.state.config.graph.land_rounds;
10764            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10765            match result {
10766                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10767                Ok(land::Fixed::Deferred) => {
10768                    // An unavailable fixer did not spend this repair request.
10769                    // Restore partial fallback work before retrying it, as for
10770                    // an interrupted repair, without closing the request.
10771                    let worktree = self
10772                        .state
10773                        .winner()
10774                        .context("repair has no winning branch")?
10775                        .worktree
10776                        .clone();
10777                    self.graft_restore(&worktree, &request.head).await?;
10778                    self.state.merge_repairs[i].phase = Phase::Requested;
10779                    self.stop_for_resource()?;
10780                    return Ok(false);
10781                }
10782                Ok(land::Fixed::Failed(why)) => {
10783                    self.hold_merge_repair(
10784                        i,
10785                        format!(
10786                            "repair failed: {why}; inspect the branch and run an explicit review"
10787                        ),
10788                    )?;
10789                    return Ok(false);
10790                }
10791                Err(e) => {
10792                    self.hold_merge_repair(
10793                        i,
10794                        format!(
10795                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10796                        ),
10797                    )?;
10798                    return Ok(false);
10799                }
10800            }
10801            // Even no change gets a real new reviewer wave. The previous
10802            // evidence remains in the request; a former clean/concluded round
10803            // cannot short-circuit the new review or gate.
10804            self.begin_merge_repair_review(i)?;
10805        }
10806        self.review_loop().await?;
10807        self.gate().await?;
10808        if self.resource_halt()? || self.state.parked {
10809            return Ok(false);
10810        }
10811        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10812            != Some(RunStatus::Gating)
10813            || !self.state.gate_allows_progress()
10814        {
10815            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10816            return Ok(false);
10817        }
10818        // Review and gate may have added commits after the initial repair.
10819        // Publish exactly their final head to the existing PR, with a lease.
10820        let winner = self
10821            .state
10822            .winner()
10823            .cloned()
10824            .context("repair has no winning branch")?;
10825        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10826        if self.state.gate_head.as_deref() != Some(after.as_str())
10827            || !git::is_clean(&winner.worktree).await?
10828        {
10829            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())?;
10830            return Ok(false);
10831        }
10832        let expected = self
10833            .state
10834            .pr_pushed_head
10835            .as_deref()
10836            .unwrap_or(&request.head)
10837            .to_owned();
10838        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10839        // Push the checked commit itself: a local ref moving after the check
10840        // must not change which commit the forge receives.
10841        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10842            return Ok(false);
10843        }
10844        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10845        let refspec = format!("{after}:refs/heads/{public}");
10846        // Saved before the push: lease, verified commit and branch. A forge
10847        // that still shows the leased head afterwards is then recognisably
10848        // this run's own lagging view, not someone else's push.
10849        let publication = crate::run::PrPublication {
10850            previous: expected.clone(),
10851            head: after.clone(),
10852            branch: public.clone(),
10853        };
10854        let already_published =
10855            Box::pin(land::repair_publication_observed(&self.state, &publication)).await?;
10856        self.state.pr_publication = Some(publication);
10857        self.state.save()?;
10858        if !already_published {
10859            let push = git::git_raw(
10860                &winner.worktree,
10861                &["push", &lease, &self.state.config.merge.remote, &refspec],
10862            )
10863            .await;
10864            match push {
10865                Ok(out) if out.ok() => {}
10866                Ok(out) => {
10867                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10868                    return Ok(false);
10869                }
10870                Err(e) => {
10871                    self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10872                    return Ok(false);
10873                }
10874            }
10875        }
10876        self.state.pr_pushed_head = Some(after);
10877        self.state.land_sync_checkpoint = None;
10878        self.state.merge_repairs[i].phase = Phase::Complete;
10879        self.state.status = RunStatus::Landing;
10880        self.state.event(
10881            "repair",
10882            "new review and gate completed; fresh owner merge decision required",
10883        );
10884        self.state.save()?;
10885        Ok(true)
10886    }
10887
10888    fn merge_repair_artifacts(&self) -> PathBuf {
10889        let artifacts = agent::artifacts_dir(&self.state.dir());
10890        match self
10891            .state
10892            .merge_repairs
10893            .last()
10894            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10895        {
10896            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10897            None => artifacts,
10898        }
10899    }
10900
10901    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10902        if let Some(e2e) = self.state.head_e2e.take() {
10903            self.state
10904                .verification_history
10905                .push(crate::run::VerificationEvidence {
10906                    superseded_by: None,
10907                    archived_at: Some(Timestamp::now()),
10908                    fixes_spent: Some(self.state.gate_fixes.len()),
10909                    gate_head: None,
10910                    gate_ran: false,
10911                    gate: Vec::new(),
10912                    e2e: Some(e2e),
10913                });
10914        }
10915        self.state.reviews.clear();
10916        self.state.gate.clear();
10917        self.state.gate_ran = false;
10918        self.state.gate_head = None;
10919        self.state.gate_fixes.clear();
10920        self.state.gate_repair_e2e = None;
10921        self.state.pre_gate.clear();
10922        self.state.pre_gate_commit = None;
10923        self.state.contested_handoff = None;
10924        self.state.land_reruns = None;
10925        self.state.land_approval = None;
10926        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10927        self.state.status = RunStatus::Reviewing;
10928        self.state.save()
10929    }
10930
10931    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10932        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10933        self.state.merge_repairs[index].failure = Some(why.clone());
10934        self.state.status = RunStatus::Blocked;
10935        self.state.event("repair", why);
10936        self.state.save()
10937    }
10938
10939    // -------------------------------------------------------------- helpers
10940
10941    /// Fetch or create a seat, keeping its conversation across nodes.
10942    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10943        if let Some(existing) = self.state.seats.get(key)
10944            && existing.agent == agent
10945        {
10946            return existing.clone();
10947        }
10948        // A seat that changes agent mints its session id from the agent too,
10949        // like a handover: the old agent's uuid is already taken by the CLI.
10950        let fresh = if self.state.seats.contains_key(key) {
10951            handover_seat(key, agent, self.state.next_seat_seed())
10952        } else {
10953            SeatState::new(key, agent, self.state.seed)
10954        };
10955        self.state.seats.insert(key.to_owned(), fresh.clone());
10956        fresh
10957    }
10958
10959    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10960    /// seat to another roster agent, in which case that agent. Nodes that
10961    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10962    /// reconsideration) must keep talking to whoever answered it, not slip
10963    /// back to the agent that failed it.
10964    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10965        match self.state.seats.get(key) {
10966            Some(s) if s.agent != spec.id => {
10967                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10968            }
10969            _ => spec,
10970        }
10971    }
10972
10973    /// A candidate rendered for judging, with the leak policy applied.
10974    fn view(&self, c: &Candidate) -> CandidateView {
10975        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10976            .unwrap_or_default();
10977        let (patch, _) = blind::sanitize_patch(
10978            &format!("candidate {} patch", c.label),
10979            &raw,
10980            &self.state.config.blind,
10981        );
10982        CandidateView {
10983            label: c.label,
10984            branch: c.branch.clone(),
10985            summary: c.summary.clone(),
10986            stat: c.stat.clone(),
10987            patch,
10988        }
10989    }
10990
10991    /// The full candidate set as prompt text, for seats with no live session.
10992    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10993        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10994        prompt::judge(
10995            "(see above)",
10996            &views,
10997            self.roles.judges.len(),
10998            base_short,
10999            "en",
11000        )
11001    }
11002
11003    /// The final-vote prompt with everything a seat that has no session of its
11004    /// own needs: the candidates, the seat's own ranking and reasons, and the
11005    /// anonymised deliberation it took part in (only when there was one, so a
11006    /// handed-over seat never sees more than the seat it replaces did). The
11007    /// `Final vote` heading stays first.
11008    fn vote_prompt_full(
11009        &self,
11010        j: usize,
11011        labels: &[char],
11012        language: &str,
11013        candidates: &[Candidate],
11014        base_short: &str,
11015    ) -> String {
11016        let mut text = format!(
11017            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
11018            prompt::final_vote(labels, language),
11019            self.state.instruction,
11020            self.candidate_block(candidates, base_short)
11021        );
11022        if let Some(own) = self
11023            .state
11024            .judgements
11025            .get(j)
11026            .filter(|r| !r.ranking.is_empty())
11027        {
11028            let reasons = own
11029                .reasons
11030                .iter()
11031                .map(|(k, v)| format!("- {k}: {v}"))
11032                .collect::<Vec<_>>()
11033                .join("\n");
11034            text.push_str(&format!(
11035                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
11036                own.ranking.iter().collect::<String>(),
11037                if reasons.is_empty() {
11038                    ""
11039                } else {
11040                    ", because:\n"
11041                }
11042            ));
11043        }
11044        if !self.state.deliberation.is_empty() {
11045            text.push_str("\n# What was argued before this vote\n");
11046            for t in self.transcript(&[], j) {
11047                text.push_str(&format!(
11048                    "\n## {}{}\n\n{}\n",
11049                    t.who,
11050                    if t.is_self { " (you)" } else { "" },
11051                    t.body.trim()
11052                ));
11053            }
11054        }
11055        text
11056    }
11057
11058    /// Anonymised transcript for judge `self_idx`.
11059    ///
11060    /// The initial rankings are always the opening statements. Seeding them
11061    /// only when no turn had been taken yet meant every judge after the first
11062    /// argued against a single voice instead of against the actual split — the
11063    /// disagreement is the information, so it is always on the table.
11064    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
11065        let mut turns = Vec::new();
11066        for j in &self.state.judgements {
11067            if j.ranking.is_empty() {
11068                continue;
11069            }
11070            let reasons = j
11071                .reasons
11072                .iter()
11073                .map(|(k, v)| format!("- {k}: {v}"))
11074                .collect::<Vec<_>>()
11075                .join("\n");
11076            turns.push(Turn {
11077                who: format!("Judge {} (opening ranking)", j.judge),
11078                is_self: j.judge == self_idx + 1,
11079                body: format!(
11080                    "Ranked {}{}{reasons}",
11081                    j.ranking.iter().collect::<String>(),
11082                    if reasons.is_empty() {
11083                        ""
11084                    } else {
11085                        ", because:\n"
11086                    }
11087                ),
11088            });
11089        }
11090        for t in self
11091            .state
11092            .deliberation
11093            .iter()
11094            .flat_map(|r| r.turns.iter())
11095            .chain(current)
11096        {
11097            turns.push(Turn {
11098                who: format!("Judge {}", t.judge),
11099                is_self: t.judge == self_idx + 1,
11100                body: t.body.clone(),
11101            });
11102        }
11103        turns
11104    }
11105}
11106
11107/// Does this seat still hold the context a follow-up prompt would rely on?
11108fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
11109    agent::has_session(spec.kind, seat, sessions)
11110}
11111
11112/// The next entry in `roster` after `start`, never wrapping back to the
11113/// front, whose id is not in `tried` yet.
11114///
11115/// Starts one past `start` rather than at the front of `roster`: `start` is
11116/// the seat's own original position, and a seat whose candidate slot already
11117/// sits on the roster's second entry must fall through to the third next, not
11118/// restart at the first — which is very likely a different candidate's own
11119/// agent already. Never wraps back past `start`, for the same reason: an
11120/// entry earlier in the roster than the seat's own position is almost
11121/// certainly some *other* candidate slot's own agent, and once the tail of
11122/// the roster is exhausted there are no more untried agents for *this* seat
11123/// to fall through to — the caller's fallback chain ends there, exactly as
11124/// "no further untried agents remain in the list for that seat" asks for.
11125///
11126/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
11127/// the same id twice (an operator's `roles.implementers` typo, or a
11128/// `[[agents]]` list reused across roles) must not let
11129/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
11130/// over `roster` either finds an untried id or runs out, so this always
11131/// terminates regardless of duplicates.
11132fn next_untried_in_roster<'a>(
11133    roster: &'a [AgentSpec],
11134    start: usize,
11135    tried: &BTreeSet<String>,
11136) -> Option<&'a AgentSpec> {
11137    roster
11138        .get(start + 1..)?
11139        .iter()
11140        .find(|s| !tried.contains(&s.id))
11141}
11142
11143/// The successor for a seat, shared by all four seat kinds (implement, judge,
11144/// review, advise). `others` holds the ids that *currently* occupy the other
11145/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
11146/// sees them), so roster entries beyond the seat count act as spares: a failed
11147/// seat goes to an agent no other seat holds whenever the roster permits.
11148///
11149/// `carried` is `Some` only for the review loop's carried failure history.
11150/// Order: (1) forward from `start`, never wrapping, untried, not a carried
11151/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
11152/// whole roster: untried and not another seat's occupant; (3) the plain walk
11153/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
11154/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
11155/// a better outcome than an empty seat, and it keeps the answer to "is there
11156/// a successor at all" exactly what it was before occupants were considered,
11157/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
11158/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
11159/// carried failure is a cheaper bet than doubling an agent on the panel, and
11160/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
11161/// the same round are handled one at a time, so a seat later in the batch
11162/// sees an earlier one's new occupant but not yet its own freed agent.
11163fn pick_successor<'a>(
11164    roster: &'a [AgentSpec],
11165    start: usize,
11166    tried: &BTreeSet<String>,
11167    carried: Option<&BTreeSet<String>>,
11168    others: &BTreeSet<String>,
11169) -> Option<&'a AgentSpec> {
11170    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
11171    roster
11172        .get(start + 1..)
11173        .and_then(|tail| {
11174            tail.iter()
11175                .filter(free)
11176                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
11177        })
11178        .or_else(|| {
11179            carried
11180                .is_some()
11181                .then(|| roster.iter().find(free))
11182                .flatten()
11183        })
11184        .or_else(|| match carried {
11185            Some(c) => next_for_seat(roster, start, tried, c),
11186            None => next_untried_in_roster(roster, start, tried),
11187        })
11188}
11189
11190/// The next agent for a seat that carries its failure history across rounds
11191/// (the review loop). `round_tried` is this round's own bound and starts
11192/// empty every round; `carried_failed` only decides priority.
11193///
11194/// First: an id walking forward from `start`, never wrapping, that is neither
11195/// tried this round nor failed in an earlier one. Only when that is exhausted
11196/// does it rescue: the first roster id (in roster order, so this one *does*
11197/// look before `start`) not yet tried this round, which is by then a carried
11198/// failure. Each id is rescued at most once per round, so it cannot loop.
11199fn next_for_seat<'a>(
11200    roster: &'a [AgentSpec],
11201    start: usize,
11202    round_tried: &BTreeSet<String>,
11203    carried_failed: &BTreeSet<String>,
11204) -> Option<&'a AgentSpec> {
11205    roster
11206        .get(start + 1..)?
11207        .iter()
11208        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11209        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11210}
11211
11212/// Where a reviewer seat starts a round: the agent that last answered it when
11213/// it is still on the roster and not marked failed, else the spec's own agent
11214/// unless it failed, else the next roster agent that has not failed, else the
11215/// spec's own agent again (the whole roster failed). Ids no longer on the
11216/// roster are ignored. An empty roster has no handover, so the spec stands.
11217fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11218    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11219        return spec;
11220    };
11221    let ok = |id: &str| !h.failed.contains(id);
11222    if let Some(last) = h.last_ok.as_deref()
11223        && ok(last)
11224        && let Some(s) = roster.iter().find(|s| s.id == last)
11225    {
11226        return s.clone();
11227    }
11228    if ok(&spec.id) {
11229        return spec;
11230    }
11231    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11232    roster
11233        .get(from + 1..)
11234        .into_iter()
11235        .flatten()
11236        .chain(roster.iter())
11237        .find(|s| ok(&s.id))
11238        .cloned()
11239        .unwrap_or(spec)
11240}
11241
11242/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11243/// seed so a CLI that mints its session id up front (`--session-id`) never
11244/// reuses the uuid the previous agent already opened under the same seat key.
11245pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11246    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11247}
11248
11249/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11250/// so the classifier below and the code that builds the message cannot drift.
11251const TIMED_OUT: &str = "timed out";
11252
11253impl FailClass {
11254    /// `None` for an answer; otherwise how the turn failed.
11255    fn of(out: &AgentOutcome) -> Option<Self> {
11256        match out {
11257            AgentOutcome::Ok(_) => None,
11258            AgentOutcome::Quota(_) => Some(Self::Quota),
11259            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11260            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11261            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11262            // Not a failure of the agent. Callers check for it first; `None`
11263            // here means "no class to hand over on".
11264            AgentOutcome::ResourceBlocked(_) => None,
11265        }
11266    }
11267
11268    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11269    fn stem_word(&self) -> &'static str {
11270        match self {
11271            Self::Quota => "quota",
11272            _ => "handover",
11273        }
11274    }
11275}
11276
11277/// The message's first line with its variable parts removed — digit runs and
11278/// path-like tokens — so "exit code 2" and "exit code 7" read
11279/// as one kind of failure.
11280fn failure_signature(msg: &str) -> String {
11281    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11282    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11283    // the historical machine key while the process diagnosis uses readable prose.
11284    if let Some(code) = line
11285        .strip_prefix("process exited with no usable output (exit code ")
11286        .and_then(|s| s.strip_suffix(')'))
11287        .and_then(|s| s.parse::<i32>().ok())
11288    {
11289        line = format!("exited with some({code}) and no usable output");
11290    } else if matches!(
11291        line.as_str(),
11292        "process exited with no usable output (no exit code reported)"
11293            | "process exited with no usable output (exit code unavailable)"
11294    ) {
11295        line = "exited with none and no usable output".to_owned();
11296    }
11297    let mut out = Vec::new();
11298    for word in line.split_whitespace() {
11299        if word.contains('/') || word.contains('\\') {
11300            out.push("<path>".to_owned());
11301            continue;
11302        }
11303        let mut w = String::new();
11304        let mut in_digits = false;
11305        for c in word.chars() {
11306            if c.is_ascii_digit() {
11307                if !in_digits {
11308                    w.push('#');
11309                }
11310                in_digits = true;
11311            } else {
11312                in_digits = false;
11313                w.push(c);
11314            }
11315        }
11316        out.push(w);
11317    }
11318    out.join(" ").chars().take(120).collect()
11319}
11320
11321/// Whether a seat that just failed with `cur` may go to the next roster agent.
11322/// A quota or a timeout always may. Any other failure may not when the agent
11323/// before it failed the same way: an error the prompt causes would otherwise
11324/// walk the whole roster. `prev` is the class of the immediately preceding
11325/// agent's failure, so a quota or timeout in between breaks the run of
11326/// identical failures by itself.
11327fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11328    match cur {
11329        FailClass::Quota | FailClass::Timeout => true,
11330        FailClass::Other(_) => prev != Some(cur),
11331    }
11332}
11333
11334/// A short human reason for a failed outcome, for the handover record.
11335fn fail_reason(out: &AgentOutcome) -> String {
11336    match out {
11337        AgentOutcome::Ok(_) => String::new(),
11338        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11339        AgentOutcome::Dropped(o) => format!(
11340            "the CLI dropped the stream ({})",
11341            o.dropped
11342                .as_ref()
11343                .map(|d| d.why.as_str())
11344                .unwrap_or("it ended without delivering its answer")
11345        ),
11346        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11347            e.lines().next().unwrap_or("").chars().take(160).collect()
11348        }
11349    }
11350}
11351
11352/// Note one handover in the run: the structured record and, in the timeline,
11353/// the sentence a person reads. A quota keeps the wording it always had.
11354pub(crate) fn record_handover(
11355    state: &mut RunState,
11356    node: &str,
11357    seat: &str,
11358    from: &str,
11359    to: &str,
11360    class: &FailClass,
11361    reason: &str,
11362) {
11363    let message = if *class == FailClass::Quota {
11364        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11365    } else {
11366        format!("{seat}: handed over {from} -> {to} ({reason})")
11367    };
11368    state.event(node, message);
11369    state.handovers.push(Handover {
11370        at: Timestamp::now(),
11371        node: node.to_owned(),
11372        seat: seat.to_owned(),
11373        from: from.to_owned(),
11374        to: to.to_owned(),
11375        reason: reason.to_owned(),
11376    });
11377}
11378
11379/// Did this reply report running a command whose own CLI never confirmed an
11380/// exit status?
11381///
11382/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11383/// command *finished* (see that type's own doc), so this can only be `true`
11384/// for a command whose completion event carried no readable exit code — not
11385/// for one that simply is not mentioned at all. That is the one signal this
11386/// crate can read, from the same record `state.jobs` renders, about a reply
11387/// standing next to work its own CLI cannot vouch for finishing; it is
11388/// deliberately not a check on the exit code's *value* (a fixer legitimately
11389/// runs a command that fails mid-iteration before it succeeds) and not a
11390/// guess at a command still running in the background (which emits no event
11391/// at all, and so leaves no evidence here to find).
11392fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11393    commands.iter().any(|c| c.exit_code.is_none())
11394}
11395
11396/// The reason recorded for a candidate, and named in a handover, when an
11397/// implement seat ended its turn without starting the work and did so again
11398/// on its one retry. See [`Runner::retry_unstarted`].
11399const UNSTARTED_TWICE: &str = "the agent ended its turn without starting the work (no tool call, \
11400                               worktree unchanged), and again when asked once more";
11401
11402/// Did this turn end cleanly without the seat having started the work?
11403///
11404/// Every part is positive evidence, and a missing one means "no": a usable
11405/// reply; a CLI whose stream reports tool calls and reported none
11406/// (`tool_calls` is `None` for a backend that does not report them, which is
11407/// unknown, never zero); no command evidence; and a checkout whose `HEAD` is
11408/// the one recorded before the turn (`before`) with nothing uncommitted. A
11409/// dirty tree, a moved `HEAD` or an unreadable repository never authorizes a
11410/// retry: partial work is the other recoveries' business.
11411///
11412/// The comparison is with the seat's own starting point, not the run's base,
11413/// so a seat that left an inherited patch untouched is unstarted too.
11414fn ended_unstarted(
11415    out: &AgentOutput,
11416    before: Option<&str>,
11417    after: Option<&str>,
11418    clean: Option<bool>,
11419) -> bool {
11420    out.usable()
11421        && out.tool_calls == Some(0)
11422        && out.commands.is_empty()
11423        && before.is_some()
11424        && before == after
11425        && clean == Some(true)
11426}
11427
11428/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11429/// adoption guard.
11430#[derive(Debug, Clone, PartialEq, Eq)]
11431enum NoopClaimVerdict {
11432    /// Reply did not open with `NO CHANGE NEEDED:`.
11433    Absent,
11434    /// Structured evidence passed schema, CLI command, and repository checks.
11435    Accepted,
11436    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11437    /// concrete reason.
11438    Rejected(String),
11439}
11440
11441fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11442    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11443    cmd.description.trim() == check.method.trim()
11444}
11445
11446/// Checks cited by `requirements` plus the final check, deduplicated in order.
11447fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11448    let mut out = report.cited_checks();
11449    if let Some(last) = report.checks.last()
11450        && !out
11451            .iter()
11452            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11453    {
11454        out.push(last);
11455    }
11456    out
11457}
11458
11459/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11460/// when the backend reported commands. Empty `commands` is allowed because not
11461/// every backend emits structured command events.
11462fn check_command_evidence(
11463    report: &verdict::VerifiedNoopReport,
11464    commands: &[agent::CommandEvidence],
11465) -> std::result::Result<(), String> {
11466    if commands.is_empty() {
11467        return Ok(());
11468    }
11469    for check in checks_to_cross_verify(report) {
11470        let matching: Vec<&agent::CommandEvidence> = commands
11471            .iter()
11472            .filter(|cmd| command_matches_check(cmd, check))
11473            .collect();
11474        match check.kind {
11475            verdict::NoopEvidenceKind::Command
11476            | verdict::NoopEvidenceKind::Test
11477            | verdict::NoopEvidenceKind::Path => {
11478                let Some(last_cmd) = matching.last() else {
11479                    return Err(format!(
11480                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11481                         but no matching command was recorded by the CLI",
11482                        check.id.trim(),
11483                        check.kind,
11484                        check.target.trim()
11485                    ));
11486                };
11487                if last_cmd.exit_code != Some(0) {
11488                    return Err(format!(
11489                        "contradictory command evidence: check `{}` claims `{}` passed, \
11490                         but its last recorded CLI command (`{}`) exited with {}",
11491                        check.id.trim(),
11492                        check.target.trim(),
11493                        last_cmd.description.trim(),
11494                        crate::notices::exit_status(last_cmd.exit_code)
11495                    ));
11496                }
11497                if check.kind == verdict::NoopEvidenceKind::Test
11498                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11499                {
11500                    return Err(format!(
11501                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11502                         but its last recorded CLI output reports failure or no passing tests",
11503                        check.id.trim(),
11504                        check.target.trim()
11505                    ));
11506                }
11507            }
11508            verdict::NoopEvidenceKind::Commit => {
11509                if let Some(last_cmd) = matching.last()
11510                    && last_cmd.exit_code != Some(0)
11511                {
11512                    return Err(format!(
11513                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11514                         but its last recorded CLI command (`{}`) exited with {}",
11515                        check.id.trim(),
11516                        check.target.trim(),
11517                        last_cmd.description.trim(),
11518                        crate::notices::exit_status(last_cmd.exit_code)
11519                    ));
11520                }
11521            }
11522        }
11523    }
11524    Ok(())
11525}
11526
11527/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11528/// exit, confirmed commands, strict structured JSON validation, and
11529/// `CommandEvidence` consistency.
11530fn evaluate_noop_claim(
11531    usable: bool,
11532    commands: &[agent::CommandEvidence],
11533    text: &str,
11534) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11535    if !text
11536        .trim_start()
11537        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11538    {
11539        return Ok(None);
11540    }
11541    if !usable {
11542        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11543    }
11544    if has_unconfirmed_command(commands) {
11545        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11546    }
11547    let Some(parsed) = verdict::parse_verified_noop(text) else {
11548        return Ok(None);
11549    };
11550    let report = parsed?;
11551    check_command_evidence(&report, commands)?;
11552    Ok(Some(report))
11553}
11554
11555/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11556/// structured no-op report against the candidate's real Git history and
11557/// worktree. Existence alone never satisfies a requirement (the report still
11558/// had to carry concrete passing checks), while a missing commit/path or a
11559/// commit not on `base_commit` disqualifies the claim.
11560async fn verify_noop_repo_evidence(
11561    report: &verdict::VerifiedNoopReport,
11562    worktree: &Path,
11563    base_commit: &str,
11564) -> std::result::Result<(), String> {
11565    let wt_canon = std::fs::canonicalize(worktree).ok();
11566    for check in checks_to_cross_verify(report) {
11567        match check.kind {
11568            verdict::NoopEvidenceKind::Commit => {
11569                let target = check.target.trim();
11570                let Some(sha) = git::commit_of(worktree, target).await else {
11571                    return Err(format!(
11572                        "check `{}` cites commit `{target}`, which does not exist in git history",
11573                        check.id.trim()
11574                    ));
11575                };
11576                if !git::is_ancestor(worktree, &sha, base_commit).await {
11577                    return Err(format!(
11578                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11579                        check.id.trim(),
11580                        short(base_commit)
11581                    ));
11582                }
11583            }
11584            verdict::NoopEvidenceKind::Path => {
11585                let target = check.target.trim();
11586                let rel = verdict::strip_path_locator(target);
11587                let full = worktree.join(rel);
11588                if !full.exists() {
11589                    return Err(format!(
11590                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11591                        check.id.trim()
11592                    ));
11593                }
11594                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11595                    && !path_canon.starts_with(wt_canon)
11596                {
11597                    return Err(format!(
11598                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11599                        check.id.trim()
11600                    ));
11601                }
11602            }
11603            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11604        }
11605    }
11606    Ok(())
11607}
11608
11609/// Full adoption guard for an implementer reply, including real Git history and
11610/// worktree path verification.
11611async fn verified_noop_claim_in_worktree(
11612    usable: bool,
11613    commands: &[agent::CommandEvidence],
11614    text: &str,
11615    worktree: &Path,
11616    base_commit: &str,
11617) -> NoopClaimVerdict {
11618    let report = match evaluate_noop_claim(usable, commands, text) {
11619        Ok(Some(r)) => r,
11620        Ok(None) => return NoopClaimVerdict::Absent,
11621        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11622    };
11623    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11624        return NoopClaimVerdict::Rejected(reason);
11625    }
11626    NoopClaimVerdict::Accepted
11627}
11628
11629/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11630/// trusted as a verified no-op — the adoption guard's pure text-and-command
11631/// half (repository history/path verification runs in
11632/// [`verified_noop_claim_in_worktree`]).
11633///
11634/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11635/// timed out): a marker only earns the benefit of the doubt from a turn the
11636/// CLI itself vouches for finishing properly, the same house style
11637/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11638/// *fix* report to for `commands`. A candidate that timed out, exited
11639/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11640/// or failed structured validation returns `None`.
11641#[cfg(test)]
11642fn verified_noop_claim(
11643    usable: bool,
11644    commands: &[agent::CommandEvidence],
11645    text: &str,
11646) -> Option<String> {
11647    evaluate_noop_claim(usable, commands, text)
11648        .ok()
11649        .flatten()
11650        .map(|report| report.summary_text())
11651}
11652
11653fn short(commit: &str) -> String {
11654    commit.chars().take(7).collect()
11655}
11656
11657fn make_executable(path: &Path) -> Result<()> {
11658    #[cfg(unix)]
11659    {
11660        use std::os::unix::fs::PermissionsExt as _;
11661        let mut perms = std::fs::metadata(path)?.permissions();
11662        perms.set_mode(0o755);
11663        std::fs::set_permissions(path, perms)?;
11664    }
11665    #[cfg(not(unix))]
11666    {
11667        let _ = path;
11668    }
11669    Ok(())
11670}
11671
11672/// What every seat in one batch shares: where the answers are attributed, the
11673/// prompt overlay they inherit, and the build cache they are told to use.
11674///
11675/// A struct rather than four more parameters: `wave` also needs the run's
11676/// state (to record who is answering right now) and the attempt number, and
11677/// eight positional arguments is both unreadable and a clippy error.
11678struct WaveCtx<'a> {
11679    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11680    /// paid for it.
11681    run: &'a str,
11682    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11683    node: &'a str,
11684    prompts: &'a Prompts,
11685    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11686    cache: Option<&'a Path>,
11687    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11688    /// `JobRecord::round`. `None` for every other node.
11689    round: Option<usize>,
11690    /// Carry each seat's failed-agent history across waves (the review loop
11691    /// only): start-of-round priority and handover choice read
11692    /// [`RunState::seat_history`], and every answer or failure writes it.
11693    carry_seats: bool,
11694    /// The run's park / interrupt requests, so a wait for a shared resource
11695    /// can be abandoned the moment the operator asks to park.
11696    pauses: Option<(&'a Pause, &'a Pause)>,
11697}
11698
11699/// Shared scheduling policy for operations and spawned seat invocations.
11700fn repository_wait(
11701    state: &RunState,
11702    pauses: Option<(&Pause, &Pause)>,
11703) -> crate::repo_lock::WaitPolicy {
11704    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11705    let inherited = crate::repo_lock::WaitPolicy::current();
11706    crate::repo_lock::WaitPolicy::new(
11707        Duration::from_secs(state.config.graph.timeout_resource_wait),
11708        move || {
11709            inherited.cancelled()
11710                || pauses
11711                    .as_ref()
11712                    .is_some_and(|(a, b)| a.parked() || b.parked())
11713        },
11714    )
11715}
11716
11717fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11718    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11719        state.event("resource", timeout.0.description());
11720        state.resource_block = Some(timeout.0.clone());
11721        return;
11722    }
11723    if error.is::<crate::repo_lock::ResourceBlocked>() {
11724        state.resource_block = Some(crate::run::ResourceBlock {
11725            cause: crate::run::ResourceBlockCause::Other,
11726            node: "repository".into(),
11727            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11728                "disk admission"
11729            } else if error.to_string().contains("disk pressure") {
11730                "disk pressure"
11731            } else if error.to_string().contains("disk admission") {
11732                "disk admission"
11733            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11734                "incremental cache admission"
11735            } else {
11736                "repository coordination"
11737            }
11738            .into(),
11739            detail: format!("{error:#}"),
11740            at: Timestamp::now(),
11741        });
11742        state.event("resource", error.to_string());
11743    }
11744}
11745
11746async fn coordinate_operation(
11747    state: &mut RunState,
11748    cwd: &Path,
11749    wait: &crate::repo_lock::WaitPolicy,
11750) -> Result<Option<crate::repo_lock::SeatLease>> {
11751    let result =
11752        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11753            .await;
11754    if let Err(e) = &result {
11755        record_repository_block(state, e);
11756    }
11757    result
11758}
11759
11760/// Run one job, honouring the parallelism budget.
11761async fn run_one(
11762    job: SeatJob,
11763    sem: Arc<Semaphore>,
11764    ctx: &WaveCtx<'_>,
11765    state: &mut RunState,
11766    attempt: usize,
11767) -> (SeatState, AgentOutcome) {
11768    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11769        .await
11770        .pop()
11771        .expect("one job in, one result out");
11772    (seat, out)
11773}
11774
11775/// Run every job concurrently, capped by the semaphore, preserving order.
11776///
11777/// Every seat in the batch is recorded into [`RunState::active`] before the
11778/// wave starts and cleared as each answer lands, so the run's own record says
11779/// who is still being waited on rather than only who finished.
11780async fn wave(
11781    jobs: Vec<SeatJob>,
11782    sem: Arc<Semaphore>,
11783    ctx: &WaveCtx<'_>,
11784    state: &mut RunState,
11785    attempt: usize,
11786) -> Vec<(usize, SeatState, AgentOutcome)> {
11787    let WaveCtx {
11788        run,
11789        node,
11790        prompts,
11791        cache,
11792        round,
11793        carry_seats: _,
11794        pauses,
11795    } = *ctx;
11796    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11797    for job in &jobs {
11798        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11799    }
11800    if let Err(e) = state.save() {
11801        // A failed persist of "who is answering right now" must not abort the
11802        // wave: the seats are already being asked, and the alternative is
11803        // losing the answers to save a status line nobody may even be
11804        // watching.
11805        tracing::warn!("could not persist in-progress seats: {e:#}");
11806    }
11807    // Shared-mode waves keep their existing single lease. Isolated writers
11808    // acquire their own checkout's target at seat admission.
11809    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11810    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11811    // never borrowed from a job's agent budget (and never charged to it either,
11812    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11813    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11814    let cache_guard = if let Some(cache_dir) = cache {
11815        if jobs_had_a_writer {
11816            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11817            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11818            match acquire_cache_lease(
11819                state,
11820                cache_dir,
11821                &owner,
11822                resource_limit,
11823                node,
11824                node,
11825                &cancel,
11826            )
11827            .await
11828            {
11829                Ok(Some(g)) => Some(g),
11830                // Parking: leave without spawning anything. The run parks at
11831                // the next boundary and the seats are asked afresh on resume.
11832                Ok(None) => {
11833                    if let Some(block) = &mut state.resource_block {
11834                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11835                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11836                        };
11837                    }
11838                    return block_wave(
11839                        jobs,
11840                        state,
11841                        node,
11842                        attempt,
11843                        "parked while waiting for the shared build cache",
11844                    );
11845                }
11846                // An unreadable lease is not contention: keep the old
11847                // fallback (no shared cache for this wave's seats).
11848                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11849                Err(e) => {
11850                    // Writing seats may not build into a cache this run does
11851                    // not hold, and an agent that cannot be given one is not
11852                    // asked at all: the run stops resumably instead.
11853                    let why = format!("{e:#}");
11854                    state.event(
11855                        "resource",
11856                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11857                    );
11858                    return block_wave(jobs, state, node, attempt, &why);
11859                }
11860            }
11861        } else {
11862            None
11863        }
11864    } else {
11865        None
11866    };
11867    let cache_guard = cache_guard.map(Arc::new);
11868    // Every job keeps its whole budget: the wait above was not the agent's.
11869    // Restart the seats' clocks so "started" means "being spawned now".
11870    state.seats_spawning(node, attempt);
11871    if let Err(e) = state.save() {
11872        tracing::warn!("could not persist the start of a wave: {e:#}");
11873    }
11874    // Queueing behind this wave's own seats for a parallelism slot is normal
11875    // (each of them is bounded by its own agent timeout); only a wait beyond
11876    // all of them plus the resource limit means the slots never came back.
11877    let slot_limit = resource_limit
11878        + jobs
11879            .iter()
11880            .map(|j| j.timeout)
11881            .max()
11882            .unwrap_or_default()
11883            .saturating_mul(jobs.len() as u32);
11884    let mut set = tokio::task::JoinSet::new();
11885    // Seats announce themselves here the moment they hold a parallelism
11886    // permit, i.e. just before their CLI is spawned.
11887    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11888    let overlay = prompts.overlay(node);
11889    let repository_wait = repository_wait(state, pauses);
11890    for (i, mut job) in jobs.into_iter().enumerate() {
11891        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11892        if cache.is_some() && (!job.allow_write || cache_guard.is_some()) {
11893            job.prompt.push('\n');
11894            job.prompt
11895                .push_str(&prompt::build_cache_note(node, job.allow_write));
11896        }
11897        let sem = Arc::clone(&sem);
11898        let run = run.to_owned();
11899        let node = node.to_owned();
11900        // Only implementers were told about the task's attachments, so only
11901        // their seats get the directory widened for reading.
11902        let attachments = if node == "implement" {
11903            state.attachments.clone()
11904        } else {
11905            Vec::new()
11906        };
11907        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11908        // `prompt::build_cache_note`'s doc for why setting it anyway is
11909        // exactly how a sandboxed reviewer's write refusal got reported as a
11910        // defect in the patch, not a property of its own seat. And a
11911        // write-allowed one is handed it only when the lease above was
11912        // actually acquired: a wave that could not get it (`cache_guard` is
11913        // `None`, see its own comment) must not send seats to build into a
11914        // directory this run does not hold - that is the exact concurrent,
11915        // unmanaged-write race this module exists to prevent, not something
11916        // "proceeding anyway" is allowed to reintroduce.
11917        let cache = cache
11918            .filter(|_| job.allow_write && cache_guard.is_some())
11919            .map(Path::to_path_buf);
11920        let cache_guard = cache_guard.clone();
11921        let spawned_tx = spawned_tx.clone();
11922        let repository_wait = repository_wait.clone();
11923        let coordination = state.config.coordination.clone();
11924        let fetched_base = state.fetched_base.clone();
11925        set.spawn(async move {
11926            // A wait for a parallelism slot is scheduling, not the agent: it
11927            // is bounded by its own limit and ends as a resource block, never
11928            // as a timeout of the agent that was not started.
11929            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11930                Ok(p) => p,
11931                Err(_) => {
11932                    return (
11933                        i,
11934                        job.seat,
11935                        AgentOutcome::ResourceBlocked(format!(
11936                            "no parallel slot became free within {}s",
11937                            slot_limit.as_secs()
11938                        )),
11939                        None,
11940                        false,
11941                    );
11942                }
11943            };
11944            spawned_tx.send(job.seat.key.clone()).ok();
11945            let mut seat = job.seat;
11946            let out = repository_wait
11947                .scope(agent::invoke_in_wave(
11948                    &job.spec,
11949                    &mut seat,
11950                    &Invocation {
11951                        coordination: coordination.as_ref(),
11952                        fetched_base: fetched_base.as_ref(),
11953                        cwd: &job.cwd,
11954                        prompt: &job.prompt,
11955                        timeout: job.timeout,
11956                        allow_write: job.allow_write,
11957                        sessions: job.sessions,
11958                        artifacts: &job.artifacts,
11959                        stem: &job.stem,
11960                        run: &run,
11961                        node: &node,
11962                        cache_dir: cache.as_deref(),
11963                        attachments: &attachments,
11964                        writable: &[],
11965                    },
11966                    cache_guard.as_deref(),
11967                ))
11968                .await;
11969            let cache_block = out
11970                .as_ref()
11971                .err()
11972                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11973                .map(|timeout| timeout.0.clone());
11974            let interrupted = out
11975                .as_ref()
11976                .err()
11977                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11978            let out = match out {
11979                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11980                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11981                // Billed work the CLI failed to hand over is not an ordinary
11982                // failure, but its text is the CLI's raw error JSON, not an
11983                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11984                // read it as one by forgetting to check. `usable()` is always
11985                // false here (dropped implies an empty response), so this has
11986                // to be checked before the catch-all `Failed` below or the
11987                // one shape this exists for is lost with the rest.
11988                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11989                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11990                Ok(o) => AgentOutcome::Failed(format!(
11991                    "process exited with no usable output ({})",
11992                    crate::notices::exit_status(o.exit_code)
11993                )),
11994                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11995                    AgentOutcome::ResourceBlocked(e.to_string())
11996                }
11997                Err(e) => AgentOutcome::Failed(e.to_string()),
11998            };
11999            (i, seat, out, cache_block, interrupted)
12000        });
12001    }
12002    drop(spawned_tx);
12003    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
12004    loop {
12005        let joined = tokio::select! {
12006            Some(key) = spawned_rx.recv() => {
12007                // The clock of this seat starts now, not when it queued.
12008                state.seat_spawned(&key);
12009                if let Err(e) = state.save() {
12010                    tracing::warn!("could not persist a seat's start: {e:#}");
12011                }
12012                continue;
12013            }
12014            joined = set.join_next() => joined,
12015        };
12016        let Some(joined) = joined else {
12017            break;
12018        };
12019        let (i, seat, out, cache_block, interrupted) = match joined {
12020            Ok(v) => v,
12021            // No seat to clear: a panicked task never reported which one it
12022            // was. The defensive sweep below this loop is what stops that
12023            // seat's `active` entry from surviving forever.
12024            Err(e) => {
12025                tracing::error!("agent task panicked: {e}");
12026                continue;
12027            }
12028        };
12029        state.seat_finished(&seat.key);
12030        if interrupted
12031            && node == "implement"
12032            && let Some(label) = state
12033                .candidates
12034                .iter()
12035                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
12036                .map(|candidate| candidate.label)
12037        {
12038            state.candidate_preservation.insert(
12039                label,
12040                "interrupted implementation awaiting persistence".into(),
12041            );
12042            state.interrupted_implementations.insert(label);
12043        }
12044        if let Some(block) = cache_block
12045            && state.resource_block.is_none()
12046        {
12047            state.event("resource", block.description());
12048            state.resource_block = Some(block);
12049        }
12050        if let AgentOutcome::ResourceBlocked(why) = &out
12051            && state.resource_block.is_none()
12052        {
12053            state.resource_block = Some(crate::run::ResourceBlock {
12054                cause: crate::run::ResourceBlockCause::Other,
12055                node: node.to_owned(),
12056                kind: if why.contains("disk pressure") {
12057                    "disk pressure"
12058                } else if why.contains("disk admission") {
12059                    "disk admission"
12060                } else if why.contains(crate::incremental::BLOCKED) {
12061                    "incremental cache admission"
12062                } else if why.contains(crate::build_target::KIND) {
12063                    crate::build_target::KIND
12064                } else if why.contains("repository coordination") {
12065                    "repository coordination"
12066                } else {
12067                    "parallel slot"
12068                }
12069                .to_owned(),
12070                detail: why.clone(),
12071                at: Timestamp::now(),
12072            });
12073            let activity = if interrupted {
12074                "agent execution interrupted"
12075            } else {
12076                "no agent was started"
12077            };
12078            state.event("resource", format!("{node}: {activity} - {why}"));
12079        }
12080        record_jobs(state, node, round, &seat.key, &out);
12081        if let Err(e) = state.save() {
12082            tracing::warn!("could not persist a seat's completion: {e:#}");
12083        }
12084        if collected.len() <= i {
12085            collected.resize_with(i + 1, || None);
12086        }
12087        collected[i] = Some((i, seat, out));
12088    }
12089    // Belt-and-braces for the panic branch above: every seat this exact batch
12090    // started shares this `(node, attempt)` pair, and every seat that finished
12091    // normally already cleared itself, so anything left tagged with it here
12092    // can only be a panicked task's leftover. Cleared unconditionally rather
12093    // than left to read as still answering forever.
12094    if state
12095        .active
12096        .values()
12097        .any(|a| a.node == node && a.attempt == attempt)
12098    {
12099        state
12100            .active
12101            .retain(|_, a| !(a.node == node && a.attempt == attempt));
12102        if let Err(e) = state.save() {
12103            tracing::warn!("could not persist the end of a wave: {e:#}");
12104        }
12105    }
12106    drop(cache_guard);
12107    collected.into_iter().flatten().collect()
12108}
12109
12110/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
12111/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
12112/// this is data collection, not the fix-specific completion contract in
12113/// [`Runner::continue_fix_report`], and applies regardless of which node
12114/// asked.
12115///
12116/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
12117/// evidence from; `Failed` does not, and correctly contributes nothing — a
12118/// timeout or crash is not itself evidence about a command the seat may have
12119/// started.
12120fn record_jobs(
12121    state: &mut RunState,
12122    node: &str,
12123    round: Option<usize>,
12124    seat: &str,
12125    out: &AgentOutcome,
12126) {
12127    let commands: &[agent::CommandEvidence] = match out {
12128        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
12129        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
12130    };
12131    let checked_at = Timestamp::now();
12132    for c in commands {
12133        state.jobs.push(JobRecord {
12134            node: node.to_owned(),
12135            round,
12136            seat: seat.to_owned(),
12137            id: c.id.clone(),
12138            description: c.description.clone(),
12139            checked_at,
12140            status: match c.exit_code {
12141                Some(0) => JobStatus::Completed,
12142                Some(_) => JobStatus::Failed,
12143                None => JobStatus::Unknown,
12144            },
12145            exit_code: c.exit_code,
12146            result_summary: c.result_summary.clone(),
12147            source: c.source.clone(),
12148        });
12149    }
12150}
12151
12152/// Is a review round clean, given how many reviewer seats answered against
12153/// how many the round expected?
12154///
12155/// A seat that never answered (timeout, crash, unparsable output) is not a
12156/// seat that read the patch and found nothing — treating it as such is
12157/// exactly the bug this function exists to close. Under the default `block`
12158/// policy a missing seat can never be clean; `warn` still requires the seats
12159/// that *did* answer to have found nothing blocking and verification to be
12160/// green.
12161///
12162/// `quota_missing` narrows that `block` default for exactly one cause of
12163/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
12164/// a session limit lifts by the very next round buys nothing — the seat is
12165/// asked again with the same quota — so once every missing seat is accounted
12166/// for by a quota loss (and at least one seat *did* answer, so a decision has
12167/// something to rest on) the round is decided on the panel that could answer,
12168/// same as `warn` would. A panel that lost every seat to quota is not
12169/// decided here: `answered == 0` falls through to the existing `block`
12170/// fallback so a fully collapsed panel still waits rather than landing on no
12171/// review at all.
12172fn round_is_clean(
12173    blocking: usize,
12174    e2e_ok: bool,
12175    answered: usize,
12176    expected: usize,
12177    quota_missing: usize,
12178    policy: IncompleteReviewPolicy,
12179) -> bool {
12180    if blocking != 0 || !e2e_ok {
12181        return false;
12182    }
12183    if answered == expected || policy == IncompleteReviewPolicy::Warn {
12184        return true;
12185    }
12186    answered > 0 && expected - answered <= quota_missing
12187}
12188
12189/// The review loop's own conclusion, derived entirely from its persisted
12190/// round records and the round budget that produced them — never from
12191/// `status`, so a reentry (or `gate`/`merge` reading it independently)
12192/// recomputes the identical answer regardless of what an earlier node in the
12193/// same walk, or a previous walk, did to `status`.
12194///
12195/// `None` while more rounds remain to try, including when review never ran
12196/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
12197/// gone clean, or the budget is spent, or the tree has stopped moving (see
12198/// [`STAGNANT_LIMIT`]), the answer is one of two things:
12199///
12200/// - An incomplete panel that raised nothing is missing input, not a
12201///   verified tree — never a hand-off candidate, whatever verification said
12202///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
12203/// - Otherwise, green e2e on the last round hands off (see
12204///   [`Runner::stop_reviewing`]); red e2e blocks.
12205///
12206/// A last round whose own verification is still `ResourceBlocked` — magi
12207/// itself never got a command to run, not evidence the patch is broken —
12208/// is neither: this returns `None` for it too, the same as "more rounds
12209/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
12210/// handling of that shape) instead of this cheap recomputation guessing a
12211/// verdict a real attempt never produced.
12212pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
12213    if max_rounds == 0
12214        || reviews.last().is_some_and(|r| {
12215            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
12216        })
12217    {
12218        return Some(RunStatus::Gating);
12219    }
12220    let last = reviews.last()?;
12221    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
12222    if reviews.len() < max_rounds && !stagnant {
12223        return None;
12224    }
12225    if last.incomplete() && last.blocking == 0 {
12226        return Some(RunStatus::Blocked);
12227    }
12228    if last.e2e_status() == E2eStatus::ResourceBlocked
12229        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12230    {
12231        return None;
12232    }
12233    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12234        RunStatus::Gating
12235    } else {
12236        RunStatus::Blocked
12237    })
12238}
12239
12240/// How long a re-ask may take, given the budget the first attempt had.
12241///
12242/// A `nudged` retry is a request to restate an answer the seat has already
12243/// worked out: it carries no new work, so it does not deserve the original
12244/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12245/// 133 seconds while a third sat for over ten minutes on a resumed session
12246/// holding 410 KB of prior output - and because the retry had inherited the
12247/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12248/// judging round whose other seats were long finished.
12249///
12250/// A quarter of the budget, with a floor so that a deliberately short timeout
12251/// does not collapse to nothing. A retry that re-sends the whole prompt
12252/// (because the seat kept no context) is the original job again, and keeps the
12253/// original budget.
12254pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12255    if nudged {
12256        (full / 4).max(Duration::from_secs(120)).min(full)
12257    } else {
12258        full
12259    }
12260}
12261
12262/// Run a wave and parse each reply, re-asking the seats whose reply was
12263/// unusable.
12264///
12265/// The re-ask is a nudge rather than the whole prompt again when the seat still
12266/// holds its conversation, which is the difference between a cheap retry and
12267/// paying for the entire candidate set twice.
12268///
12269/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12270/// successor in `roster` is handed to it instead of being re-asked: the
12271/// handover is the retry. A seat with no successor left (a single-agent
12272/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12273/// the asks to one seat in one node number at most
12274/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12275/// is asked once (a dropped stream is nudged first), and only the last agent
12276/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12277/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12278/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12279/// other failure stops the chain when the previous agent failed the same way
12280/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12281/// [`has_context`] is false and the job's own full prompt and full budget are
12282/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12283/// intermediate ones are not losses) and is returned as a failure like any
12284/// other absent seat — the caller decides whether the panel still has a
12285/// quorum. An empty `roster` disables handover: failures are nudged as they
12286/// always were, and a quota is simply lost. A reply that fails to parse or
12287/// validate is the prompt's doing and is only ever nudged, never handed over.
12288///
12289/// The returned [`SeatState`] names the agent that answered (or tried last).
12290#[allow(clippy::too_many_arguments)]
12291async fn ask_json_wave<T>(
12292    jobs: Vec<SeatJob>,
12293    sem: Arc<Semaphore>,
12294    retries: usize,
12295    roster: &[AgentSpec],
12296    ctx: &WaveCtx<'_>,
12297    losses: &mut Vec<QuotaLoss>,
12298    state: &mut RunState,
12299    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12300) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12301where
12302    T: serde::de::DeserializeOwned + Send + 'static,
12303{
12304    ask_wave_with(
12305        jobs,
12306        sem,
12307        retries,
12308        roster,
12309        ctx,
12310        losses,
12311        state,
12312        &|text: &str| {
12313            let v = verdict::extract_json::<T>(text)?;
12314            validate(&v)?;
12315            Ok(v)
12316        },
12317    )
12318    .await
12319}
12320
12321/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12322/// a node whose answer is prose (deliberation) shares the same handover,
12323/// failure classification, quota bookkeeping and bounds instead of a copy.
12324///
12325/// A seat handed to another roster agent is sent the job's `handover` prompt
12326/// (when it has one) rather than `prompt`: the new agent has no session, so a
12327/// resume-style prompt would be incomplete. That holds for the handover ask
12328/// and for every nudge to that agent whose `has_context` is false.
12329#[allow(clippy::too_many_arguments)]
12330async fn ask_wave_with<T>(
12331    jobs: Vec<SeatJob>,
12332    sem: Arc<Semaphore>,
12333    retries: usize,
12334    roster: &[AgentSpec],
12335    ctx: &WaveCtx<'_>,
12336    losses: &mut Vec<QuotaLoss>,
12337    state: &mut RunState,
12338    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12339) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12340where
12341    T: Send + 'static,
12342{
12343    let n = jobs.len();
12344    let originals: Vec<SeatJob> = jobs;
12345    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12346    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12347    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12348    // answer, N once it has gone through N nudges. Read back once this
12349    // returns, so a caller building a history record (`ReviewRecord`) can
12350    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12351    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12352    // field's own doc.
12353    let mut nudges: Vec<usize> = vec![0; n];
12354    // The agent now occupying each seat, the ids it has already been through,
12355    // where in the roster the walk began, the class of the last failure, and
12356    // the stem word of a handover not yet asked (full prompt, full budget).
12357    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12358    let mut tried: Vec<BTreeSet<String>> = specs
12359        .iter()
12360        .map(|s| BTreeSet::from([s.id.clone()]))
12361        .collect();
12362    let starts: Vec<usize> = specs
12363        .iter()
12364        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12365        .collect();
12366    let carry = ctx.carry_seats && !roster.is_empty();
12367    // Carried across rounds: ids that failed the seat earlier, and how the
12368    // last failure went (so a repeat of it is not handed over again).
12369    let carried: Vec<BTreeSet<String>> = originals
12370        .iter()
12371        .map(|j| {
12372            state
12373                .seat_history
12374                .get(&j.seat.key)
12375                .filter(|_| carry)
12376                .map(|h| h.failed.clone())
12377                .unwrap_or_default()
12378        })
12379        .collect();
12380    let mut prev: Vec<Option<FailClass>> = originals
12381        .iter()
12382        .map(|j| {
12383            state
12384                .seat_history
12385                .get(&j.seat.key)
12386                .filter(|_| carry)
12387                .and_then(|h| h.last_fail.clone())
12388        })
12389        .collect();
12390    let next_agent =
12391        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12392            let others: BTreeSet<String> = specs
12393                .iter()
12394                .enumerate()
12395                .filter(|(j, _)| *j != i)
12396                .map(|(_, s)| s.id.clone())
12397                .collect();
12398            pick_successor(
12399                roster,
12400                starts[i],
12401                tried,
12402                carry.then(|| &carried[i]),
12403                &others,
12404            )
12405            .cloned()
12406        };
12407    let mut fresh: Vec<Option<String>> = vec![None; n];
12408    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12409    let mut pending: Vec<usize> = (0..n).collect();
12410
12411    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12412    // asks: an agent with a successor is asked once and handed over, and only
12413    // a seat with no successor spends `retries` nudges on the same agent. This
12414    // only guarantees the loop's own termination whatever those say.
12415    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12416    for round in 0..max_rounds {
12417        if pending.is_empty() {
12418            break;
12419        }
12420        let mut batch = Vec::with_capacity(pending.len());
12421        let mut renudged: Vec<&str> = Vec::new();
12422        for &i in &pending {
12423            let src = &originals[i];
12424            // A seat now held by another agent than the job named has no
12425            // session of its own: it gets the full-context prompt whenever
12426            // it is asked in full (the handover ask, a nudge it cannot
12427            // resume).
12428            let full: &str = match &src.handover {
12429                Some(h) if specs[i].id != src.spec.id => h,
12430                _ => &src.prompt,
12431            };
12432            // The prompt and the budget are one decision: a nudge restates
12433            // finished work, a re-sent prompt redoes it.
12434            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12435                (
12436                    full.to_owned(),
12437                    src.timeout,
12438                    format!("{}-{word}-{}", src.stem, specs[i].id),
12439                )
12440            } else if nudges[i] == 0 {
12441                (full.to_owned(), src.timeout, src.stem.clone())
12442            } else {
12443                renudged.push(src.seat.key.as_str());
12444                let why = done[i]
12445                    .as_ref()
12446                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12447                    .unwrap_or_else(|| "no parsable answer".to_owned());
12448                let nudge = prompt::nudge(&why);
12449                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12450                let prompt = if nudged {
12451                    nudge
12452                } else {
12453                    format!("{full}\n\n---\n\n{nudge}")
12454                };
12455                (
12456                    prompt,
12457                    retry_budget(src.timeout, nudged),
12458                    format!("{}-retry{}", src.stem, nudges[i]),
12459                )
12460            };
12461            batch.push(SeatJob {
12462                spec: specs[i].clone(),
12463                seat: seats[i].clone(),
12464                cwd: src.cwd.clone(),
12465                prompt,
12466                timeout,
12467                allow_write: src.allow_write,
12468                sessions: src.sessions,
12469                artifacts: src.artifacts.clone(),
12470                stem,
12471                handover: None,
12472            });
12473        }
12474
12475        if !renudged.is_empty() {
12476            state.event(
12477                ctx.node,
12478                format!("retry {round}: re-asking {}", renudged.join(", ")),
12479            );
12480        }
12481        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12482        let mut still = Vec::new();
12483        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12484            seats[i] = seat;
12485            // No agent was asked: nothing to hand over, nudge, remember or
12486            // charge. The caller sees `resource_block` and stops the node.
12487            if let AgentOutcome::ResourceBlocked(why) = &out {
12488                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12489                continue;
12490            }
12491            let class = FailClass::of(&out);
12492            // A dropped stream is nudged first (the conversation is still
12493            // there to pick up); only a seat whose nudges are spent hands over.
12494            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12495                && nudges[i] < retries
12496                && !roster.is_empty();
12497            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12498                let next = should_hand_over(prev[i].as_ref(), &cur)
12499                    .then(|| next_agent(i, &tried[i], &specs))
12500                    .flatten();
12501                if carry {
12502                    let h = state
12503                        .seat_history
12504                        .entry(originals[i].seat.key.clone())
12505                        .or_default();
12506                    h.failed.insert(specs[i].id.clone());
12507                    h.last_fail = Some(cur.clone());
12508                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12509                        h.last_ok = None;
12510                    }
12511                    // Saved before the next agent is asked, so a restart in
12512                    // between does not forget who failed.
12513                    if let Err(e) = state.save() {
12514                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12515                    }
12516                }
12517                if let Some(next) = next {
12518                    record_handover(
12519                        state,
12520                        ctx.node,
12521                        &originals[i].seat.key,
12522                        &specs[i].id,
12523                        &next.id,
12524                        &cur,
12525                        &fail_reason(&out),
12526                    );
12527                    tried[i].insert(next.id.clone());
12528                    prev[i] = Some(cur.clone());
12529                    seats[i] =
12530                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12531                    specs[i] = next;
12532                    fresh[i] = Some(cur.stem_word().to_owned());
12533                    nudges[i] = 0;
12534                    done[i] = Some(Err(anyhow::anyhow!(
12535                        "handed over after: {}",
12536                        fail_reason(&out)
12537                    )));
12538                    still.push(i);
12539                    continue;
12540                }
12541            }
12542            if carry
12543                && !nudge_first
12544                && let Some(cur) = class.clone()
12545            {
12546                // The chain ended here (no successor, or a repeated failure).
12547                let h = state
12548                    .seat_history
12549                    .entry(originals[i].seat.key.clone())
12550                    .or_default();
12551                h.failed.insert(specs[i].id.clone());
12552                h.last_fail = Some(cur);
12553            }
12554            let parsed = match out {
12555                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12556                AgentOutcome::Quota(o) => {
12557                    last_quota[i] = o.quota.clone();
12558                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12559                }
12560                // Not a parseable answer: the nudge loop re-asks it, which is
12561                // exactly what a dropped stream needs. Just don't hand its raw
12562                // error JSON to `extract_json`.
12563                AgentOutcome::Dropped(o) => {
12564                    let why = o
12565                        .dropped
12566                        .as_ref()
12567                        .map(|d| d.why.as_str())
12568                        .unwrap_or("the CLI ended the stream without delivering its answer");
12569                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12570                }
12571                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12572                    Err(anyhow::anyhow!(e))
12573                }
12574            };
12575            let quota = class == Some(FailClass::Quota);
12576            let failed = parsed.is_err();
12577            if !failed && matches!(ctx.node, "judge" | "vote") {
12578                // A validated answer restores this seat's quorum presence,
12579                // including on the normal path after an all-seat block.
12580                state
12581                    .quota
12582                    .retain(|loss| loss.seat != originals[i].seat.key);
12583            }
12584            done[i] = Some(parsed);
12585            if carry && !failed {
12586                let h = state
12587                    .seat_history
12588                    .entry(originals[i].seat.key.clone())
12589                    .or_default();
12590                h.failed.remove(&specs[i].id);
12591                h.last_ok = Some(specs[i].id.clone());
12592                h.last_fail = None;
12593            }
12594            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12595            // fail the same way; and never re-ask a seat that already parsed.
12596            // A failed agent that still has a successor is not re-asked
12597            // either: the handover was its remedy and has just been refused
12598            // (the chain stops on a repeated failure class). A seat with no
12599            // successor left (a single-agent roster, the roster's tail, or an
12600            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12601            let agent_failure = class.is_some()
12602                && !nudge_first
12603                && !roster.is_empty()
12604                && next_agent(i, &tried[i], &specs).is_some();
12605            if failed && !quota && !agent_failure && nudges[i] < retries {
12606                nudges[i] += 1;
12607                still.push(i);
12608            }
12609        }
12610        pending = still;
12611    }
12612
12613    // One loss per seat whose chain ended on a quota: the intermediate ones
12614    // were absorbed by a handover and are not losses.
12615    for (i, q) in last_quota.into_iter().enumerate() {
12616        if let Some(quota) = q {
12617            losses.push(QuotaLoss::from_report(
12618                originals[i].seat.key.clone(),
12619                ctx.node,
12620                Some(&quota),
12621            ));
12622        }
12623    }
12624
12625    // A stalled quorum already has its own recovery checkpoint. Refresh
12626    // its missing seats before deciding whether it can resume.
12627    if state.status != RunStatus::Stalled
12628        && ctx.node != "deliberate"
12629        && n > 0
12630        && losses.len() == n
12631        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12632    {
12633        block_machine_outage(state, ctx.node, losses);
12634        state.quota.append(losses);
12635    }
12636
12637    seats
12638        .into_iter()
12639        .zip(done)
12640        .zip(nudges)
12641        .map(|((seat, res), attempts)| {
12642            (
12643                seat,
12644                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12645                attempts,
12646            )
12647        })
12648        .collect()
12649}
12650
12651/// A node with no available agent has no task verdict. Preserve the node
12652/// checkpoint and record why a subsequent explicit resume is needed.
12653pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12654    let mut auth: Vec<_> = losses
12655        .iter()
12656        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12657        .map(|loss| loss.agent.clone())
12658        .collect();
12659    auth.sort();
12660    auth.dedup();
12661    let (kind, detail) = if auth.is_empty() {
12662        (
12663            "agent usage limit",
12664            "All seats reached their agent usage limits; resume after usage is available"
12665                .to_owned(),
12666        )
12667    } else {
12668        (
12669            "agent authentication",
12670            format!(
12671                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12672                auth.join(", ")
12673            ),
12674        )
12675    };
12676    state.resource_block = Some(crate::run::ResourceBlock {
12677        node: node.to_owned(),
12678        kind: kind.to_owned(),
12679        cause: crate::run::ResourceBlockCause::Other,
12680        detail: detail.clone(),
12681        at: Timestamp::now(),
12682    });
12683    state.event(node, detail);
12684}
12685
12686/// Did the wave end without asking any agent (see [`block_wave`])?
12687fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12688    results
12689        .iter()
12690        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12691}
12692
12693/// Settle a wave that never spawned anything: every job answers
12694/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12695/// else about the seat (session, history, quota) is touched.
12696fn block_wave(
12697    jobs: Vec<SeatJob>,
12698    state: &mut RunState,
12699    node: &str,
12700    attempt: usize,
12701    why: &str,
12702) -> Vec<(usize, SeatState, AgentOutcome)> {
12703    state.resource_wait = None;
12704    state
12705        .active
12706        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12707    if let Err(e) = state.save() {
12708        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12709    }
12710    jobs.into_iter()
12711        .enumerate()
12712        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12713        .collect()
12714}
12715
12716/// Acquire the shared build cache's lease, waiting out contention within
12717/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12718/// unbounded wait is never acceptable).
12719///
12720/// A first, non-blocking check happens before ever waiting; if it finds the
12721/// lease busy, that fact is logged as a `verify` event *and* flushed with
12722/// [`RunState::save`] immediately — not only once the wait finally succeeds
12723/// or gives up — so a `magi show` run by a different process while this one
12724/// is still waiting reads a `run.json` that says so, rather than whatever it
12725/// looked like before the wait started. The same applies to the terminal
12726/// failure: logged and saved before this returns `Err`, so a caller that
12727/// could not get the lease at all still leaves a legible record of why.
12728async fn acquire_cache_lease(
12729    state: &mut RunState,
12730    cache_dir: &Path,
12731    owner: &crate::cache::Owner,
12732    budget: Duration,
12733    node: &str,
12734    context: &str,
12735    cancel: &(dyn Fn() -> bool + Sync),
12736) -> Result<Option<crate::cache::Guard>> {
12737    let home = crate::run::home();
12738    let kind = if crate::build_target::isolated(&state.config) {
12739        crate::build_target::KIND
12740    } else {
12741        "shared build cache"
12742    };
12743    let started = Instant::now();
12744    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12745        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12746        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12747        Err(e) => {
12748            state.event(
12749                "verify",
12750                format!(
12751                    "{context}: could not check the {kind} at {}: {e:#}",
12752                    cache_dir.display()
12753                ),
12754            );
12755            if let Err(e2) = state.save() {
12756                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12757            }
12758            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12759        }
12760    };
12761    state.event(
12762        "verify",
12763        format!(
12764            "{context}: waiting for the {kind} at {} ({})",
12765            cache_dir.display(),
12766            busy.describe()
12767        ),
12768    );
12769    // Seats of this node are waiting, not running: say so, so the countdown a
12770    // reader sees only ever measures an agent that has been spawned.
12771    state.resource_wait = Some(crate::run::ResourceWait {
12772        node: context.to_owned(),
12773        kind: kind.to_owned(),
12774        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12775        since: Timestamp::now(),
12776        limit_secs: budget.as_secs(),
12777    });
12778    if let Err(e) = state.save() {
12779        tracing::warn!("could not persist a cache wait: {e:#}");
12780    }
12781    let remaining = budget.saturating_sub(started.elapsed());
12782    let waited = crate::cache::wait_for_unless(
12783        &home,
12784        cache_dir,
12785        owner,
12786        remaining,
12787        Duration::from_secs(5),
12788        cancel,
12789    )
12790    .await;
12791    state.resource_wait = None;
12792    let cause = match &waited {
12793        Ok(Some(_)) => None,
12794        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12795        Err(error)
12796            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12797        {
12798            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12799                target: cache_dir.to_owned(),
12800                waited_secs: started.elapsed().as_secs(),
12801                limit_secs: budget.as_secs(),
12802            })
12803        }
12804        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12805            Some(crate::run::ResourceBlockCause::Timeout {
12806                waited_secs: started.elapsed().as_secs(),
12807                limit_secs: budget.as_secs(),
12808            })
12809        }
12810        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12811    };
12812    if let Some(cause) = cause {
12813        let detail = match &waited {
12814            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12815            Err(error) => format!("{error:#}"),
12816        };
12817        state.resource_block = Some(crate::run::ResourceBlock {
12818            cause,
12819            node: node.to_owned(),
12820            kind: kind.into(),
12821            detail: format!("{}: {detail}", cache_dir.display()),
12822            at: Timestamp::now(),
12823        });
12824        state.event(
12825            "resource",
12826            state.resource_block.as_ref().unwrap().description(),
12827        );
12828    }
12829    if let Err(error) = state.save() {
12830        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12831    }
12832    waited
12833}
12834
12835/// The lease state could not be read at all (unreadable lease file, a
12836/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12837/// known to be contended, so a wave degrades to running without a shared cache
12838/// instead of stopping on a hold that [`crate::triage`] could never release.
12839#[derive(Debug)]
12840struct CacheCheckError(String);
12841
12842impl std::fmt::Display for CacheCheckError {
12843    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12844        f.write_str(&self.0)
12845    }
12846}
12847
12848impl std::error::Error for CacheCheckError {}
12849
12850/// Keep a specific acquisition outcome when the caller adds command evidence.
12851fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12852    let kind = if crate::build_target::isolated(&state.config) {
12853        crate::build_target::KIND
12854    } else {
12855        "shared build cache"
12856    };
12857    state
12858        .resource_block
12859        .get_or_insert_with(|| crate::run::ResourceBlock {
12860            cause: crate::run::ResourceBlockCause::Other,
12861            node: node.to_owned(),
12862            kind: kind.into(),
12863            detail: format!("{error:#}"),
12864            at: Timestamp::now(),
12865        });
12866    if let Err(error) = state.save() {
12867        tracing::warn!("could not persist cache resource block: {error:#}");
12868    }
12869}
12870
12871tokio::task_local! {
12872    static VERIFY_TARGET: PathBuf;
12873}
12874
12875/// Run `body` — a verify command batch — while holding the shared build
12876/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12877/// never interleave with another borrower's build against the same
12878/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12879/// timeout, or a human's own `magi review`. See the `cache` module doc for
12880/// why this matters more than Cargo's own per-target locking covers — two
12881/// *different* worktrees building the same package name/version into one
12882/// cache directory is a staleness bug, not a lock contention one.
12883///
12884/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12885/// agent waves do. Repository scheduling also has its own bounded,
12886/// cancellable resource-wait policy. Contention must not consume the
12887/// verification budget: `body` receives the full `budget` after both leases
12888/// are acquired and the cache is fresh. Without a shared cache, only
12889/// repository coordination is acquired before handing over the full budget.
12890///
12891/// A lease that cannot be acquired within the resource wait is reported as a single
12892/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12893/// verification — the same shape a spawn failure already takes in
12894/// [`run_commands`], so a caller need not special-case it.
12895#[allow(clippy::too_many_arguments)]
12896async fn with_cache_lease<'s, F, Fut>(
12897    state: &'s mut RunState,
12898    cache_dir: Option<&Path>,
12899    node: &str,
12900    seat: &str,
12901    worktree: &Path,
12902    head: &str,
12903    budget: Duration,
12904    context: &str,
12905    wait: &crate::repo_lock::WaitPolicy,
12906    body: F,
12907) -> Result<(Vec<CommandOutcome>, bool)>
12908where
12909    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12910    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12911{
12912    // Match editing waves: cache first, repository second. In particular,
12913    // pre_gate must never hold the repository while waiting for a wave's cache.
12914    let started = Instant::now();
12915    let home = crate::run::home();
12916    let isolated = crate::build_target::isolated(&state.config);
12917    let planned_target = if isolated {
12918        let plan = (|| -> Result<PathBuf> {
12919            crate::build_target::supports(&state.config)?;
12920            crate::build_target::resolve(&home, worktree)
12921        })();
12922        match plan {
12923            Ok(path) => Some(path),
12924            Err(error) => {
12925                record_cache_error(state, node, &error);
12926                return Ok((
12927                    vec![CommandOutcome {
12928                        command: "(planning isolated build cache)".into(),
12929                        code: None,
12930                        output_tail: format!("{error:#}"),
12931                        duration_ms: 0,
12932                        resource_blocked: true,
12933                        ..Default::default()
12934                    }],
12935                    false,
12936                ));
12937            }
12938        }
12939    } else {
12940        None
12941    };
12942    let cache_dir = planned_target.as_deref().or(cache_dir);
12943    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12944    let guard = if let Some(cache_dir) = cache_dir {
12945        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12946        match acquire_cache_lease(
12947            state,
12948            cache_dir,
12949            &owner,
12950            resource_limit,
12951            node,
12952            context,
12953            &|| wait.cancelled(),
12954        )
12955        .await
12956        .and_then(|g| {
12957            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12958        }) {
12959            Ok(g) => Some(g),
12960            Err(e) => {
12961                record_cache_error(state, node, &e);
12962                return Ok((
12963                    vec![CommandOutcome {
12964                        command: if isolated {
12965                            "(waiting for the isolated build cache)"
12966                        } else {
12967                            "(waiting for the shared build cache)"
12968                        }
12969                        .into(),
12970                        code: None,
12971                        output_tail: e.to_string(),
12972                        duration_ms: started.elapsed().as_millis() as u64,
12973                        resource_blocked: true,
12974                        ..Default::default()
12975                    }],
12976                    false,
12977                ));
12978            }
12979        }
12980    } else {
12981        None
12982    };
12983    let _coordination = coordinate_operation(state, worktree, wait).await?;
12984    if let Some(path) = &planned_target {
12985        state.event(node, format!("isolated build target: {}", path.display()));
12986    }
12987    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12988        let identity = crate::cache::Identity::new(worktree, head);
12989        let fresh = crate::cache::ensure_fresh(
12990            &home,
12991            cache_dir,
12992            &identity,
12993            &state.config.verify.cargo_targets(),
12994        );
12995        if let Err(e) = fresh {
12996            record_cache_error(state, node, &e);
12997            state.event(
12998                "verify",
12999                format!(
13000                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
13001                    worktree.display(),
13002                    short(head)
13003                ),
13004            );
13005            if let Some(guard) = guard {
13006                guard.release();
13007            }
13008            return Ok((
13009                vec![CommandOutcome {
13010                    command: "(confirming the build cache is fresh)".into(),
13011                    code: None,
13012                    output_tail: e.to_string(),
13013                    duration_ms: started.elapsed().as_millis() as u64,
13014                    resource_blocked: true,
13015                    ..Default::default()
13016                }],
13017                false,
13018            ));
13019        }
13020    }
13021    let future = body(state, budget);
13022    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
13023        VERIFY_TARGET.scope(target, future).await
13024    } else {
13025        future.await
13026    };
13027    if !timed_out_pids.is_empty() {
13028        wait_for_timed_out_children_to_die(&timed_out_pids).await;
13029    }
13030    // Drop repository coordination before releasing the cache, reversing the
13031    // acquisition order. A cancelled/error future also drops both guards.
13032    drop(_coordination);
13033    if let Some(guard) = guard {
13034        guard.release();
13035    }
13036    Ok((outcomes, retried))
13037}
13038
13039/// Poll `pids` — commands [`run_commands`] reports as still running when its
13040/// own timeout elapsed — until every one is confirmed gone, or
13041/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
13042///
13043/// Real confirmation where confirmation is possible, not a substitute for
13044/// full process-tree observation: a grandchild the timed-out process spawned
13045/// and that survives independently of it is invisible to a pid check the
13046/// same way it always was, and continuing to observe and collect *that*
13047/// stays a different piece of work with its own owner. This only narrows a
13048/// fixed blind wait into an actual check of the pids this process does know
13049/// about.
13050async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
13051    wait_for_pids_with(
13052        pids,
13053        crate::proc::pid_alive,
13054        LEASE_RELEASE_POLL,
13055        LEASE_RELEASE_MAX_WAIT,
13056    )
13057    .await;
13058}
13059
13060/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
13061/// interval and ceiling supplied by the caller, so the polling *logic* -
13062/// returns as soon as every pid reports dead, gives up at the ceiling
13063/// otherwise - is testable on millisecond durations without asking the real
13064/// OS about a pid at all.
13065async fn wait_for_pids_with<F: Fn(u32) -> bool>(
13066    pids: &[u32],
13067    alive: F,
13068    poll: Duration,
13069    max_wait: Duration,
13070) {
13071    let deadline = Instant::now() + max_wait;
13072    loop {
13073        if pids.iter().all(|&pid| !alive(pid)) {
13074            return;
13075        }
13076        if Instant::now() >= deadline {
13077            return;
13078        }
13079        tokio::time::sleep(poll).await;
13080    }
13081}
13082
13083/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
13084/// admission that it could not even get a verify command to run, as opposed
13085/// to evidence the command actually produced? A caller that would otherwise
13086/// read a resource-blocked outcome as a red command must check this first:
13087/// see [`Runner::gate`], which retries rather than records `Blocked` when
13088/// this is true.
13089fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
13090    outcomes.iter().any(|o| o.resource_blocked)
13091}
13092
13093/// What [`Runner::gate_fix_round`] decided.
13094pub(crate) enum GateFix {
13095    /// The tree changed and `verify.e2e` is still green: run the gate again.
13096    Retry,
13097    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
13098    /// last failure stands and the run ends blocked.
13099    Stop,
13100    /// `verify.e2e` could not run after the fix (magi's own contention):
13101    /// decide nothing now, a later reentry retries.
13102    Defer,
13103}
13104
13105/// Is every red command in `outcomes` an ordinary failure the code could
13106/// explain: it ran, exited non-zero, and said something?
13107///
13108/// A timeout, a spawn failure and a killed process all leave `code` `None`;
13109/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
13110/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
13111/// what the command is stays the gate's business.
13112pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
13113    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13114    red.peek().is_some()
13115        && red.all(|o| {
13116            !o.resource_blocked
13117                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13118                && !o.output_tail.trim().is_empty()
13119        })
13120}
13121
13122/// Describe one verify command's outcome for the event log, distinguishing a
13123/// build/link failure — the toolchain never produced a binary to run — from
13124/// an actual test failure, since only the latter is a verdict on the patch.
13125fn e2e_outcome_label(o: &CommandOutcome) -> String {
13126    if o.ok() {
13127        return "pass".to_owned();
13128    }
13129    let reason = if o.build_failed() {
13130        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
13131    } else {
13132        format!("FAIL ({:?})", o.code)
13133    };
13134    format!(
13135        "{reason}\n{}",
13136        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13137    )
13138}
13139
13140/// Does `outcomes` hold a failure worth one more run on the same commit?
13141///
13142/// Only an ordinary test result qualifies: every red command ran, exited
13143/// non-zero and said which way (not a build/link failure, a timeout or kill,
13144/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
13145/// evidence about the machine or the toolchain, never about a flaky test.
13146fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
13147    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13148    red.peek().is_some()
13149        && !verify_inconclusive(outcomes)
13150        && red.all(|o| {
13151            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13152        })
13153}
13154
13155/// Run `verify.e2e`, retrying once if the first attempt could not build or
13156/// link — a build/link failure is frequently a race against a shared
13157/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
13158/// `verify` event per command, tagged with `context` (normally `"round N"`)
13159/// so the call sites that need this — the ordinary per-round leg in
13160/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
13161/// will ever call a round green, `verify_current_head` and the gate-repair
13162/// check — read identically in the event log.
13163///
13164/// A failure that is a test result (see [`rerunnable_failure`]) is believed
13165/// only after the failed commands have run once more on the same commit, in
13166/// the same worktree and — because the caller holds it around this whole
13167/// function — under the same cache lease, with a full `timeout` of their own
13168/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
13169/// flake: the head is verified, the first failure is recorded and filed
13170/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
13171/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
13172/// preserving bounded evidence and artifact references for both attempts;
13173/// it claims a matching reproduction only when both attempts yield identical
13174/// confirmed terminal test failures. One verification is therefore run at most
13175/// three times: the build/link retry, then this one rerun. `round` is the
13176/// review round the verification belongs to, if any.
13177async fn run_e2e_with_retry(
13178    state: &mut RunState,
13179    shell: &[String],
13180    commands: &[String],
13181    worktree: &Path,
13182    timeout: Duration,
13183    context: &str,
13184    round: Option<usize>,
13185) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
13186    let (mut e2e, mut timed_out_pids) = run_commands(
13187        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
13188    )
13189    .await;
13190    for o in &e2e {
13191        state.event(
13192            "verify",
13193            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
13194        );
13195    }
13196    // A build/link failure is not a verdict on the patch — it is frequently a
13197    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
13198    // one retry before letting a red like that decide the round.
13199    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
13200    if verify_retried {
13201        state.event(
13202            "verify",
13203            format!(
13204                "{context}: verify could not build/link, not a test result — retrying once \
13205                 before concluding"
13206            ),
13207        );
13208        let retried = run_commands(
13209            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
13210        )
13211        .await;
13212        e2e = retried.0;
13213        // Both attempts' timeouts matter, not just the last one: the first
13214        // attempt's descendants may still be alive alongside the retry's.
13215        timed_out_pids.extend(retried.1);
13216        for o in &e2e {
13217            state.event(
13218                "verify",
13219                format!(
13220                    "{context}: retry `{}` -> {}",
13221                    o.command,
13222                    e2e_outcome_label(o)
13223                ),
13224            );
13225        }
13226    }
13227    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13228        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13229        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13230        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13231        state.event(
13232            "verify",
13233            format!(
13234                "{context}: {} failed with a test result — running it once more on the same \
13235                 commit {} before deciding",
13236                rerun_commands
13237                    .iter()
13238                    .map(|c| format!("`{c}`"))
13239                    .collect::<Vec<_>>()
13240                    .join(", "),
13241                short(&head)
13242            ),
13243        );
13244        let (second, pids) = run_commands(
13245            state,
13246            "verify",
13247            "e2e",
13248            1 + usize::from(verify_retried),
13249            shell,
13250            &rerun_commands,
13251            worktree,
13252            timeout,
13253        )
13254        .await;
13255        timed_out_pids.extend(pids);
13256        for o in &second {
13257            state.event(
13258                "verify",
13259                format!(
13260                    "{context}: rerun `{}` -> {}",
13261                    o.command,
13262                    e2e_outcome_label(o)
13263                ),
13264            );
13265        }
13266        for (slot, &i) in failed.iter().enumerate() {
13267            let Some(again) = second.get(slot) else {
13268                break;
13269            };
13270            let first = std::mem::replace(&mut e2e[i], again.clone());
13271            if again.ok() {
13272                let signature = crate::flake::signature(&first.output_tail, first.code);
13273                let flake = crate::run::VerifyFlake {
13274                    round,
13275                    context: context.to_owned(),
13276                    head: head.clone(),
13277                    command: first.command.clone(),
13278                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13279                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13280                    at: Timestamp::now(),
13281                    task: None,
13282                    filed: false,
13283                    filing_error: None,
13284                };
13285                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13286            } else if !again.resource_blocked {
13287                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13288                let message = crate::verify_evidence::rerun_event_message(
13289                    context,
13290                    &e2e[i].command,
13291                    &comparison,
13292                );
13293                e2e[i].rerun_comparison = Some(comparison);
13294                state.event("verify", message);
13295            }
13296        }
13297    }
13298    (e2e, verify_retried, timed_out_pids)
13299}
13300
13301/// Run configured shell commands in `cwd`, in order. The second element is
13302/// the pid of every command that hit `timeout` and was still running when
13303/// this stopped waiting on it (best-effort: `None` when the platform did not
13304/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13305/// that releases a shared resource afterward needs to know.
13306///
13307/// Records `task` into [`RunState::active`] at every command boundary
13308/// (`RunState::task_command`) and clears it once the whole list has run
13309/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13310/// for minutes with no seat and no output of its own to show for it (see
13311/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13312/// apart from "not yet run" without this), and this is the only place that
13313/// knows which command is running right now and how many are left. Three
13314/// saves per command — start, not per second — matching the same "only at a
13315/// boundary" rule [`wave`] already follows for seats.
13316#[allow(clippy::too_many_arguments)]
13317async fn run_commands(
13318    state: &mut RunState,
13319    node: &str,
13320    task: &str,
13321    attempt: usize,
13322    shell: &[String],
13323    commands: &[String],
13324    cwd: &Path,
13325    timeout: Duration,
13326) -> (Vec<CommandOutcome>, Vec<u32>) {
13327    let isolated = crate::build_target::isolated(&state.config);
13328    if isolated && let Some(block) = &state.resource_block {
13329        return (
13330            vec![CommandOutcome {
13331                command: "(isolated build admission)".into(),
13332                code: None,
13333                output_tail: block.description(),
13334                duration_ms: 0,
13335                resource_blocked: true,
13336                ..Default::default()
13337            }],
13338            Vec::new(),
13339        );
13340    }
13341    if commands.is_empty() {
13342        // Nothing to mark as running and nothing to clear — an empty list
13343        // means "not configured", and touching `active` (or the disk) over
13344        // that would be a write for every round of a repo with no
13345        // `verify.e2e` / `verify.gate` commands at all.
13346        return (Vec::new(), Vec::new());
13347    }
13348    let mut out = Vec::new();
13349    let mut timed_out_pids = Vec::new();
13350    let total = commands.len();
13351    for (idx, command) in commands.iter().enumerate() {
13352        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13353        if let Err(e) = state.save() {
13354            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13355        }
13356        let started = Instant::now();
13357        let mut cmd = tokio::process::Command::new(&shell[0]);
13358        cmd.quiet();
13359        // Verify the checkout as a standalone caller. Worker ownership and
13360        // pinned executable selection belong to this driver, not to tests or
13361        // tools it runs. Preserve home/seat context and Running's containment.
13362        for key in crate::worker::INVOCATION_ENV {
13363            cmd.env_remove(key);
13364        }
13365        cmd.env_remove(crate::build_id::EXPECT_ENV);
13366        cmd.args(&shell[1..])
13367            .current_dir(cwd)
13368            .stdin(std::process::Stdio::null())
13369            .stdout(std::process::Stdio::piped())
13370            .stderr(std::process::Stdio::piped())
13371            .kill_on_drop(true);
13372        let mut outputs = Vec::new();
13373        let mut cache = None;
13374        let home = crate::run::home();
13375        if isolated {
13376            let prepared = (|| -> Result<()> {
13377                let plan = crate::build_target::command::plan(command)?;
13378                if let Some(dir) = &plan.dir {
13379                    cmd.current_dir(crate::build_target::command::resolve_dir(cwd, dir)?);
13380                }
13381                cmd.arg(plan.script);
13382                Ok(())
13383            })();
13384            if let Err(e) = prepared {
13385                out.push(CommandOutcome {
13386                    command: command.clone(),
13387                    code: Some(1),
13388                    output_tail: format!("{e:#}"),
13389                    duration_ms: started.elapsed().as_millis() as u64,
13390                    ..Default::default()
13391                });
13392                continue;
13393            }
13394        }
13395        let head = if isolated {
13396            Some(git::rev_parse(cwd, "HEAD").await)
13397        } else {
13398            None
13399        };
13400        let protected = (|| -> Result<()> {
13401            crate::incremental::configure(&mut cmd, cwd)?;
13402            cache = if isolated {
13403                let target = VERIFY_TARGET
13404                    .try_with(Clone::clone)
13405                    .context("isolated verification has no target lease")?;
13406                crate::build_target::command::configure(&mut cmd, &target)?;
13407                Some(target)
13408            } else {
13409                crate::build_target::command::clear(&mut cmd)?;
13410                cmd.arg(command);
13411                state.config.cache_dir()
13412            };
13413            let mut paths = vec![cwd.to_owned()];
13414            if let Some(cache) = &cache {
13415                paths.push(cache.clone());
13416            }
13417            let admit = if isolated {
13418                crate::retention::OutputLease::admit_isolated
13419            } else {
13420                crate::retention::OutputLease::admit
13421            };
13422            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13423            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13424                outputs.push(guard);
13425            }
13426            if let Some(cache) = &cache {
13427                outputs.push(crate::retention::OutputLease::cache(
13428                    &crate::run::home(),
13429                    cache,
13430                    false,
13431                )?);
13432                if let Some(head) = head {
13433                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13434                    if task == "pre_gate" {
13435                        crate::cache::invalidate_identity(&home, cache);
13436                    }
13437                }
13438            }
13439            Ok(())
13440        })();
13441        if let Err(e) = protected {
13442            let detail = format!("execution admission unavailable: {e:#}");
13443            state.resource_block = Some(crate::run::ResourceBlock {
13444                cause: crate::run::ResourceBlockCause::Other,
13445                node: node.to_owned(),
13446                kind: if detail.contains("disk admission") {
13447                    "disk admission"
13448                } else {
13449                    "output ownership"
13450                }
13451                .to_owned(),
13452                detail: detail.clone(),
13453                at: Timestamp::now(),
13454            });
13455            out.push(CommandOutcome {
13456                command: command.clone(),
13457                code: None,
13458                output_tail: detail,
13459                duration_ms: 0,
13460                resource_blocked: true,
13461                ..Default::default()
13462            });
13463            break;
13464        }
13465        let spawned = if isolated {
13466            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13467        } else {
13468            crate::seat_process::Running::spawn(cmd, None, outputs)
13469        };
13470        let (code, out_text, err_text, body) = match spawned {
13471            Ok(mut running) => {
13472                let pid = running.child().id();
13473                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13474                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13475                let mut paths = vec![cwd.to_owned()];
13476                if let Some(cache) = cache {
13477                    paths.push(cache);
13478                }
13479                let mut pressure = None;
13480                let status = tokio::select! {
13481                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13482                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13483                        pressure = Some(reason); None
13484                    }
13485                };
13486                let (code, failure) = match status {
13487                    Some(Ok(Ok(status))) => (
13488                        status.code(),
13489                        status
13490                            .code()
13491                            .is_none()
13492                            .then(|| format!("command terminated: {status}")),
13493                    ),
13494                    Some(Ok(Err(error))) => {
13495                        (None, Some(format!("failed waiting for command: {error}")))
13496                    }
13497                    Some(Err(_)) => {
13498                        // Leased cleanup confirms process-tree death itself.
13499                        // Unleased commands still need the caller's PID check
13500                        // after kill-on-drop, before releasing cache ownership.
13501                        if !running.coordinated()
13502                            && let Some(pid) = pid
13503                        {
13504                            timed_out_pids.push(pid);
13505                        }
13506                        (
13507                            None,
13508                            Some(format!("timed out after {}s", timeout.as_secs())),
13509                        )
13510                    }
13511                    None => (None, None),
13512                };
13513                running.finish().await;
13514                if let Some(reason) = pressure {
13515                    state.resource_block = Some(crate::run::ResourceBlock {
13516                        cause: crate::run::ResourceBlockCause::Other,
13517                        node: node.to_owned(),
13518                        kind: "disk pressure".to_owned(),
13519                        detail: reason.clone(),
13520                        at: Timestamp::now(),
13521                    });
13522                    out.push(CommandOutcome {
13523                        command: command.clone(),
13524                        code: None,
13525                        output_tail: reason,
13526                        duration_ms: started.elapsed().as_millis() as u64,
13527                        resource_blocked: true,
13528                        ..Default::default()
13529                    });
13530                    break;
13531                }
13532                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13533                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13534                let mut body = out_text.clone();
13535                body.push_str(&err_text);
13536                if let Some(failure) = failure {
13537                    body.push('\n');
13538                    body.push_str(&failure);
13539                }
13540                (code, out_text, err_text, body)
13541            }
13542            Err(e) if isolated => {
13543                let e = anyhow::Error::new(e)
13544                    .context(format!("could not start managed build `{}`", shell[0]));
13545                record_cache_error(state, node, &e);
13546                out.push(CommandOutcome {
13547                    command: command.clone(),
13548                    code: None,
13549                    output_tail: format!("{e:#}"),
13550                    duration_ms: 0,
13551                    resource_blocked: true,
13552                    ..Default::default()
13553                });
13554                break;
13555            }
13556            Err(e) => (
13557                None,
13558                String::new(),
13559                String::new(),
13560                format!("failed to spawn `{}`: {e}", shell[0]),
13561            ),
13562        };
13563        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13564        let mut artifact = None;
13565        if !body.is_empty() {
13566            // The full text is kept whatever the summary dropped. A fresh
13567            // name per command so a resume or retry never overwrites an
13568            // earlier run's output. A failed write changes no verdict.
13569            match crate::run::write_verification_artifact(state, task, &body) {
13570                Ok(name) => {
13571                    let rel = format!("artifacts/{name}");
13572                    if summary != body {
13573                        summary = format!("[full output: {rel}]\n{summary}");
13574                    }
13575                    artifact = Some(rel);
13576                }
13577                Err(e) => {
13578                    let warning = format!("could not save the full {task} output: {e:#}");
13579                    tracing::warn!("{warning}");
13580                    state.event(node, warning);
13581                    if summary != body {
13582                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13583                    }
13584                }
13585            }
13586        }
13587        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13588        let mut outcome = CommandOutcome {
13589            command: command.clone(),
13590            code,
13591            output_tail: summary,
13592            duration_ms: started.elapsed().as_millis() as u64,
13593            resource_blocked,
13594            artifact,
13595            failure_evidence: None,
13596            rerun_comparison: None,
13597        };
13598        if !outcome.ok() && !outcome.resource_blocked {
13599            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13600                code,
13601                outcome.build_failed(),
13602                &out_text,
13603                &err_text,
13604            ));
13605        }
13606        out.push(outcome);
13607        if resource_blocked {
13608            state.resource_block = Some(crate::run::ResourceBlock {
13609                cause: crate::run::ResourceBlockCause::Other,
13610                node: node.to_owned(),
13611                kind: "incremental cache admission".into(),
13612                detail: body,
13613                at: Timestamp::now(),
13614            });
13615            break;
13616        }
13617    }
13618    state.task_finished(task);
13619    if let Err(e) = state.save() {
13620        tracing::warn!("could not persist the end of {task}: {e:#}");
13621    }
13622    (out, timed_out_pids)
13623}
13624
13625/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13626/// section (`report::run`) and in the `merge` event this node records — for
13627/// the operator to run by hand.
13628///
13629/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13630/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13631/// merge commits", or "require linear history") rejects the push a `--no-ff`
13632/// merge would produce, which is exactly the guidance this function replaces.
13633/// `message`'s first line becomes the squash commit's subject, matching the
13634/// note `report::run` prints alongside this command — see that function for
13635/// why an explicit subject is not optional there.
13636fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13637    let repo = repo.display();
13638    match style {
13639        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13640        MergeStyle::Squash => {
13641            // The subject sits inside double quotes, and a title an agent
13642            // wrote may carry the characters that break out of them.
13643            let subject = message
13644                .lines()
13645                .next()
13646                .unwrap_or(branch)
13647                .replace(['\\', '"', '$', '`'], "");
13648            format!(
13649                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13650            )
13651        }
13652        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13653    }
13654}
13655
13656/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13657/// under the hood, rejects a `title` over 256 characters and the whole
13658/// command fails — no PR at all, for a run whose body was otherwise fine
13659/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13660/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13661/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13662/// this bound. It is a margin, not a guarantee — a title packed
13663/// with multi-unit characters could still in principle land close to the
13664/// edge, but a real task title's occasional emoji or accented letter fits
13665/// comfortably inside it.
13666const PR_TITLE_MAX: usize = 240;
13667
13668/// A pull request title from the opening line of `text`, or `None` when that
13669/// line is not English (GitHub text is) or has no letters.
13670///
13671/// A line within `max` is kept as is. A longer one is cut at the end of its
13672/// first sentence when that falls inside `max`, else at a word boundary with a
13673/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13674/// make every merely-truncated title look non-English). The language check
13675/// runs on the kept text before any mark is added, so only what GitHub will
13676/// show is judged: an English opening followed by non-ASCII far past the cut
13677/// still passes.
13678fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13679    let line = queue::first_line(text)?;
13680    let chars: Vec<char> = line.chars().collect();
13681    let (kept, mark) = if chars.len() <= max {
13682        (line.to_owned(), "")
13683    } else if let Some(end) = sentence_end(&chars, max) {
13684        (chars[..end].iter().collect::<String>(), "")
13685    } else {
13686        let room = max.saturating_sub(3);
13687        // Cut at the last space inside the room; when the char just past the
13688        // room is a space the room already ends on a word.
13689        let cut = if chars[room].is_whitespace() {
13690            room
13691        } else {
13692            chars[..room]
13693                .iter()
13694                .rposition(|c| c.is_whitespace())
13695                .unwrap_or(room)
13696        };
13697        let head: String = chars[..cut].iter().collect();
13698        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13699        (head.to_owned(), "...")
13700    };
13701    if kept.is_empty() {
13702        return None;
13703    }
13704    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13705        return None;
13706    }
13707    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13708        return None;
13709    }
13710    Some(format!("{kept}{mark}"))
13711}
13712
13713/// The char length of the first sentence of `chars` when it ends within `max`
13714/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13715/// abbreviations so `e.g. foo` does not end a title early.
13716fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13717    const MIN: usize = 20;
13718    for i in MIN..max.min(chars.len()) {
13719        if !matches!(chars[i], '.' | '!' | '?') {
13720            continue;
13721        }
13722        let Some(&next) = chars.get(i + 1) else {
13723            continue;
13724        };
13725        if !next.is_whitespace() {
13726            continue;
13727        }
13728        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13729        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13730            continue;
13731        }
13732        let word: String = chars[..i]
13733            .iter()
13734            .rev()
13735            .take_while(|c| !c.is_whitespace())
13736            .collect::<Vec<_>>()
13737            .into_iter()
13738            .rev()
13739            .collect();
13740        let word = word.to_ascii_lowercase();
13741        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13742            continue;
13743        }
13744        let end = chars[..i]
13745            .iter()
13746            .rposition(|c| !c.is_whitespace())
13747            .map_or(i, |p| p + 1);
13748        return Some(end);
13749    }
13750    None
13751}
13752
13753/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13754/// change: a title and a body describing what was *implemented*, not the task
13755/// that asked for it. A task reads as a request; a reader of the merged
13756/// history wants the change.
13757struct PrMessage {
13758    title: String,
13759    body: String,
13760}
13761
13762impl PrMessage {
13763    /// Title, blank line, body. The first line is the squash/merge commit
13764    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13765    /// has to stay one sensible line.
13766    fn commit_message(&self) -> String {
13767        format!("{}\n\n{}", self.title, self.body)
13768    }
13769}
13770
13771/// The text after a leading `TITLE:` (any case) on `line`.
13772fn title_marker(line: &str) -> Option<&str> {
13773    let line = line.trim();
13774    let head = line.get(..6)?;
13775    head.eq_ignore_ascii_case("title:")
13776        .then(|| line[6..].trim())
13777}
13778
13779/// The implementer's own one-line title: the `TITLE:` line the implement
13780/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13781/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13782/// source, and a title that says as much is refused here too.
13783fn summary_title(summary: &str) -> Option<String> {
13784    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13785    let raw = title_marker(first)?;
13786    if raw.is_empty() {
13787        return None;
13788    }
13789    let title = queue::title_from(raw, PR_TITLE_MAX);
13790    let lower = title.to_ascii_lowercase();
13791    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13792        return None;
13793    }
13794    Some(title)
13795}
13796
13797/// How `open_review`'s instruction begins; see [`landing_title`].
13798const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13799
13800/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13801pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13802
13803/// Does this run review work that already existed, rather than implement a
13804/// task? Runs recorded before `reviewed_commits` existed carry only the
13805/// candidate marker.
13806pub(crate) fn is_review_run(state: &RunState) -> bool {
13807    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13808}
13809
13810/// The title of a review-only run: the subject of the oldest commit under
13811/// review. Later commits are usually fixups, and `instruction` is the review
13812/// prompt, which says nothing about the change. GitHub text is English, so a
13813/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13814fn review_title(state: &RunState) -> Option<String> {
13815    english_subject(
13816        state.reviewed_commits.as_ref()?.first()?,
13817        state.config.graph.github_english(),
13818    )
13819}
13820
13821/// `raw` as a pull request title, or `None` when it is blank, not English
13822/// (GitHub text is), or one of magi's own candidate commit subjects.
13823fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13824    let raw = raw.trim();
13825    if raw.is_empty() {
13826        return None;
13827    }
13828    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13829        return None;
13830    }
13831    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13832        return None;
13833    }
13834    let title = queue::title_from(raw, PR_TITLE_MAX);
13835    let lower = title.to_ascii_lowercase();
13836    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13837        return None;
13838    }
13839    Some(title)
13840}
13841
13842/// What a review-only run's branch says about itself, read at the moment the
13843/// pull request is opened.
13844#[derive(Debug, Clone, PartialEq, Eq)]
13845struct BranchFacts {
13846    /// `(subject, body)` of each commit, oldest first.
13847    commits: Vec<(String, String)>,
13848    /// Trimmed `git diff --stat`.
13849    stat: String,
13850}
13851
13852/// Longest diff stat shown: this many file lines plus the summary line.
13853const STAT_FILE_LINES: usize = 25;
13854/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13855const COMMITS_MAX_CHARS: usize = 20_000;
13856
13857/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13858/// say or finds nothing, so the caller falls back to what the run recorded.
13859async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13860    let commits = git::commit_log(repo, base, branch).await.ok()?;
13861    if commits.is_empty() {
13862        return None;
13863    }
13864    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13865    let lines: Vec<&str> = stat.lines().collect();
13866    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13867        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13868        let more = format!(" ... {omitted} more file(s)");
13869        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13870        kept.push(&more);
13871        kept.push(lines[lines.len() - 1]);
13872        kept.join("\n")
13873    } else {
13874        lines.join("\n")
13875    };
13876    Some(BranchFacts { commits, stat })
13877}
13878
13879/// Defang what would break the surrounding markdown: a closing `</details>`
13880/// and a code fence.
13881fn markdown_safe(text: &str) -> String {
13882    text.replace("</details>", "&lt;/details&gt;")
13883        .replace("\x60\x60\x60", "~~~")
13884}
13885
13886fn neutral_title(state: &RunState, winner: char) -> String {
13887    format!(
13888        "chore: land candidate {} of run {}",
13889        winner.to_ascii_uppercase(),
13890        state.id
13891    )
13892}
13893
13894/// Reuse the graph's bounded fixer without starting another graph or driver.
13895/// Copy the working state back even on errors so spent rounds remain visible.
13896pub(crate) async fn repair_landing_gate(
13897    state: &mut RunState,
13898    winner: &Candidate,
13899    outcomes: &[CommandOutcome],
13900) -> Result<GateFix> {
13901    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13902        return Ok(GateFix::Stop);
13903    }
13904    let mut runner = Runner {
13905        roles: state.config.resolve_roles()?,
13906        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13907        state: state.clone(),
13908        pause: Pause::new(),
13909        interrupt: Pause::new(),
13910    };
13911    let result = runner.gate_fix_round(winner, outcomes).await;
13912    *state = runner.state;
13913    result
13914}
13915
13916/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13917/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13918pub(crate) async fn verify_current_head(
13919    state: &mut RunState,
13920    winner: &Candidate,
13921    wait: &crate::repo_lock::WaitPolicy,
13922) -> Result<bool> {
13923    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13924    // Preserve the previous record before replacing it, including on crash recovery.
13925    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13926        state
13927            .verification_history
13928            .push(crate::run::VerificationEvidence {
13929                superseded_by: Some(head.clone()),
13930                archived_at: Some(Timestamp::now()),
13931                fixes_spent: Some(state.gate_fixes.len()),
13932                gate_head: None,
13933                gate_ran: false,
13934                gate: Vec::new(),
13935                e2e: state.head_e2e.take(),
13936            });
13937    }
13938    if let Some(e) = &state.head_e2e
13939        && e.head == head
13940    {
13941        if e.passed {
13942            return Ok(true);
13943        }
13944        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13945            state.status = RunStatus::Blocked;
13946            state.save()?;
13947            return Ok(false);
13948        }
13949    } else if state.reviews.last().is_some_and(|r| {
13950        r.verified_head.as_deref() == Some(head.as_str())
13951            && (r.e2e_status() == E2eStatus::Passed
13952                || (r.e2e_status() == E2eStatus::NotConfigured
13953                    && state.config.verify.e2e.is_empty()))
13954    }) || state
13955        .gate_repair_e2e
13956        .as_ref()
13957        .is_some_and(|e| e.head == head && e.passed)
13958    {
13959        return Ok(true);
13960    }
13961    if let Some(e) = &state.gate_repair_e2e
13962        && e.head == head
13963        && !e.passed
13964        && !e.outcomes.is_empty()
13965        && !verify_inconclusive(&e.outcomes)
13966    {
13967        state.status = RunStatus::Blocked;
13968        state.save()?;
13969        return Ok(false);
13970    }
13971    // Bind the result to the base used by the candidate, not a tracking ref
13972    // that the background fetch can advance independently of verification.
13973    let base_commit = state
13974        .base_sync
13975        .as_ref()
13976        .map(|s| s.tip.clone())
13977        .filter(|tip| !tip.is_empty())
13978        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13979    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13980        head.clone(),
13981        false,
13982        Vec::new(),
13983    ));
13984    state.save()?;
13985    let commands = state.config.verify.e2e.clone();
13986    let shell = state.config.shell();
13987    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13988    let cache_dir = state.config.cache_dir();
13989    let outcomes = if commands.is_empty() {
13990        Vec::new()
13991    } else {
13992        let (outcomes, _) = with_cache_lease(
13993            state,
13994            cache_dir.as_deref(),
13995            "e2e",
13996            "e2e",
13997            &winner.worktree,
13998            &head,
13999            timeout,
14000            "current head e2e",
14001            wait,
14002            |state, budget| async move {
14003                run_e2e_with_retry(
14004                    state,
14005                    &shell,
14006                    &commands,
14007                    &winner.worktree,
14008                    budget,
14009                    "current head e2e",
14010                    None,
14011                )
14012                .await
14013            },
14014        )
14015        .await?;
14016        outcomes
14017    };
14018    let unresolved = verify_inconclusive(&outcomes);
14019    let passed = !unresolved
14020        && outcomes.iter().all(CommandOutcome::ok)
14021        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14022    if !outcomes.is_empty() && !unresolved {
14023        state.record_base_progress(&head);
14024    }
14025    let generation = Some(state.verification_history.len());
14026    let pass = state.passes.last().map(|p| p.index);
14027    let recorded_at = Some(Timestamp::now());
14028    let resumption_generation = state.entry_resumption_generation;
14029    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
14030    record.base_commit = base_commit;
14031    record.generation = generation;
14032    record.pass = pass;
14033    record.recorded_at = recorded_at;
14034    record.resumption_generation = resumption_generation;
14035    if !passed && !unresolved {
14036        let detail = state
14037            .head_e2e
14038            .as_ref()
14039            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14040            .map(|d| format!(" ({d})"))
14041            .unwrap_or_default();
14042        state.status = RunStatus::Blocked;
14043        state.event(
14044            "e2e",
14045            format!("verify.e2e failed on head {head}{detail}; nothing published"),
14046        );
14047        record.recorded_events = Some(state.events.len());
14048    }
14049    state.head_e2e = Some(record);
14050    state.save()?;
14051    Ok(passed)
14052}
14053
14054/// Recheck a repair's e2e requirement across failures, resource deferrals and
14055/// process interruptions. A successful result only applies to its exact SHA.
14056pub(crate) async fn check_gate_repair_e2e(
14057    state: &mut RunState,
14058    winner: &Candidate,
14059    wait: &crate::repo_lock::WaitPolicy,
14060) -> Result<GateFix> {
14061    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
14062        return Ok(GateFix::Retry);
14063    }
14064    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14065    if let Some(record) = &state.gate_repair_e2e
14066        && record.head == head
14067    {
14068        if record.passed {
14069            return Ok(GateFix::Retry);
14070        }
14071        if !record.outcomes.is_empty()
14072            && record.outcomes.iter().all(|o| {
14073                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
14074            })
14075        {
14076            return Ok(GateFix::Stop);
14077        }
14078    }
14079    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
14080        head.clone(),
14081        false,
14082        Vec::new(),
14083    ));
14084    state.save()?;
14085    let commands = state.config.verify.e2e.clone();
14086    let outcomes = if commands.is_empty() {
14087        Vec::new()
14088    } else {
14089        let shell = state.config.shell();
14090        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14091        let cache_dir = state.config.cache_dir();
14092        let (outcomes, _) = with_cache_lease(
14093            state,
14094            cache_dir.as_deref(),
14095            "e2e",
14096            "e2e",
14097            &winner.worktree,
14098            &head,
14099            timeout,
14100            "gate repair e2e",
14101            wait,
14102            |state, budget| async move {
14103                run_e2e_with_retry(
14104                    state,
14105                    &shell,
14106                    &commands,
14107                    &winner.worktree,
14108                    budget,
14109                    "gate repair e2e",
14110                    None,
14111                )
14112                .await
14113            },
14114        )
14115        .await?;
14116        outcomes
14117    };
14118    let deferred = verify_inconclusive(&outcomes);
14119    let passed = outcomes.iter().all(CommandOutcome::ok)
14120        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14121    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
14122    state.save()?;
14123    if deferred {
14124        Ok(GateFix::Defer)
14125    } else if !passed {
14126        let detail = state
14127            .gate_repair_e2e
14128            .as_ref()
14129            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14130            .map(|d| format!(" ({d})"))
14131            .unwrap_or_default();
14132        state.event(
14133            "gate",
14134            format!("verify.e2e failed after gate repair{detail}; nothing published"),
14135        );
14136        Ok(GateFix::Stop)
14137    } else {
14138        Ok(GateFix::Retry)
14139    }
14140}
14141
14142/// Run the same configured gate for a landing head and a fresh graph.
14143pub(crate) async fn run_landing_gate(
14144    state: &mut RunState,
14145    winner: &Candidate,
14146    wait: &crate::repo_lock::WaitPolicy,
14147) -> Result<Vec<CommandOutcome>> {
14148    let shell = state.config.shell();
14149    let gate_commands = state.config.verify.gate.clone();
14150    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
14151    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
14152        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
14153        Vec::new()
14154    } else {
14155        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14156        let cache_dir = state.config.cache_dir();
14157        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14158        let (outcomes, _) = with_cache_lease(
14159            state,
14160            cache_dir.as_deref(),
14161            "gate",
14162            "gate",
14163            &winner.worktree,
14164            &head,
14165            timeout,
14166            "final gate",
14167            wait,
14168            |state, budget| {
14169                let shell = shell.clone();
14170                let gate_commands = gate_commands.clone();
14171                let winner = winner.clone();
14172                async move {
14173                    Runner::run_pre_gate(state, &winner).await;
14174                    // Bind command evidence after mechanical fixes, before commands start.
14175                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
14176                    let (outcomes, timed_out_pids) = run_commands(
14177                        state,
14178                        "gate",
14179                        "gate",
14180                        0,
14181                        &shell,
14182                        &gate_commands,
14183                        &winner.worktree,
14184                        budget,
14185                    )
14186                    .await;
14187                    (outcomes, false, timed_out_pids)
14188                }
14189            },
14190        )
14191        .await?;
14192        outcomes
14193    };
14194    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
14195    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
14196        let mut outcomes = outcomes;
14197        outcomes.push(CommandOutcome {
14198            command: "gate head stability".into(), code: None,
14199            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
14200            duration_ms: 0, resource_blocked: false,
14201            ..Default::default()
14202        });
14203        return Ok(outcomes);
14204    }
14205    if outcomes.is_empty() {
14206        // Nothing configured to check — distinct from every other
14207        // silence in this run's event log, since an empty `gate` alone
14208        // no longer says whether the gate ran at all (see
14209        // `RunState::gate_ran`'s own doc).
14210        state.event("gate", "no gate commands configured; not tested");
14211    }
14212    for o in &outcomes {
14213        state.event(
14214            "gate",
14215            format!(
14216                "`{}` -> {}",
14217                o.command,
14218                if o.ok() {
14219                    "pass".to_owned()
14220                } else {
14221                    format!(
14222                        "FAIL ({:?})\n{}",
14223                        o.code,
14224                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
14225                    )
14226                }
14227            ),
14228        );
14229    }
14230    Ok(outcomes)
14231}
14232
14233/// The pull request title to hand to `land::merge_subject`. A review-only run
14234/// opened by an earlier build titled its pull request with the review prompt;
14235/// that title is dropped (empty, so the fallback applies) rather than landed.
14236/// Any other title, including an operator's rename, passes through untouched,
14237/// and so does every title of a run that implements a task.
14238pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
14239    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
14240        ""
14241    } else {
14242        pr_title
14243    }
14244}
14245
14246/// What the squash subject falls back to when the pull request title is empty
14247/// or candidate-shaped: for a review-only run the derived title, never the
14248/// review prompt held in `instruction`.
14249pub fn landing_subject_source(state: &RunState) -> String {
14250    if is_review_run(state) {
14251        let winner = state.candidates.first().map_or('A', |c| c.label);
14252        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14253    }
14254    state.instruction.clone()
14255}
14256
14257/// `summary` without its `TITLE:` line, which the pull request title already
14258/// carries.
14259fn summary_without_title(summary: &str) -> String {
14260    let mut lines = summary.trim().lines().peekable();
14261    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14262        lines.next();
14263    }
14264    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14265}
14266
14267/// The pull request title and body for the winning candidate.
14268///
14269/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14270/// the task's own opening line via [`queue::title_from`] when there is none.
14271/// `state.instruction` can open with blank lines (`task_text` only rejects a
14272/// body that is blank *entirely*), which `title_from` skips.
14273///
14274/// Publishing uses an independent description generated from the final diff
14275/// and structured evidence. Internal summaries and reports remain local.
14276/// Non-publishing previews may display the original task and candidate summary.
14277/// The footer retains the run and candidate provenance.
14278#[cfg(test)]
14279fn pr_message(state: &RunState, winner: char) -> PrMessage {
14280    pr_message_with(state, winner, None)
14281}
14282
14283/// [`pr_message`] with what the branch of a review-only run says about itself.
14284/// `facts` is ignored for a run that implements a task.
14285#[cfg(test)]
14286fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14287    let raw = pr_message_raw(
14288        state,
14289        winner,
14290        facts,
14291        crate::pr_outcome::FinalHead::Unreported,
14292        ChangeNote::NotAsked,
14293    );
14294    let id = crate::scrub::Identity::current();
14295    PrMessage {
14296        title: crate::scrub::scrub(&raw.title, &id),
14297        body: crate::scrub::scrub(&raw.body, &id),
14298    }
14299}
14300
14301/// What the public description may say about the change itself.
14302#[derive(Debug, Clone, Copy)]
14303enum ChangeNote<'a> {
14304    /// A local preview or non-publishing merge mode: no public generation needed.
14305    NotAsked,
14306    /// A summary written from the final diff.
14307    Summary(&'a crate::run::ChangeSummary),
14308    /// A summary was asked for and could not be produced; the text says why.
14309    Unavailable(&'a str),
14310}
14311
14312fn pr_message_raw(
14313    state: &RunState,
14314    winner: char,
14315    facts: Option<&BranchFacts>,
14316    head: crate::pr_outcome::FinalHead<'_>,
14317    change: ChangeNote<'_>,
14318) -> PrMessage {
14319    if !matches!(change, ChangeNote::NotAsked) {
14320        let (title, mut body) = match change {
14321            ChangeNote::Summary(c) => (
14322                c.title.clone(),
14323                format!("## Summary\n\n{}\n\n", c.body.trim()),
14324            ),
14325            ChangeNote::Unavailable(why) => (
14326                neutral_title(state, winner),
14327                format!(
14328                    "## 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"
14329                ),
14330            ),
14331            ChangeNote::NotAsked => unreachable!(),
14332        };
14333        body.push_str(&public_pr_evidence(state, head));
14334        body.push_str(&format!(
14335            "\n---\nmagi:run/{} magi:candidate-{}\n",
14336            state.id,
14337            winner.to_ascii_lowercase()
14338        ));
14339        return PrMessage { title, body };
14340    }
14341    pr_preview(state, winner, facts, head)
14342}
14343
14344/// Append public facts from the run records after every prose generation,
14345/// including posting-gate rewrites. The agent cannot drop this provenance.
14346fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14347    let mut body = crate::pr_outcome::review_rounds(state);
14348    body.push_str(&crate::pr_outcome::final_verification(state, head));
14349    let open = state.last_round_findings();
14350    if !open.is_empty() {
14351        body.push_str("## Open review findings\n\n");
14352        for f in open {
14353            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14354        }
14355        body.push('\n');
14356    }
14357    if let Some(c) = state.change_summary.as_ref()
14358        && head == crate::pr_outcome::FinalHead::At(&c.head)
14359    {
14360        body.push_str(&format!(
14361            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14362            c.base, c.head
14363        ));
14364    }
14365    body
14366}
14367
14368/// Local-only preview of the operator's task and candidate summary.
14369fn pr_preview(
14370    state: &RunState,
14371    winner: char,
14372    facts: Option<&BranchFacts>,
14373    head: crate::pr_outcome::FinalHead<'_>,
14374) -> PrMessage {
14375    let summary = state
14376        .candidates
14377        .iter()
14378        .find(|c| c.label == winner)
14379        .map(|c| c.summary.as_str())
14380        .unwrap_or_default();
14381    // The fallback is the operator's own words and may not be English; GitHub
14382    // text always is, so a non-English task gets a neutral title instead.
14383    let review = is_review_run(state);
14384    let title = if review {
14385        facts
14386            .and_then(|f| {
14387                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14388            })
14389            .or_else(|| review_title(state))
14390            .or_else(|| {
14391                state
14392                    .candidates
14393                    .iter()
14394                    .find(|c| c.label == winner)
14395                    .filter(|c| !c.branch.starts_with("magi/"))
14396                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14397            })
14398            .unwrap_or_else(|| neutral_title(state, winner))
14399    } else {
14400        summary_title(summary).unwrap_or_else(|| {
14401            english_title(
14402                &state.instruction,
14403                PR_TITLE_MAX,
14404                state.config.graph.github_english(),
14405            )
14406            .unwrap_or_else(|| neutral_title(state, winner))
14407        })
14408    };
14409
14410    let mut body = String::new();
14411    let what = summary_without_title(summary);
14412    if !what.is_empty() {
14413        body.push_str("## Summary\n\n");
14414        body.push_str(&what);
14415        body.push_str("\n\n");
14416    }
14417
14418    // Review history uses structured facts across all rounds, never reports.
14419    body.push_str(&crate::pr_outcome::review_rounds(state));
14420    body.push_str(&crate::pr_outcome::final_verification(state, head));
14421    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14422
14423    let open = state.open_findings();
14424    if !open.is_empty() {
14425        body.push_str("## Open review findings\n\n");
14426        for f in &open {
14427            body.push_str(&format!(
14428                "- `{}` [{:?}] {}\n",
14429                f.id, f.severity, "Context retained in local review records."
14430            ));
14431        }
14432        body.push('\n');
14433    }
14434
14435    if let Some(fix) = fix
14436        && !fix.rejected.is_empty()
14437    {
14438        body.push_str("## Declined by the fixer\n\n");
14439        for r in &fix.rejected {
14440            body.push_str(&format!(
14441                "- `{}`: {}\n",
14442                r.id, "Reason retained in local review records."
14443            ));
14444        }
14445        body.push('\n');
14446    }
14447
14448    if review {
14449        // The review prompt is not the task; list what the branch carries.
14450        body.push_str("## Commits under review\n\n");
14451        if let Some(facts) = facts {
14452            let mut left = COMMITS_MAX_CHARS;
14453            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14454                let mut entry = format!("- {}\n", markdown_safe(subject));
14455                for l in markdown_safe(text).lines() {
14456                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14457                }
14458                if left == 0 {
14459                    body.push_str(&format!(
14460                        "- ... {} more commit(s)\n",
14461                        facts.commits.len() - i
14462                    ));
14463                    break;
14464                }
14465                if entry.len() > left {
14466                    // Even the first commit is cut: one huge body must not
14467                    // push the whole description past GitHub's limit.
14468                    let mut end = left;
14469                    while !entry.is_char_boundary(end) {
14470                        end -= 1;
14471                    }
14472                    entry.truncate(end);
14473                    entry.push_str("\n  ... (truncated)\n");
14474                    left = 0;
14475                } else {
14476                    left -= entry.len();
14477                }
14478                body.push_str(&entry);
14479            }
14480            if !facts.stat.trim().is_empty() {
14481                body.push_str(&format!(
14482                    "\n## Diff stat\n\n```\n{}\n```\n",
14483                    markdown_safe(facts.stat.trim())
14484                ));
14485            }
14486        } else {
14487            match &state.reviewed_commits {
14488                Some(subjects) => {
14489                    for s in subjects {
14490                        body.push_str(&format!("- {}\n", s.trim()));
14491                    }
14492                }
14493                None => {
14494                    // An older run kept only the prompt, with the commit list
14495                    // after its first paragraph.
14496                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14497                    body.push_str(rest.trim());
14498                    body.push('\n');
14499                }
14500            }
14501        }
14502    } else {
14503        let task = state.instruction.trim();
14504        let task = if task.is_empty() {
14505            "(empty task)"
14506        } else {
14507            task
14508        };
14509        body.push_str(&format!(
14510            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14511            task.replace("</details>", "&lt;/details&gt;")
14512        ));
14513    }
14514
14515    body.push_str(&format!(
14516        "\n---\nmagi:run/{} magi:candidate-{}\n",
14517        state.id,
14518        winner.to_ascii_lowercase()
14519    ));
14520
14521    PrMessage { title, body }
14522}
14523
14524/// Source imports have already been prepared from structured inputs. Legacy
14525/// inferred references must never instruct a seat to reconstruct those imports.
14526fn seeded_instruction(state: &RunState) -> String {
14527    let mut inputs = Vec::new();
14528    if let Some(start) = &state.sources.start_from {
14529        inputs.push(format!(
14530            "Start from `{}` at `{}` (including ancestry).",
14531            start.token, start.sha
14532        ));
14533    }
14534    for pick in &state.sources.pick_commits {
14535        inputs.push(format!(
14536            "Pick `{}` at `{}` (single commit).",
14537            pick.token, pick.sha
14538        ));
14539    }
14540    if inputs.is_empty() {
14541        state.instruction.clone()
14542    } else {
14543        format!(
14544            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14545            state.instruction,
14546            inputs.join("\n")
14547        )
14548    }
14549}
14550
14551/// Does the winner have no commits ahead of the base it would land on?
14552/// Any failure to find out reads as "not empty": the merge then behaves as it
14553/// always did rather than refusing on a guess.
14554async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14555    let base = &state.base_branch;
14556    let mut against = base.clone();
14557    if mode == MergeMode::Pr {
14558        // A pull request lands on the remote's base, never the local branch
14559        // of the same name: if that cannot be read, "not empty" is the safe
14560        // answer.
14561        let remote = &state.config.merge.remote;
14562        let tracking = format!("{remote}/{base}");
14563        let fetched = git::fetch(repo, remote, base).await;
14564        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14565            against = tracking;
14566        } else {
14567            return false;
14568        }
14569    }
14570    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14571}
14572
14573/// Why nothing was opened for an empty winner, with what the task's own
14574/// references resolved to.
14575fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14576    let mut detail = format!(
14577        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14578         nothing to open a pull request for"
14579    );
14580    detail.push_str(
14581        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14582    );
14583    detail
14584}
14585
14586/// What the `Pr` merge does once it knows whether the branch already has an
14587/// open pull request.
14588#[derive(Debug, PartialEq, Eq)]
14589enum PrPlan {
14590    Create,
14591    Adopt { url: String, title: String },
14592    Stop(String),
14593}
14594
14595/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14596/// a failed lookup -> stop with the real reason. Never guesses.
14597fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14598    match found {
14599        Ok(land::OpenPr::None) => PrPlan::Create,
14600        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14601        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14602            "several open pull requests exist for this branch, not picking one: {}",
14603            urls.join(" ")
14604        )),
14605        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14606    }
14607}
14608
14609/// `gh pr create`, returning the PR url.
14610pub(crate) async fn gh_pr_create(
14611    cwd: &Path,
14612    base: &str,
14613    head: &str,
14614    title: &str,
14615    body: &str,
14616) -> Result<String> {
14617    let out = tokio::process::Command::new("gh")
14618        .args([
14619            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14620        ])
14621        .current_dir(cwd)
14622        .quiet()
14623        .stdin(std::process::Stdio::null())
14624        .output()
14625        .await
14626        .context("spawn gh")?;
14627    if out.status.success() {
14628        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14629    } else {
14630        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14631    }
14632}
14633
14634/// Never force deletion of uncommitted work, including unknown legacy trees.
14635async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14636    match std::fs::symlink_metadata(path) {
14637        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14638            // A previous cleanup may have removed the tree before a branch
14639            // deletion or state save failed. Unregister it if still present.
14640            git::worktree_remove_clean(repo, path).await?;
14641            return Ok(());
14642        }
14643        Err(e) => return Err(e.into()),
14644        Ok(_) => {}
14645    }
14646    if !git::is_clean(path).await? {
14647        bail!(
14648            "worktree has uncommitted work; refusing removal: {}",
14649            path.display()
14650        );
14651    }
14652    if !git::worktree_remove_clean(repo, path).await? {
14653        bail!("worktree removal refused: {}", path.display());
14654    }
14655    Ok(())
14656}
14657
14658/// Read seats return replies, not working-tree changes. Only registered,
14659/// detached seats directly inside this run's root may discard those changes.
14660async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14661    if !crate::retention::read_seat(path) || !path.exists() {
14662        return remove_preserved_worktree(&state.repo, path).await;
14663    }
14664    let owned = std::fs::symlink_metadata(path)?.is_dir()
14665        && path.parent().map(Path::canonicalize).transpose()?
14666            == Some(state.worktree_root().canonicalize()?)
14667        && crate::retention::worktrees(state)
14668            .await?
14669            .contains(&path.canonicalize()?);
14670    let common = crate::repo_lock::common_dir(&state.repo).await?;
14671    if !owned
14672        || common.is_none()
14673        || crate::repo_lock::common_dir(path).await? != common
14674        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14675            .await?
14676            .ok()
14677        || state.candidates.iter().any(|c| c.worktree == path)
14678    {
14679        return remove_preserved_worktree(&state.repo, path).await;
14680    }
14681    let changes = git::status_porcelain(path).await?;
14682    if !git::worktree_remove(&state.repo, path).await? {
14683        bail!(
14684            "read-only seat worktree removal refused: {}",
14685            path.display()
14686        );
14687    }
14688    if !changes.is_empty() {
14689        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14690        let paths: String = paths.chars().take(1024).collect();
14691        state.event(
14692            "fold",
14693            format!(
14694                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14695                path.file_name().unwrap_or_default().to_string_lossy(),
14696                changes.lines().count()
14697            ),
14698        );
14699    }
14700    Ok(())
14701}
14702
14703fn fold_target(
14704    home: &Path,
14705    root: &Path,
14706    path: &Path,
14707    isolated: bool,
14708) -> Option<crate::build_target::FoldTarget> {
14709    if !isolated {
14710        return None;
14711    }
14712    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14713        Ok(target) => target,
14714        Err(error) => {
14715            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14716            None
14717        }
14718    }
14719}
14720
14721fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14722    if let Some(target) = target
14723        && let Err(error) = target.reclaim_orphaned_target(home)
14724    {
14725        tracing::warn!(%error, "isolated target retained after fold");
14726    }
14727}
14728
14729/// Why a fold left a run alone. A typed refusal lets the automatic callers
14730/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14731/// turn) say *why* in their receipts; it never changes what is deleted.
14732#[derive(Debug, Clone, PartialEq, Eq)]
14733pub enum FoldRefusal {
14734    /// A lease or lock a live owner holds - the run's execution lease or
14735    /// ownership lock, a source's output lease, a Cargo build, the repository's
14736    /// coordination lease - or a live daemon claim on the run.
14737    Live(String),
14738    /// A resumable status: someone may still continue this run.
14739    Resumable,
14740    /// Finished less than the fold grace period ago.
14741    WithinGrace,
14742    /// An explicitly retained recovery source (`pr_recovery`).
14743    Retained(String),
14744    /// The proof that nothing is lost is not complete: startup or candidate
14745    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14746    /// residue, Git checkpoints, the fetched base) could not be established.
14747    ProofIncomplete(String),
14748    /// The run's record is gone, or is not the record that was locked: it was
14749    /// deleted while the fold waited for its locks. Nothing is touched and
14750    /// nothing is recreated.
14751    RecordGone,
14752    /// The record was readable when the caller first looked and cannot be read
14753    /// once the run's locks are held.
14754    Unreadable(String),
14755}
14756
14757impl std::fmt::Display for FoldRefusal {
14758    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14759        match self {
14760            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14761            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14762            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14763            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14764            Self::RecordGone => f.write_str("refusing fold: record gone"),
14765            Self::Unreadable(detail) => {
14766                write!(
14767                    f,
14768                    "refusing fold: the run record became unreadable: {detail}"
14769                )
14770            }
14771        }
14772    }
14773}
14774
14775impl std::error::Error for FoldRefusal {}
14776
14777/// Is `error` somebody else holding a lock or lease right now? Only
14778/// contention is: any other failure of a lock call is a real failure.
14779pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14780    error.chain().any(|cause| {
14781        cause.is::<crate::retention::OutputsInUse>()
14782            || cause.is::<crate::repo_lock::ResourceBlocked>()
14783            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14784                io.kind() == std::io::ErrorKind::WouldBlock
14785                    || cfg!(windows) && io.raw_os_error() == Some(33)
14786            })
14787    })
14788}
14789
14790/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14791///
14792/// The refusal is *added to* the error as context, never substituted for it:
14793/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14794/// coordination wait, which several of them treat as a resource stop), and the
14795/// receipt's classification reads the refusal. Both downcasts succeed.
14796fn live_or(error: anyhow::Error) -> anyhow::Error {
14797    if held_by_live_owner(&error) {
14798        error.context(FoldRefusal::Live(
14799            "a lock or lease is held by another owner".into(),
14800        ))
14801    } else {
14802        error
14803    }
14804}
14805
14806/// A failure to take a run's owner lock or execution lease. A run directory
14807/// that is not there (deleted, or never was) is `record gone` and is *not*
14808/// created for the lock's sake; contention is `live`; anything else stays a
14809/// failure with its own text.
14810fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14811    if is_missing(&error) {
14812        FoldRefusal::RecordGone.into()
14813    } else {
14814        live_or(error)
14815    }
14816}
14817
14818fn is_missing(error: &anyhow::Error) -> bool {
14819    error.chain().any(|cause| {
14820        cause
14821            .downcast_ref::<std::io::Error>()
14822            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14823    })
14824}
14825
14826fn preservation_refusal() -> anyhow::Error {
14827    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14828        .into()
14829}
14830
14831/// The record's own preconditions for the explicit recovery-retention override.
14832fn ensure_overridable(state: &RunState) -> Result<()> {
14833    anyhow::ensure!(
14834        state.status.done() && !state.status.resumable(),
14835        "recovery retention override requires a finished, non-resumable run"
14836    );
14837    Ok(())
14838}
14839
14840/// How a failure of the confirmed-merge source verification reaches the fold's
14841/// caller: somebody else holding a lock is `live`; a lock call that failed for
14842/// another reason is a failure of its own (`failed` in the receipt), not
14843/// evidence that the sources are unproven; anything else - missing or changed
14844/// evidence - is an incomplete proof.
14845fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14846    if held_by_live_owner(&error) {
14847        live_or(error)
14848    } else if error
14849        .chain()
14850        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14851    {
14852        error
14853    } else {
14854        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14855    }
14856}
14857
14858/// Which loader a fold uses on the record it reads again under its locks.
14859#[derive(Clone, Copy, PartialEq, Eq)]
14860enum Reload {
14861    /// Housekeeping: the record as saved, whatever schema wrote it
14862    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14863    /// always read it.
14864    Tolerant,
14865    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14866    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14867    /// the preservation checks and the saved record then rest on.
14868    Strict,
14869}
14870
14871/// Why a record read under the locks is no longer the one that was locked.
14872fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14873    if is_missing(error) {
14874        FoldRefusal::RecordGone
14875    } else {
14876        FoldRefusal::Unreadable(format!("{error:#}"))
14877    }
14878}
14879
14880/// What a test does after a fold's first look at the record and before it
14881/// takes the run's locks: where a deletion or a handover falls.
14882#[cfg(test)]
14883type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14884
14885#[cfg(test)]
14886thread_local! {
14887    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14888        const { std::cell::RefCell::new(None) };
14889}
14890
14891/// Tear a run's worktrees and branches down.
14892///
14893/// `home` is where the updated `run.json` is saved (via
14894/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14895/// a housekeeping pass already has its own honest `home` handed to it, and
14896/// falling through to the global here would write back through whichever
14897/// directory some other process or test pinned into that `OnceLock` first,
14898/// not the one the caller actually resolved its `runs` and `state` from.
14899///
14900/// Every deletion decision is made on the record as it is on disk once the
14901/// owner lock and execution lease are held, not on the `state` the caller read
14902/// earlier: see [`fold_run_when`].
14903pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14904    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14905}
14906
14907/// [`fold_run`] for the automatic callers, which decide whether the run may be
14908/// folded at all, and whether its winner goes too, from the run record.
14909///
14910/// `decide` is called on the caller's earlier read by the caller itself, and
14911/// again here on the record reloaded after taking the run's owner lock and
14912/// execution lease. A handover (`handover::release`) records `released_to` /
14913/// `released_branches` under that owner lock and removes the old worktree while
14914/// keeping the branch; a fold that acted on a record read before the handover
14915/// would delete the branch already given to the successor and save the stale
14916/// record over the handover. A run no longer eligible under the fresh record
14917/// is left alone and the refusal says why. The reload is tolerant of older
14918/// schemas, as `clean::fold_due` always was; the explicit entry points
14919/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14920/// migrating loader.
14921pub async fn fold_run_when(
14922    state: &mut RunState,
14923    home: &Path,
14924    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14925) -> Result<Vec<String>> {
14926    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14927}
14928
14929/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14930pub async fn fold_run_overriding_recovery_retention(
14931    state: &mut RunState,
14932    drop_winner: bool,
14933    home: &Path,
14934) -> Result<Vec<String>> {
14935    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14936}
14937
14938async fn fold_run_with_policy(
14939    state: &mut RunState,
14940    home: &Path,
14941    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14942    reload: Reload,
14943    override_recovery_retention: bool,
14944) -> Result<Vec<String>> {
14945    // Cheap refusals on the caller's snapshot, before any lock is taken.
14946    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14947        && !override_recovery_retention
14948    {
14949        return Err(FoldRefusal::Retained(reason).into());
14950    }
14951    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14952        return Err(preservation_refusal());
14953    }
14954    // A fold needs the saved record of the run it locks. Nothing below may
14955    // bring a deleted run's directory back, and a fold is never entitled to
14956    // write a record of its own making: the caller's `state` is only a first
14957    // look, and every decision is made on what is read under the locks.
14958    let id = state.id.clone();
14959    let record = home.join("runs").join(&id).join("run.json");
14960    if !record.try_exists()? {
14961        return Err(FoldRefusal::RecordGone.into());
14962    }
14963    #[cfg(test)]
14964    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14965        hook(home, &id);
14966    }
14967    // Serialize ordinary folding with the same starts/resumes as target-only
14968    // eviction. Otherwise a second janitor could remove the whole worktree
14969    // around a live output borrower even though target eviction was fenced.
14970    // Deleting a run record takes these same two locks (`clean::delete_run`).
14971    // The lock files are opened where they are and never created in a
14972    // directory that is not there: a refusal changes nothing, and the lock
14973    // files are never unlinked (`pr_head::owner_lock`).
14974    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14975    // An override must use current durable ownership, not a pre-lock snapshot.
14976    // Its liveness assessment has to be made before this fold holds the
14977    // execution lease itself (a held lease reads as a live driver); the record
14978    // it is made on is checked for identity like every other, and the final
14979    // record, read once both locks are held, is checked again below.
14980    if override_recovery_retention {
14981        let current =
14982            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14983        if current.id != id {
14984            return Err(FoldRefusal::RecordGone.into());
14985        }
14986        ensure_overridable(&current)?;
14987        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14988        anyhow::ensure!(
14989            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14990            "run is live or its ownership is unknown"
14991        );
14992    }
14993    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14994    // Both locks are held, so no handover, driver claim, deletion or other
14995    // fold can change the record from here on: act on it, not on the earlier
14996    // read. There is no fallback to that read - a record that cannot be read
14997    // again, or is not this run's, ends the fold and touches nothing.
14998    let loaded = match reload {
14999        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
15000        Reload::Strict => RunState::load_under(&id, home),
15001    };
15002    match loaded {
15003        Ok(fresh) if fresh.id == id => *state = fresh,
15004        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
15005        Err(e) => return Err(reload_refusal(&e).into()),
15006    }
15007    if override_recovery_retention {
15008        ensure_overridable(state)?;
15009    }
15010    let drop_winner = decide(state)?;
15011    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
15012        return Err(preservation_refusal());
15013    }
15014    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
15015    if let Some(reason) = &retention_reason
15016        && !override_recovery_retention
15017    {
15018        return Err(FoldRefusal::Retained(reason.clone()).into());
15019    }
15020    let mut output_guards = Vec::new();
15021    for entry in std::fs::read_dir(state.worktree_root())
15022        .into_iter()
15023        .flatten()
15024        .flatten()
15025    {
15026        if entry.path().join(".git").is_file() {
15027            output_guards
15028                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
15029        }
15030    }
15031    let repo = state.repo.clone();
15032    // CLI, Web and automatic cleanup all enter here, independently of
15033    // Runner::fold_losers. Protect deletion and shared config release too.
15034    //
15035    // Lock order. A handover (`handover::release`, a review taking a branch
15036    // over) holds repository coordination and then asks for this run's owner
15037    // lock; this fold already holds the owner lock. An automatic fold must not
15038    // *wait* for coordination here: the handover would wait for the owner lock
15039    // while the fold waited for coordination, and neither bound (the handover's
15040    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
15041    // - the handover fails its startup, which costs the task an attempt. So it
15042    // asks once; when the lease is busy it gives way: everything it holds is
15043    // released on return, nothing was changed or saved, and the run is `live`
15044    // for this pass and judged again on a later one. The explicit callers
15045    // (`magi fold`, the phone's route) were asked for by a person and still
15046    // wait, bounded as before.
15047    let _coordination = if reload == Reload::Tolerant {
15048        match crate::repo_lock::SeatLease::operation_with(
15049            &repo,
15050            state.config.coordination.as_ref(),
15051            &crate::repo_lock::WaitPolicy::immediate(),
15052        )
15053        .await
15054        {
15055            Ok(lease) => lease,
15056            Err(e) => return Err(live_or(e)),
15057        }
15058    } else {
15059        let wait = repository_wait(state, None);
15060        match coordinate_operation(state, &repo, &wait).await {
15061            Ok(lease) => lease,
15062            Err(e) => {
15063                state.save_under(home)?;
15064                return Err(live_or(e));
15065            }
15066        }
15067    };
15068    // Confirmed merges dispose of their owned sources after durable evidence
15069    // capture. Preflight every source before removing anything. A failure of
15070    // this stage is, by what the stage is for, an incomplete proof - unless
15071    // it is only a lock somebody else holds.
15072    let _source_outputs = if retention_reason.is_some()
15073        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
15074    {
15075        match verify_merged_fold_sources(state, drop_winner, home).await {
15076            Ok(held) => held,
15077            Err(e) => return Err(source_proof_failure(e)),
15078        }
15079    } else {
15080        Vec::new()
15081    };
15082    if let Some(reason) = retention_reason {
15083        state.event(
15084            "fold",
15085            format!(
15086                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
15087                state.id
15088            ),
15089        );
15090        state.save_under(home)?;
15091    }
15092    let root = state.worktree_root();
15093    let winner = state.tally.as_ref().map(|t| t.winner);
15094    let mut removed = Vec::new();
15095    let isolated = crate::build_target::isolated(&state.config);
15096
15097    for i in 0..state.candidates.len() {
15098        let c = state.candidates[i].clone();
15099        let is_winner = Some(c.label) == winner;
15100        if is_winner && !drop_winner {
15101            continue;
15102        }
15103        let existed = c.worktree.exists();
15104        let target = fold_target(home, &root, &c.worktree, isolated);
15105        // A vanished directory can still have a Git registration that keeps
15106        // its branch checked out. Remove that registration before the branch.
15107        remove_preserved_worktree(&repo, &c.worktree).await?;
15108        reclaim_fold_target(home, target);
15109        if existed {
15110            removed.push(c.worktree.to_string_lossy().into_owned());
15111        }
15112        // A branch handed to a later run (and its pull request) is not this
15113        // run's to delete.
15114        let handed_over = state.released_branches.contains(&c.branch);
15115        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
15116            if !git::branch_delete(&repo, &c.branch).await? {
15117                bail!("candidate branch removal refused");
15118            }
15119            removed.push(c.branch.clone());
15120        }
15121        state.candidates[i].folded = true;
15122    }
15123
15124    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
15125        let path = name.path();
15126        let keep = !drop_winner
15127            && winner.is_some_and(|w| {
15128                path.file_name()
15129                    .is_some_and(|n| n == format!("cand-{w}").as_str())
15130            });
15131        if keep {
15132            continue;
15133        }
15134        let target = fold_target(home, &root, &path, isolated);
15135        remove_read_seat_worktree(state, &path).await?;
15136        reclaim_fold_target(home, target);
15137        removed.push(path.to_string_lossy().into_owned());
15138    }
15139
15140    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
15141    // judge worktrees, so once the loop above has cleared all of them out,
15142    // the parent is a bare directory nobody else was ever going to remove -
15143    // git only ever managed what was inside it. Left alone, one of these
15144    // accumulates per fully-folded run; the operator's own machine had 74.
15145    // `remove_if_empty` re-checks rather than assuming: a run whose winner
15146    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
15147    // so does anything a run never claimed that happens to share the bay.
15148    remove_if_empty(&root);
15149
15150    if state.enabled_worktree_config && drop_winner {
15151        // A release, not a raw disable: some sibling run in this repository
15152        // may still hold its own reference (see `git::acquire_worktree_config`),
15153        // and only the last release actually turns the setting back off.
15154        git::release_worktree_config(&repo).await.ok();
15155        state.enabled_worktree_config = false;
15156    }
15157    // What this fold itself found, written in the same locked save: nothing
15158    // left to remove and no bay on disk (a failed or erroring check is not
15159    // "gone"). The busy-time fold turn skips such a run only while the bay is
15160    // still confirmed absent; any fold that found work clears the mark.
15161    state.fold_settled_at =
15162        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
15163    state.save_under(home)?;
15164    Ok(removed)
15165}
15166
15167async fn verify_merged_fold_sources(
15168    state: &RunState,
15169    drop_winner: bool,
15170    home: &Path,
15171) -> Result<Vec<std::fs::File>> {
15172    let winner = state.tally.as_ref().map(|t| t.winner);
15173    let mut heads = BTreeSet::new();
15174    for candidate in &state.candidates {
15175        if Some(candidate.label) == winner && !drop_winner {
15176            continue;
15177        }
15178        anyhow::ensure!(
15179            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
15180            "candidate recovery source is outside the inventoried run root: {}",
15181            candidate.worktree.display()
15182        );
15183        match std::fs::symlink_metadata(&candidate.worktree) {
15184            Ok(_) => {}
15185            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15186            Err(error) => return Err(error.into()),
15187        }
15188        if !state.released_branches.contains(&candidate.branch)
15189            && git::branch_exists(&state.repo, &candidate.branch).await?
15190        {
15191            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
15192        }
15193    }
15194    let mut cargo_guards = Vec::new();
15195    let entries = match std::fs::read_dir(state.worktree_root()) {
15196        Ok(entries) => Some(entries),
15197        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
15198        Err(error) => return Err(error.into()),
15199    };
15200    for entry in entries.into_iter().flatten() {
15201        let path = entry?.path();
15202        let metadata = std::fs::symlink_metadata(&path)?;
15203        anyhow::ensure!(
15204            metadata.is_dir() && !metadata.file_type().is_symlink(),
15205            "non-directory or symlink recovery source retained: {}",
15206            path.display()
15207        );
15208        if !drop_winner
15209            && winner.is_some_and(|w| {
15210                path.file_name()
15211                    .is_some_and(|name| name == format!("cand-{w}").as_str())
15212            })
15213        {
15214            continue;
15215        }
15216        anyhow::ensure!(
15217            path.join(".git").is_file(),
15218            "unregistered recovery source retained: {}",
15219            path.display()
15220        );
15221        anyhow::ensure!(
15222            git::git(
15223                &path,
15224                &[
15225                    "status",
15226                    "--porcelain",
15227                    "--untracked-files=all",
15228                    "--ignored",
15229                    "--",
15230                    ".",
15231                    ":(exclude)target"
15232                ]
15233            )
15234            .await?
15235            .is_empty(),
15236            "source changes or ignored recovery files retained: {}",
15237            path.display()
15238        );
15239        match std::fs::symlink_metadata(path.join("target")) {
15240            Ok(_) => {
15241                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
15242            }
15243            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15244            Err(error) => return Err(error.into()),
15245        }
15246        for checkpoint in [
15247            "rebase-merge",
15248            "rebase-apply",
15249            "sequencer",
15250            "CHERRY_PICK_HEAD",
15251            "MERGE_HEAD",
15252            "REBASE_HEAD",
15253            "REVERT_HEAD",
15254            "BISECT_LOG",
15255            "AUTO_MERGE",
15256            "MERGE_MSG",
15257        ] {
15258            let location = git::git(
15259                &path,
15260                &[
15261                    "rev-parse",
15262                    "--path-format=absolute",
15263                    "--git-path",
15264                    checkpoint,
15265                ],
15266            )
15267            .await?;
15268            anyhow::ensure!(
15269                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15270                if e.kind() == std::io::ErrorKind::NotFound),
15271                "Git recovery checkpoint retained: {checkpoint}"
15272            );
15273        }
15274        heads.insert(git::rev_parse(&path, "HEAD").await?);
15275    }
15276    crate::fold_evidence::preserve(state, home, &heads).await?;
15277
15278    Ok(cargo_guards)
15279}
15280
15281/// Remove `dir` if it exists and has nothing in it.
15282///
15283/// Best-effort and silent by design: a directory that is not empty (a run
15284/// whose winner is still parked there, a stray file some other process left)
15285/// is exactly the case this must refuse, and a directory that is already gone
15286/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15287/// already refuses a non-empty directory, so the emptiness check below is
15288/// belt, not suspenders - it is what keeps this from ever attempting the
15289/// removal in the case that matters, rather than trusting `remove_dir`'s
15290/// error path to have no side effects if it ever changed.
15291fn remove_if_empty(dir: &Path) {
15292    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15293        std::fs::remove_dir(dir).ok();
15294    }
15295}
15296
15297/// Severity of the worst open finding in the last review round, for reporting.
15298pub fn worst_open(state: &RunState) -> Option<Severity> {
15299    state
15300        .reviews
15301        .last()?
15302        .reviews
15303        .iter()
15304        .flat_map(|r| r.findings.iter())
15305        .map(|f| f.severity)
15306        .max()
15307}
15308
15309/// `[worktree] setup` hides its products per worktree, which needs
15310/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15311/// worktrees, like the hook's; every place that runs setup calls this first.
15312async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15313    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15314        git::acquire_worktree_config(repo).await?;
15315        state.enabled_worktree_config = true;
15316    }
15317    Ok(())
15318}
15319
15320#[cfg(test)]
15321mod tests {
15322    #[tokio::test]
15323    async fn launcher_base_fetch_requires_remote_success() {
15324        let tmp = tempfile::tempdir().unwrap();
15325        let repo = tmp.path().join("repo");
15326        let remote = tmp.path().join("remote");
15327        std::fs::create_dir(&repo).unwrap();
15328        std::fs::create_dir(&remote).unwrap();
15329        git::git(&remote, &["init", "--bare", "-b", "main"])
15330            .await
15331            .unwrap();
15332        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15333        git::git(
15334            &repo,
15335            &[
15336                "-c",
15337                "user.name=Fixture",
15338                "-c",
15339                "user.email=fixture@example.invalid",
15340                "commit",
15341                "--allow-empty",
15342                "-m",
15343                "fixture",
15344            ],
15345        )
15346        .await
15347        .unwrap();
15348        git::git(
15349            &repo,
15350            &["remote", "add", "origin", remote.to_str().unwrap()],
15351        )
15352        .await
15353        .unwrap();
15354        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15355        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15356        assert_eq!(
15357            resolve_base(&repo, "main", "origin", None)
15358                .await
15359                .unwrap()
15360                .commit,
15361            head
15362        );
15363        #[cfg(unix)]
15364        {
15365            let policy: crate::config::Coordination = toml::from_str(
15366                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15367            ).unwrap();
15368            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15369            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15370            let held = crate::repo_lock::SeatLease::operation_with(
15371                &repo,
15372                Some(&policy),
15373                &crate::repo_lock::WaitPolicy::default(),
15374            )
15375            .await
15376            .unwrap();
15377            assert!(held.is_some());
15378            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15379            tokio::pin!(fetch);
15380            assert!(
15381                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15382                    .await
15383                    .is_err()
15384            );
15385            assert!(
15386                !repo.join(".git/FETCH_HEAD").exists(),
15387                "no fetch before admission"
15388            );
15389            drop(held);
15390            let fetched = fetch.await.unwrap();
15391            assert_eq!(fetched.commit, head);
15392            assert_eq!(fetched.remote, "origin");
15393            assert_eq!(fetched.branch, "main");
15394        }
15395        // A surviving tracking ref is not successful fetch evidence.
15396        git::git(
15397            &repo,
15398            &[
15399                "remote",
15400                "set-url",
15401                "origin",
15402                tmp.path().join("missing").to_str().unwrap(),
15403            ],
15404        )
15405        .await
15406        .unwrap();
15407        let error = resolve_base(&repo, "main", "origin", None)
15408            .await
15409            .unwrap_err()
15410            .to_string();
15411        assert!(error.contains("cannot read origin/main"));
15412        assert!(error.contains("refusing to branch off"));
15413    }
15414
15415    #[test]
15416    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15417        let leaked = vec!["chore(deps): update a crate".to_owned()];
15418        let own = "fix(daemon): apply a chosen action";
15419        assert!(should_retitle("", own, &leaked));
15420        assert!(should_retitle(
15421            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15422            own,
15423            &leaked
15424        ));
15425        assert!(should_retitle(
15426            "chore: land candidate A of run 1",
15427            own,
15428            &leaked
15429        ));
15430        assert!(should_retitle(
15431            "magi: candidate A (uncommitted work)",
15432            own,
15433            &leaked
15434        ));
15435        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15436        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15437        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15438    }
15439
15440    #[test]
15441    fn pr_merge_plan_creates_adopts_or_stops() {
15442        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15443        assert_eq!(
15444            pr_merge_plan(Ok(land::OpenPr::One {
15445                url: "u".into(),
15446                title: "t".into()
15447            })),
15448            PrPlan::Adopt {
15449                url: "u".into(),
15450                title: "t".into()
15451            }
15452        );
15453        let PrPlan::Stop(many) =
15454            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15455        else {
15456            panic!("many must stop");
15457        };
15458        assert!(many.contains('a') && many.contains('b'));
15459        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15460            panic!("a failed lookup must stop");
15461        };
15462        assert!(err.contains("bad token"));
15463    }
15464
15465    use super::*;
15466    use crate::run::GateStatus;
15467    use std::collections::BTreeMap;
15468    use std::time::Duration;
15469
15470    fn conductor() -> AgentSpec {
15471        AgentSpec {
15472            id: "conductor".to_owned(),
15473            kind: crate::config::AgentKind::Command,
15474            model: None,
15475            command: vec!["true".to_owned()],
15476            extra_args: Vec::new(),
15477            env: BTreeMap::new(),
15478            prompt_delivery: None,
15479            max_turn_secs: None,
15480        }
15481    }
15482
15483    fn spec(id: &str) -> AgentSpec {
15484        AgentSpec {
15485            id: id.to_owned(),
15486            kind: crate::config::AgentKind::Command,
15487            model: None,
15488            command: vec!["true".to_owned()],
15489            extra_args: Vec::new(),
15490            env: BTreeMap::new(),
15491            prompt_delivery: None,
15492            max_turn_secs: None,
15493        }
15494    }
15495
15496    fn ids(xs: &[&str]) -> BTreeSet<String> {
15497        xs.iter().map(|s| (*s).to_owned()).collect()
15498    }
15499
15500    #[test]
15501    fn pick_successor_skips_an_agent_another_seat_holds() {
15502        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15503        let roster = [spec("a"), spec("b"), spec("c")];
15504        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15505        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15506    }
15507
15508    #[test]
15509    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15510        // The other seat started on c but was handed to d; c is free again.
15511        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15512        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15513        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15514        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15515        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15516    }
15517
15518    #[test]
15519    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15520        let roster = [spec("a"), spec("b")];
15521        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15522        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15523        let carried = ids(&["b"]);
15524        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15525        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15526    }
15527
15528    #[test]
15529    fn pick_successor_returns_none_without_any_untried_successor() {
15530        let roster = [spec("a"), spec("b")];
15531        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15532        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15533        let carried = ids(&["a"]);
15534        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15535    }
15536
15537    #[test]
15538    fn pick_successor_rescue_avoids_another_seats_occupant() {
15539        // b is a carried failure and free; a is held by the other seat.
15540        let roster = [spec("a"), spec("b"), spec("c")];
15541        let carried = ids(&["b", "c"]);
15542        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15543        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15544    }
15545
15546    #[test]
15547    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15548        let roster = [spec("a"), spec("b"), spec("c")];
15549        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15550        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15551    }
15552
15553    #[test]
15554    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15555        let roster = [spec("a"), spec("b"), spec("c")];
15556        let failed = ids(&["a", "b", "c"]);
15557        // Rescue looks at the whole roster, once per id, then runs out.
15558        let mut tried = ids(&["b"]);
15559        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15560        assert_eq!(first.id, "a");
15561        tried.insert(first.id.clone());
15562        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15563        assert_eq!(second.id, "c");
15564        tried.insert(second.id.clone());
15565        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15566    }
15567
15568    #[test]
15569    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15570        let roster = [spec("a"), spec("b")];
15571        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15572        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15573    }
15574
15575    #[test]
15576    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15577        let roster = [spec("a"), spec("b"), spec("c")];
15578        let h = SeatHistory {
15579            failed: ids(&["a"]),
15580            last_ok: Some("b".to_owned()),
15581            last_fail: None,
15582        };
15583        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15584        // A last answerer that left the roster, or later failed, is ignored.
15585        let gone = SeatHistory {
15586            last_ok: Some("zzz".to_owned()),
15587            ..h.clone()
15588        };
15589        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15590        let failed = SeatHistory {
15591            failed: ids(&["a", "b"]),
15592            last_ok: Some("b".to_owned()),
15593            last_fail: None,
15594        };
15595        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15596    }
15597
15598    #[test]
15599    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15600        let first = SeatState::new("review-1", "alpha", 7);
15601        let next = handover_seat("review-1", "gamma", 7);
15602        assert_ne!(first.claude_session, next.claude_session);
15603    }
15604
15605    #[test]
15606    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15607        let mut state = state_with_summary("x", "y");
15608        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15609        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15610        assert_ne!(a.claude_session, b.claude_session);
15611    }
15612
15613    #[test]
15614    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15615        let roster = [spec("a"), spec("b")];
15616        let h = SeatHistory {
15617            failed: ids(&["a", "b"]),
15618            ..SeatHistory::default()
15619        };
15620        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15621        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15622        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15623    }
15624
15625    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15626    // fallback loop depends on to terminate: it must walk forward from the
15627    // seat's own position, never restart at the front of the roster, and it
15628    // must never hand back an id already tried, however many times that id
15629    // happens to appear.
15630
15631    #[test]
15632    fn failure_signature_ignores_numbers_and_paths() {
15633        assert_eq!(
15634            failure_signature("exited with Some(2) and no usable output"),
15635            failure_signature("exited with Some(137) and no usable output")
15636        );
15637        assert_eq!(
15638            failure_signature("process exited with no usable output (exit code 2)"),
15639            failure_signature("process exited with no usable output (exit code 137)")
15640        );
15641        for (old, new) in [
15642            (
15643                "exited with Some(2) and no usable output",
15644                "process exited with no usable output (exit code 2)",
15645            ),
15646            (
15647                "exited with None and no usable output",
15648                "process exited with no usable output (exit code unavailable)",
15649            ),
15650        ] {
15651            let previous = FailClass::Other(failure_signature(old));
15652            let current = FailClass::Other(failure_signature(new));
15653            assert_eq!(previous, current, "resumption retains the failure class");
15654            assert!(!should_hand_over(Some(&previous), &current));
15655        }
15656        assert_eq!(
15657            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15658            failure_signature("cannot open /var/x.txt: denied")
15659        );
15660        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15661    }
15662
15663    #[test]
15664    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15665        let other = FailClass::Other("x".into());
15666        assert!(should_hand_over(None, &FailClass::Quota));
15667        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15668        assert!(should_hand_over(
15669            Some(&FailClass::Timeout),
15670            &FailClass::Timeout
15671        ));
15672        assert!(should_hand_over(None, &other));
15673        assert!(!should_hand_over(Some(&other), &other));
15674        assert!(should_hand_over(
15675            Some(&other),
15676            &FailClass::Other("y".into())
15677        ));
15678        // A quota or timeout in between ends the run of identical failures.
15679        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15680        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15681    }
15682
15683    #[test]
15684    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15685        let a = SeatState::new("judge-1", "alpha", 7);
15686        let b = handover_seat("judge-1", "beta", 7);
15687        assert_ne!(a.claude_session, b.claude_session);
15688        assert_eq!(b.turns, 0);
15689    }
15690
15691    #[test]
15692    fn a_timeout_is_classified_apart_from_other_failures() {
15693        assert_eq!(
15694            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15695            Some(FailClass::Timeout)
15696        );
15697        assert!(matches!(
15698            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15699            Some(FailClass::Other(_))
15700        ));
15701    }
15702
15703    #[test]
15704    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15705        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15706        let tried = BTreeSet::from(["beta".to_owned()]);
15707        // beta sits at index 1; the next candidate is gamma, never alpha —
15708        // which is very likely a different candidate slot's own agent.
15709        let next = next_untried_in_roster(&roster, 1, &tried);
15710        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15711    }
15712
15713    #[test]
15714    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15715        let roster = vec![spec("alpha"), spec("beta")];
15716        let tried = BTreeSet::from(["beta".to_owned()]);
15717        // beta is the roster's last entry: nothing follows it, and alpha —
15718        // earlier in the roster, almost certainly a different candidate
15719        // slot's own agent — must not be reached by wrapping back to it.
15720        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15721    }
15722
15723    #[test]
15724    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15725        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15726        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15727        // beta (index 1) and gamma (index 2, the only entry after it) have
15728        // both been tried; alpha (index 0) never has, but it comes before
15729        // beta's own position, so there is nothing further for this seat.
15730        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15731    }
15732
15733    #[test]
15734    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15735        let roster = vec![spec("a"), spec("a"), spec("b")];
15736        let tried = BTreeSet::from(["a".to_owned()]);
15737        let next = next_untried_in_roster(&roster, 0, &tried);
15738        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15739    }
15740
15741    #[test]
15742    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15743        let roster = vec![spec("a"), spec("b")];
15744        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15745        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15746    }
15747
15748    #[test]
15749    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15750        let dir = tempfile::tempdir().unwrap();
15751        let bay = dir.path().join("ffff");
15752
15753        // Not there yet: nothing to do, nothing to panic on.
15754        remove_if_empty(&bay);
15755        assert!(!bay.exists());
15756
15757        // Something still inside - the winner's worktree, or a stray file -
15758        // keeps the directory standing.
15759        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15760        remove_if_empty(&bay);
15761        assert!(bay.exists(), "non-empty directory must survive");
15762
15763        // Once the last entry is gone, so is the directory itself.
15764        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15765        remove_if_empty(&bay);
15766        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15767    }
15768
15769    // `round_is_clean` is the exact decision this task fixed: a round with a
15770    // seat that never answered must not read the same as a round every seat
15771    // actually reviewed. These are deterministic and process-free by design —
15772    // the equivalent end-to-end check (a real reviewer timing out under a
15773    // live graph run) is a genuine race against wall-clock contention, and a
15774    // spawn slow enough to blow even a generous budget under a loaded test
15775    // run must not turn this specific regression check flaky.
15776
15777    #[test]
15778    fn a_full_panel_that_found_nothing_is_clean() {
15779        assert!(round_is_clean(
15780            0,
15781            true,
15782            2,
15783            2,
15784            0,
15785            IncompleteReviewPolicy::Block
15786        ));
15787    }
15788
15789    #[test]
15790    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15791        assert!(!round_is_clean(
15792            0,
15793            true,
15794            1,
15795            2,
15796            0,
15797            IncompleteReviewPolicy::Block
15798        ));
15799    }
15800
15801    #[test]
15802    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15803        assert!(!round_is_clean(
15804            1,
15805            true,
15806            1,
15807            2,
15808            0,
15809            IncompleteReviewPolicy::Warn
15810        ));
15811    }
15812
15813    #[test]
15814    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15815        assert!(round_is_clean(
15816            0,
15817            true,
15818            1,
15819            2,
15820            0,
15821            IncompleteReviewPolicy::Warn
15822        ));
15823    }
15824
15825    #[test]
15826    fn a_full_panel_with_an_open_finding_is_not_clean() {
15827        assert!(!round_is_clean(
15828            1,
15829            true,
15830            2,
15831            2,
15832            0,
15833            IncompleteReviewPolicy::Block
15834        ));
15835    }
15836
15837    #[test]
15838    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15839        assert!(!round_is_clean(
15840            0,
15841            false,
15842            2,
15843            2,
15844            0,
15845            IncompleteReviewPolicy::Block
15846        ));
15847    }
15848
15849    // The stall this task closes: under the default `block` policy, a seat
15850    // missing only because it was rate limited must not force a wait for a
15851    // session limit that will not lift by the next round. `round_is_clean`
15852    // is where that quorum carve-out lives; the review loop around it never
15853    // changes what a reviewer's vote or a finding's severity means.
15854
15855    #[test]
15856    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15857        // 1 of 2 answered, and the one missing was quota'd — the exact
15858        // "review-2 rate limited (quota)" shape from the field report.
15859        assert!(round_is_clean(
15860            0,
15861            true,
15862            1,
15863            2,
15864            1,
15865            IncompleteReviewPolicy::Block
15866        ));
15867    }
15868
15869    #[test]
15870    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15871        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15872        // not a quota loss (`quota_missing` stays 0) — worth another try.
15873        assert!(!round_is_clean(
15874            0,
15875            true,
15876            1,
15877            2,
15878            0,
15879            IncompleteReviewPolicy::Block
15880        ));
15881    }
15882
15883    #[test]
15884    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15885        assert!(!round_is_clean(
15886            1,
15887            true,
15888            1,
15889            2,
15890            1,
15891            IncompleteReviewPolicy::Block
15892        ));
15893        assert!(!round_is_clean(
15894            0,
15895            false,
15896            1,
15897            2,
15898            1,
15899            IncompleteReviewPolicy::Block
15900        ));
15901    }
15902
15903    #[test]
15904    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15905        // Every seat quota'd, nobody answered: there is no panel to decide
15906        // on, so this must fall through to the existing block-and-retry
15907        // fallback rather than call an unreviewed patch clean.
15908        assert!(!round_is_clean(
15909            0,
15910            true,
15911            0,
15912            2,
15913            2,
15914            IncompleteReviewPolicy::Block
15915        ));
15916    }
15917
15918    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15919        CommandOutcome {
15920            command: "test".to_owned(),
15921            code,
15922            output_tail: String::new(),
15923            duration_ms: 0,
15924            resource_blocked,
15925            ..Default::default()
15926        }
15927    }
15928
15929    #[cfg(unix)]
15930    #[tokio::test]
15931    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15932        ask_test_home();
15933        let temp = tempfile::tempdir().unwrap();
15934        let mut runner = runner_at(RunStatus::Gating);
15935        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15936        let commands = vec![
15937            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15938            "touch must-not-run".to_owned(),
15939        ];
15940        let (outcomes, retried, pids) = run_e2e_with_retry(
15941            &mut runner.state,
15942            &shell,
15943            &commands,
15944            temp.path(),
15945            Duration::from_secs(5),
15946            "fixture",
15947            None,
15948        )
15949        .await;
15950        assert_eq!(outcomes.len(), 1);
15951        assert!(outcomes[0].resource_blocked);
15952        assert!(!outcomes[0].build_failed());
15953        assert!(!retried);
15954        assert!(pids.is_empty());
15955        assert!(!temp.path().join("must-not-run").exists());
15956        assert_eq!(
15957            runner.state.resource_block.as_ref().unwrap().kind,
15958            "incremental cache admission"
15959        );
15960    }
15961
15962    #[test]
15963    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15964        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15965        assert!(
15966            !verify_inconclusive(&[outcome(Some(1), false)]),
15967            "an ordinary failure is still evidence about the patch"
15968        );
15969        assert!(verify_inconclusive(&[outcome(None, true)]));
15970        assert!(
15971            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15972            "one inconclusive outcome taints the whole batch"
15973        );
15974        assert!(!verify_inconclusive(&[]));
15975    }
15976
15977    #[tokio::test]
15978    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15979        // Alive for the first two checks, then dead - confirms the loop
15980        // actually re-polls rather than deciding once and sleeping out the
15981        // ceiling regardless.
15982        let calls = std::sync::atomic::AtomicUsize::new(0);
15983        let started = Instant::now();
15984        wait_for_pids_with(
15985            &[123],
15986            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15987            Duration::from_millis(5),
15988            Duration::from_secs(5),
15989        )
15990        .await;
15991        assert!(
15992            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15993            "must keep checking rather than deciding on the first answer"
15994        );
15995        assert!(
15996            started.elapsed() < Duration::from_secs(1),
15997            "must return the moment it is confirmed dead, not wait out the ceiling"
15998        );
15999    }
16000
16001    #[tokio::test]
16002    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
16003        let started = Instant::now();
16004        wait_for_pids_with(
16005            &[123],
16006            |_| true, // never reports dead
16007            Duration::from_millis(5),
16008            Duration::from_millis(30),
16009        )
16010        .await;
16011        let elapsed = started.elapsed();
16012        assert!(
16013            elapsed >= Duration::from_millis(30),
16014            "must not give up before its own ceiling: {elapsed:?}"
16015        );
16016        assert!(
16017            elapsed < Duration::from_secs(1),
16018            "must not wait past its own ceiling either: {elapsed:?}"
16019        );
16020    }
16021
16022    #[tokio::test]
16023    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
16024        let started = Instant::now();
16025        wait_for_pids_with(
16026            &[],
16027            |_| true,
16028            Duration::from_secs(5),
16029            Duration::from_secs(5),
16030        )
16031        .await;
16032        assert!(
16033            started.elapsed() < Duration::from_millis(200),
16034            "an empty pid list has nothing to confirm"
16035        );
16036    }
16037
16038    // `review_conclusion` is the exact decision the review hand-off task
16039    // fixed: a round budget spent (or a tree that stopped moving) must not
16040    // collapse into `Blocked` regardless of what verification actually
16041    // said. Deterministic and process-free for the same reason the
16042    // `round_is_clean` family above is.
16043    fn review_round(
16044        clean: bool,
16045        blocking: usize,
16046        answered: usize,
16047        expected: usize,
16048        progressed: bool,
16049        e2e_ok: bool,
16050    ) -> ReviewRound {
16051        ReviewRound {
16052            round: 1,
16053            head: "h".to_owned(),
16054            verified_head: None,
16055            verified_at: None,
16056            reviews: Vec::new(),
16057            e2e: vec![CommandOutcome {
16058                command: "test".to_owned(),
16059                code: Some(if e2e_ok { 0 } else { 1 }),
16060                output_tail: String::new(),
16061                duration_ms: 0,
16062                resource_blocked: false,
16063                ..Default::default()
16064            }],
16065            verify_retried: false,
16066            e2e_deferred: false,
16067            e2e_defer_reason: None,
16068            fix: None,
16069            blocking,
16070            answered,
16071            expected,
16072            clean,
16073            progressed,
16074            vote_split: false,
16075            reconsideration: Vec::new(),
16076            verdict: None,
16077        }
16078    }
16079
16080    #[test]
16081    fn review_conclusion_is_none_when_nothing_has_run() {
16082        assert_eq!(review_conclusion(&[], 3), None);
16083    }
16084
16085    #[test]
16086    fn review_conclusion_is_none_while_rounds_remain() {
16087        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
16088        assert_eq!(review_conclusion(&rounds, 3), None);
16089    }
16090
16091    #[test]
16092    fn review_conclusion_is_gating_once_a_round_is_clean() {
16093        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
16094        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
16095    }
16096
16097    #[test]
16098    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
16099        let rounds = vec![
16100            review_round(false, 1, 2, 2, true, true),
16101            review_round(false, 1, 2, 2, true, true),
16102        ];
16103        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
16104    }
16105
16106    #[test]
16107    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
16108        let rounds = vec![
16109            review_round(false, 1, 2, 2, true, true),
16110            review_round(false, 1, 2, 2, true, false),
16111        ];
16112        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
16113    }
16114
16115    #[test]
16116    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
16117        // Magi never got a command to run against this round's own head — a
16118        // resource-blocked attempt, not a red one — so this must never
16119        // settle on `Blocked` the way a genuine e2e failure would. `None`
16120        // here is what tells `Runner::review_loop` to retry the check
16121        // itself rather than trust this cheap recomputation with a verdict
16122        // it cannot actually produce.
16123        let mut blocked = review_round(false, 1, 2, 2, true, false);
16124        blocked.e2e[0].resource_blocked = true;
16125        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
16126        assert_eq!(review_conclusion(&rounds, 2), None);
16127    }
16128
16129    #[test]
16130    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
16131        // Missing input, not a verified tree — never a hand-off candidate.
16132        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
16133        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
16134    }
16135
16136    #[test]
16137    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
16138        let rounds = vec![
16139            review_round(false, 1, 2, 2, false, true),
16140            review_round(false, 1, 2, 2, false, true),
16141        ];
16142        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
16143    }
16144
16145    fn secs(n: u64) -> Duration {
16146        Duration::from_secs(n)
16147    }
16148
16149    /// A throwaway repo with one commit on `main`, for tests that need `merge`
16150    /// to make real (and, if it runs at all, real*ly fail*) git calls.
16151    #[tokio::test]
16152    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
16153        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
16154        if std::env::var_os(CHILD).is_none() {
16155            // Other tests reconcile every run in the process-global home,
16156            // briefly taking owner locks. This ancestry test expects an idle
16157            // predecessor, so give it its own process and pinned test home.
16158            let output = std::process::Command::new(std::env::current_exe().unwrap())
16159                .args([
16160                    "--exact",
16161                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
16162                    "--nocapture",
16163                ])
16164                .env(CHILD, "1")
16165                .env_remove("MAGI_WORKER_HOME")
16166                .env_remove("MAGI_WORKER_ID")
16167                .output()
16168                .unwrap();
16169            assert!(
16170                output.status.success()
16171                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
16172                "{}\n{}",
16173                String::from_utf8_lossy(&output.stdout),
16174                String::from_utf8_lossy(&output.stderr)
16175            );
16176            return;
16177        }
16178        ask_test_home();
16179        let tmp = tempfile::tempdir().unwrap();
16180        let repo = tmp.path().join("repo");
16181        std::fs::create_dir_all(&repo).unwrap();
16182        init_repo(&repo);
16183        let g = |args: &[&str]| {
16184            let out = std::process::Command::new("git")
16185                .args(args)
16186                .current_dir(&repo)
16187                .quiet()
16188                .output()
16189                .unwrap();
16190            assert!(
16191                out.status.success(),
16192                "{}",
16193                String::from_utf8_lossy(&out.stderr)
16194            );
16195        };
16196        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16197        g(&["checkout", "-b", "historical"]);
16198        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
16199        g(&["add", "."]);
16200        g(&["commit", "-m", "old alternative"]);
16201        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
16202        g(&["checkout", "-b", "magi/task-selected", &base]);
16203        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
16204        g(&["add", "."]);
16205        g(&["commit", "-m", "measurement infrastructure"]);
16206        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
16207        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
16208        g(&["add", "."]);
16209        g(&["commit", "-m", "dependent implementation"]);
16210        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
16211        g(&["checkout", "main"]);
16212        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
16213        g(&["add", "."]);
16214        g(&["commit", "-m", "unrelated base change"]);
16215        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
16216        let origin = tmp.path().join("origin.git");
16217        g(&[
16218            "clone",
16219            "--bare",
16220            repo.to_str().unwrap(),
16221            origin.to_str().unwrap(),
16222        ]);
16223        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
16224        g(&["fetch", "origin"]);
16225        let selection = crate::pr_recovery::Selection {
16226            url: "https://example.test/project/pull/1".into(),
16227            branch: "magi/task-selected".into(),
16228            head: head.clone(),
16229            source_head: None,
16230            source_run: None,
16231            source_proof: None,
16232            disposition: Some(crate::pr_recovery::Disposition::Review),
16233            instruction: "preserve measured behavior".into(),
16234            approved_at: jiff::Timestamp::now(),
16235        };
16236        let mut template = runner_at(RunStatus::Reviewing);
16237        template.state.repo = repo.clone();
16238        template.state.base_commit = current.clone();
16239        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16240        template.state.origin = Some(crate::run::Origin::queue("selected"));
16241        template.state.pr_head = Some(selection.branch.clone());
16242        template.state.pr_recovery = Some(selection.clone());
16243        let mut runner =
16244            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
16245                .await
16246                .unwrap();
16247        let wt = runner.state.winner().unwrap().worktree.clone();
16248        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16249        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16250        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16251        assert!(runner.state.seeds.is_empty());
16252        assert_eq!(runner.state.instruction, "preserve measured behavior");
16253        runner.sync_to_base().await.unwrap();
16254        assert_eq!(
16255            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16256            "prerequisite"
16257        );
16258        assert_eq!(
16259            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16260            "measured implementation"
16261        );
16262        assert_eq!(
16263            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16264            "current main change"
16265        );
16266        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16267        assert_eq!(
16268            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16269            head
16270        );
16271
16272        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16273        let mut partial = runner_at(RunStatus::Reviewing);
16274        partial.state.repo = repo.clone();
16275        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16276        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16277            run: Some("exit 1".into()),
16278            ..Default::default()
16279        }];
16280        let selection = runner.state.pr_recovery.clone().unwrap();
16281        partial.state.pr_recovery = Some(selection.clone());
16282        partial.state.pr_head = Some(selection.branch.clone());
16283        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16284        let id = partial.state.id.clone();
16285        let error = match Runner::open_selected(
16286            &repo,
16287            partial.state,
16288            partial.roles,
16289            1,
16290            runner.state.base_commit.clone(),
16291            selection,
16292        )
16293        .await
16294        {
16295            Ok(_) => panic!("setup must fail"),
16296            Err(e) => e,
16297        };
16298        assert_eq!(
16299            error
16300                .downcast_ref::<crate::run::StartupFailure>()
16301                .unwrap()
16302                .run,
16303            id
16304        );
16305        let failed = RunState::load(&id).unwrap();
16306        assert_eq!(failed.status, RunStatus::Failed);
16307        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16308        assert!(Runner::resume(&id).is_err());
16309        runner.state.status = RunStatus::Ready;
16310        runner.state.driver_exited = true;
16311        runner.state.save().unwrap();
16312        let mut retry = runner_at(RunStatus::Reviewing);
16313        retry.state.repo = repo.clone();
16314        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16315        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16316        reselected.approved_at = jiff::Timestamp::now();
16317        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16318        retry.state.pr_head = Some(reselected.branch.clone());
16319        retry.state.pr_recovery = Some(reselected.clone());
16320        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16321            .await
16322            .unwrap();
16323        let restarted = Runner::open_selected(
16324            &repo,
16325            retry.state,
16326            retry.roles,
16327            1,
16328            runner.state.base_commit.clone(),
16329            reselected,
16330        )
16331        .await
16332        .unwrap();
16333        assert_eq!(
16334            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16335                .await
16336                .unwrap(),
16337            head
16338        );
16339        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16340        assert_eq!(
16341            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16342            head
16343        );
16344    }
16345
16346    #[tokio::test]
16347    #[cfg(unix)]
16348    async fn fallback_and_interrupted_restoration_require_coordination() {
16349        use std::os::fd::AsRawFd as _;
16350        ask_test_home();
16351        let tmp = tempfile::tempdir().unwrap();
16352        let mut runner = registered_runner(tmp.path()).await;
16353        runner.state.config.graph.timeout_resource_wait = 1;
16354        let winner = runner.state.candidates[0].clone();
16355        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16356        let leftover = winner.worktree.join("leftover");
16357        std::fs::write(&leftover, "untrusted edits").unwrap();
16358        let next = tmp.path().join("next-fixer");
16359        let mut failed = spec("first");
16360        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16361        let mut successor = spec("second");
16362        successor.command = vec![
16363            "sh".into(),
16364            "-c".into(),
16365            format!("touch '{}'; echo done", next.display()),
16366        ];
16367        let attempts = vec![
16368            (failed.clone(), "first".into()),
16369            (successor.clone(), "second".into()),
16370        ];
16371        let lock_path = runner.state.repo.join(".git/updater.lock");
16372        let external = std::fs::File::create(&lock_path).unwrap();
16373        assert_eq!(
16374            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16375            0
16376        );
16377        let artifacts = tmp.path().join("artifacts");
16378        let build = |spec, seat| SeatJob {
16379            spec,
16380            seat,
16381            cwd: winner.worktree.clone(),
16382            prompt: "fixture".into(),
16383            timeout: Duration::from_secs(10),
16384            allow_write: true,
16385            sessions: false,
16386            artifacts: artifacts.clone(),
16387            stem: "fix".into(),
16388            handover: None,
16389        };
16390        let (_, _, out) = runner
16391            .ask_fixer_among(
16392                attempts.clone(),
16393                "graft",
16394                None,
16395                Some((&winner.worktree, &head)),
16396                build,
16397            )
16398            .await;
16399        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16400        assert!(leftover.exists(), "contention must prevent clean");
16401        assert!(!next.exists());
16402        assert!(runner.state.handovers.is_empty());
16403        // Early interrupted-repair rollback uses the same protected route.
16404        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16405            from_run: "earlier".into(),
16406            generation: 1,
16407            mode: crate::recovery::Mode::VerifyRepair,
16408            reasons: Vec::new(),
16409            reviewed_head: None,
16410            rounds: Vec::new(),
16411            open_findings: Vec::new(),
16412            evidence: None,
16413            criteria_inherited: true,
16414            repair: crate::recovery::Repair::Started {
16415                before: head.clone(),
16416            },
16417        });
16418        assert!(
16419            runner
16420                .recovery_repair(&winner)
16421                .await
16422                .unwrap_err()
16423                .is::<crate::repo_lock::ResourceBlocked>()
16424        );
16425        assert!(matches!(
16426            runner.state.recovery.as_ref().unwrap().repair,
16427            crate::recovery::Repair::Started { .. }
16428        ));
16429        assert!(leftover.exists());
16430        drop(external);
16431        runner.recovery_repair(&winner).await.unwrap();
16432        assert!(!leftover.exists());
16433        assert!(matches!(
16434            runner.state.recovery.as_ref().unwrap().repair,
16435            crate::recovery::Repair::Done { .. }
16436        ));
16437        // A hard lock-open failure also leaves HEAD and untracked work intact.
16438        std::fs::remove_file(&lock_path).unwrap();
16439        std::fs::create_dir(&lock_path).unwrap();
16440        std::fs::write(&leftover, "untrusted edits").unwrap();
16441        let (_, _, out) = runner
16442            .ask_fixer_among(
16443                attempts,
16444                "graft",
16445                None,
16446                Some((&winner.worktree, &head)),
16447                build,
16448            )
16449            .await;
16450        assert!(matches!(out, AgentOutcome::Failed(_)));
16451        assert!(leftover.exists());
16452        assert!(!next.exists());
16453        assert_eq!(
16454            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16455            head
16456        );
16457    }
16458
16459    #[cfg(unix)]
16460    async fn registered_runner(root: &Path) -> Runner {
16461        repository_runner(root, crate::config::test_coordination()).await
16462    }
16463
16464    async fn repository_runner(
16465        root: &Path,
16466        coordination: Option<crate::config::Coordination>,
16467    ) -> Runner {
16468        ask_test_home();
16469        let repo = root.join("repo");
16470        std::fs::create_dir_all(&repo).unwrap();
16471        init_repo(&repo);
16472        if coordination.is_some() {
16473            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16474        }
16475        let mut runner = runner_at(RunStatus::Prep);
16476        runner.state.repo = repo.clone();
16477        runner.state.config.coordination = coordination;
16478        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16479        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16480        runner.state.config.graph.advise = false;
16481        runner.roles.implementers = vec![spec("implement")];
16482        runner.roles.judges = vec![spec("judge")];
16483        runner.prep().await.unwrap();
16484        runner
16485    }
16486
16487    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16488
16489    #[tokio::test]
16490    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16491        let tmp = tempfile::tempdir().unwrap();
16492        let mut runner = repository_runner(tmp.path(), None).await;
16493        let prompts = runner.state.config.prompts.clone();
16494        let run = runner.state.id.clone();
16495        let ctx = WaveCtx {
16496            carry_seats: false,
16497            pauses: None,
16498            run: &run,
16499            node: "advise",
16500            prompts: &prompts,
16501            cache: None,
16502            round: None,
16503        };
16504        let jobs: Vec<_> = ["alpha", "beta"]
16505            .into_iter()
16506            .map(|id| SeatJob {
16507                spec: scripted(id, AUTH_OUTAGE),
16508                seat: SeatState::new(id, id, 7),
16509                prompt: "propose".into(),
16510                cwd: runner.state.candidates[0].worktree.clone(),
16511                timeout: Duration::from_secs(10),
16512                allow_write: false,
16513                sessions: false,
16514                artifacts: agent::artifacts_dir(&runner.state.dir()),
16515                stem: id.into(),
16516                handover: None,
16517            })
16518            .collect();
16519        let mut losses = Vec::new();
16520        let results = ask_wave_with(
16521            jobs.clone(),
16522            runner.sem.clone(),
16523            2,
16524            &[],
16525            &ctx,
16526            &mut losses,
16527            &mut runner.state,
16528            &|_: &str| Ok(()),
16529        )
16530        .await;
16531        assert!(
16532            results
16533                .iter()
16534                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16535        );
16536        assert_eq!(runner.state.quota.len(), 2);
16537        assert!(
16538            runner
16539                .state
16540                .quota
16541                .iter()
16542                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16543        );
16544        assert!(!runner.state.advise_attempted);
16545        runner.stop_for_resource().unwrap();
16546        assert_eq!(runner.state.status, RunStatus::Blocked);
16547        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16548        assert_eq!(
16549            runner.state.resource_block.as_ref().unwrap().kind,
16550            "agent authentication"
16551        );
16552        // A machine loss followed by an ordinary failure is not evidence
16553        // that the whole node was unavailable, and must not earn a refund.
16554        runner.state.resource_block = None;
16555        runner.state.quota.clear();
16556        let mut mixed = jobs;
16557        mixed[1].spec.command = vec!["false".into()];
16558        let results = ask_wave_with(
16559            mixed,
16560            runner.sem.clone(),
16561            0,
16562            &[],
16563            &ctx,
16564            &mut losses,
16565            &mut runner.state,
16566            &|_: &str| Ok(()),
16567        )
16568        .await;
16569        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16570        assert!(runner.state.resource_block.is_none());
16571        assert_eq!(losses.len(), 1);
16572    }
16573
16574    #[tokio::test]
16575    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16576        let tmp = tempfile::tempdir().unwrap();
16577        let mut runner = repository_runner(tmp.path(), None).await;
16578        let implementer = scripted("implement", AUTH_OUTAGE);
16579        runner.roles.implementers = vec![implementer.clone()];
16580        runner.state.config.agents = vec![implementer];
16581        runner.implement().await.unwrap();
16582        assert_eq!(runner.state.status, RunStatus::Blocked);
16583        assert_eq!(runner.state.quota.len(), 1);
16584        assert_eq!(
16585            runner.state.quota[0].cause,
16586            agent::QuotaCause::Authentication
16587        );
16588        let candidate = &runner.state.candidates[0];
16589        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16590        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16591    }
16592
16593    #[tokio::test]
16594    #[cfg(unix)]
16595    async fn parked_implementer_persists_completed_work() {
16596        for registered in [false, true] {
16597            let tmp = tempfile::tempdir().unwrap();
16598            let mut runner = registered_runner(tmp.path()).await;
16599            if !registered {
16600                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16601            }
16602            let marker = tmp.path().join("started");
16603            let release = tmp.path().join("release");
16604            let mut implementer = spec("implement");
16605            implementer.command = vec![
16606                "sh".into(),
16607                "-c".into(),
16608                format!(
16609                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16610                    marker.display(),
16611                    release.display()
16612                ),
16613            ];
16614            runner.roles.implementers = vec![implementer.clone()];
16615            runner.state.config.agents = vec![implementer];
16616            let pause = runner.pause.clone();
16617            let (result, ()) = tokio::join!(runner.implement(), async {
16618                tokio::time::timeout(Duration::from_secs(10), async {
16619                    while !marker.exists() {
16620                        tokio::time::sleep(Duration::from_millis(10)).await;
16621                    }
16622                })
16623                .await
16624                .unwrap();
16625                pause.park();
16626                std::fs::write(&release, "go").unwrap();
16627            });
16628            result.unwrap();
16629            let candidate = &runner.state.candidates[0];
16630            assert!(candidate.commits > 0, "{candidate:?}");
16631            assert!(candidate.summary.contains("saved-result"));
16632            assert_eq!(candidate.files, 1);
16633            let before = candidate.commits;
16634            runner.implement().await.unwrap();
16635            assert_eq!(runner.state.candidates[0].commits, before);
16636        }
16637    }
16638
16639    #[tokio::test]
16640    #[cfg(unix)]
16641    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16642        let tmp = tempfile::tempdir().unwrap();
16643        let mut runner = registered_runner(tmp.path()).await;
16644        let winner = runner.state.candidates[0].clone();
16645        let cache = tmp.path().join("cache");
16646        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16647        runner.state.config.graph.timeout_resource_wait = 0;
16648        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16649        let crate::cache::AcquireOutcome::Acquired(held) =
16650            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16651        else {
16652            panic!("cache must be free")
16653        };
16654        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16655            from_run: "earlier".into(),
16656            generation: 1,
16657            mode: crate::recovery::Mode::VerifyRepair,
16658            reasons: Vec::new(),
16659            reviewed_head: None,
16660            rounds: Vec::new(),
16661            open_findings: Vec::new(),
16662            evidence: None,
16663            criteria_inherited: true,
16664            repair: crate::recovery::Repair::NotStarted,
16665        });
16666        runner.recovery_repair(&winner).await.unwrap();
16667        assert!(matches!(
16668            runner.state.recovery.as_ref().unwrap().repair,
16669            crate::recovery::Repair::WaitingForRestore { .. }
16670        ));
16671        drop(held);
16672        runner.state.resource_block = None;
16673        runner.state.config.graph.timeout_resource_wait = 1;
16674        runner.recovery_repair(&winner).await.unwrap();
16675        assert!(matches!(
16676            runner.state.recovery.as_ref().unwrap().repair,
16677            crate::recovery::Repair::Done { .. }
16678        ));
16679        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16680    }
16681
16682    #[tokio::test]
16683    #[cfg(unix)]
16684    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16685        use std::os::fd::AsRawFd as _;
16686        for graft in [false, true] {
16687            let tmp = tempfile::tempdir().unwrap();
16688            let mut runner = registered_runner(tmp.path()).await;
16689            runner.state.config.graph.timeout_resource_wait = 1;
16690            let winner = runner.state.candidates[0].clone();
16691            let marker = tmp.path().join("fixer-started");
16692            let mut fixer = spec("fixer");
16693            fixer.command = vec![
16694                "sh".into(),
16695                "-c".into(),
16696                format!("echo started >> '{}'; echo done", marker.display()),
16697            ];
16698            runner.roles.fixer = Some(vec![fixer]);
16699            if graft {
16700                let mut loser = winner.clone();
16701                loser.label = 'B';
16702                loser.index = 1;
16703                runner.state.candidates.push(loser);
16704                runner.state.config.graph.graft_runner_up = true;
16705                runner.state.tally = Some(Tally {
16706                    first_choice: BTreeMap::new(),
16707                    borda: BTreeMap::new(),
16708                    winner: winner.label,
16709                    rankings: 1,
16710                    unanimous_initial: true,
16711                    deliberated: false,
16712                    changed_votes: 0,
16713                    unanimous_final: true,
16714                    tie_break: None,
16715                    judges: 1,
16716                    present: 1,
16717                    quorum: 1,
16718                    met_quorum: true,
16719                    uncontested: None,
16720                });
16721                runner.state.judgements.push(crate::run::Judgement {
16722                    judge: 1,
16723                    seat: "judge-1".into(),
16724                    agent: "judge".into(),
16725                    ranking: vec![winner.label, 'B'],
16726                    reasons: BTreeMap::new(),
16727                    confidence: None,
16728                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16729                    order: vec![0, 1],
16730                    failed: None,
16731                    duration_ms: 0,
16732                });
16733            } else {
16734                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16735                    from_run: "earlier".into(),
16736                    generation: 1,
16737                    mode: crate::recovery::Mode::VerifyRepair,
16738                    reasons: Vec::new(),
16739                    reviewed_head: None,
16740                    rounds: Vec::new(),
16741                    open_findings: Vec::new(),
16742                    evidence: None,
16743                    criteria_inherited: true,
16744                    repair: crate::recovery::Repair::NotStarted,
16745                });
16746            }
16747            let reader = crate::repo_lock::SeatLease::for_checkout(
16748                &winner.worktree,
16749                false,
16750                crate::config::test_coordination().as_ref(),
16751            )
16752            .await
16753            .unwrap();
16754            let pause = runner.pause.clone();
16755            let (result, ()) = tokio::join!(
16756                async {
16757                    if graft {
16758                        runner.graft().await
16759                    } else {
16760                        runner.recovery_repair(&winner).await
16761                    }
16762                },
16763                async {
16764                    tokio::time::sleep(Duration::from_millis(100)).await;
16765                    pause.park();
16766                }
16767            );
16768            result.unwrap();
16769            assert!(!marker.exists(), "a blocked seat must not spawn");
16770            // Exercise the persisted state, as a binary replacement/resume does.
16771            runner.state = RunState::load(&runner.state.id).unwrap();
16772            if graft {
16773                assert_eq!(
16774                    runner.state.graft.as_ref().unwrap().outcome,
16775                    GraftOutcome::WaitingForRestore
16776                );
16777            } else {
16778                assert!(matches!(
16779                    runner.state.recovery.as_ref().unwrap().repair,
16780                    crate::recovery::Repair::WaitingForRestore { .. }
16781                ));
16782            }
16783            drop(reader);
16784            runner.pause = Pause::new();
16785            runner.state.resource_block = None;
16786            // Deferred restoration must still respect an external lock owner.
16787            let external =
16788                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16789            assert_eq!(
16790                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16791                0
16792            );
16793            let leftover = winner.worktree.join("leftover");
16794            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16795            let result = if graft {
16796                runner.graft().await
16797            } else {
16798                runner.recovery_repair(&winner).await
16799            };
16800            assert!(
16801                result
16802                    .unwrap_err()
16803                    .is::<crate::repo_lock::ResourceBlocked>()
16804            );
16805            assert!(leftover.exists());
16806            assert!(!marker.exists());
16807            drop(external);
16808            runner.state.resource_block = None;
16809            let result = if graft {
16810                runner.graft().await
16811            } else {
16812                runner.recovery_repair(&winner).await
16813            };
16814            result.unwrap();
16815            assert!(!leftover.exists(), "restore must precede retry");
16816            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16817            if graft {
16818                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16819            } else {
16820                assert!(matches!(
16821                    runner.state.recovery.as_ref().unwrap().repair,
16822                    crate::recovery::Repair::Done { .. }
16823                ));
16824            }
16825        }
16826    }
16827
16828    #[tokio::test]
16829    #[cfg(unix)]
16830    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16831        use std::os::fd::AsRawFd as _;
16832        let tmp = tempfile::tempdir().unwrap();
16833        let mut runner = registered_runner(tmp.path()).await;
16834        runner.state.config.graph.timeout_resource_wait = 1;
16835        let winner = runner.state.candidates[0].clone();
16836        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16837        runner.state.tally = Some(Tally {
16838            first_choice: BTreeMap::new(),
16839            borda: BTreeMap::new(),
16840            winner: winner.label,
16841            rankings: 0,
16842            unanimous_initial: false,
16843            deliberated: false,
16844            changed_votes: 0,
16845            unanimous_final: false,
16846            tie_break: None,
16847            judges: 0,
16848            present: 0,
16849            quorum: 0,
16850            met_quorum: true,
16851            uncontested: Some("fixture".into()),
16852        });
16853        runner.state.graft = Some(GraftRecord {
16854            pre: pre.clone(),
16855            post: None,
16856            lines: None,
16857            limit: None,
16858            agent: None,
16859            outcome: GraftOutcome::Running,
16860            requested: Vec::new(),
16861            adoption: None,
16862            adoption_error: None,
16863        });
16864        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16865        git::commit_all(&winner.worktree, "unfinished graft")
16866            .await
16867            .unwrap();
16868        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16869        let leftover = winner.worktree.join("leftover");
16870        std::fs::write(&leftover, "untrusted edits").unwrap();
16871        let path = runner.state.repo.join(".git/updater.lock");
16872        let external = std::fs::File::create(&path).unwrap();
16873        assert_eq!(
16874            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16875            0
16876        );
16877        assert!(
16878            runner
16879                .graft()
16880                .await
16881                .unwrap_err()
16882                .is::<crate::repo_lock::ResourceBlocked>()
16883        );
16884        assert!(matches!(
16885            runner.state.graft.as_ref().unwrap().outcome,
16886            GraftOutcome::Running
16887        ));
16888        assert_eq!(
16889            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16890            unfinished
16891        );
16892        assert!(leftover.exists());
16893        drop(external);
16894        std::fs::remove_file(&path).unwrap();
16895        std::fs::create_dir(&path).unwrap();
16896        assert!(runner.graft().await.is_err());
16897        assert!(matches!(
16898            runner.state.graft.as_ref().unwrap().outcome,
16899            GraftOutcome::Running
16900        ));
16901        assert_eq!(
16902            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16903            unfinished
16904        );
16905        assert!(leftover.exists());
16906        std::fs::remove_dir(&path).unwrap();
16907        runner.graft().await.unwrap();
16908        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16909        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16910        assert!(!leftover.exists());
16911    }
16912
16913    #[tokio::test]
16914    #[cfg(unix)]
16915    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16916        use std::os::fd::AsRawFd as _;
16917        let tmp = tempfile::tempdir().unwrap();
16918        let mut runner = registered_runner(tmp.path()).await;
16919        runner.state.prep_complete = Some(false);
16920        runner.state.config.graph.timeout_resource_wait = 1;
16921        runner.state.save().unwrap();
16922        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16923        assert_eq!(
16924            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16925            0
16926        );
16927        runner.execute().await.unwrap();
16928        let disk = RunState::load(&runner.state.id).unwrap();
16929        assert!(disk.driver_exited);
16930        assert_eq!(disk.driver_pid, None);
16931        assert_eq!(runner.state.status, RunStatus::Blocked);
16932        assert_eq!(
16933            runner.state.resource_block.as_ref().unwrap().kind,
16934            "repository coordination"
16935        );
16936        assert!(runner.state.prep_failure.is_none());
16937        assert!(runner.state.seats.is_empty());
16938        runner.pause.park();
16939        // Include headroom for Git subprocesses under parallel test load;
16940        // the repository contention deadline itself remains one second.
16941        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16942            .await
16943            .unwrap()
16944            .unwrap();
16945        assert!(runner.state.parked);
16946        assert!(runner.state.prep_failure.is_none());
16947        let disk = RunState::load(&runner.state.id).unwrap();
16948        assert!(disk.driver_exited);
16949        assert_eq!(disk.driver_pid, None);
16950    }
16951
16952    #[tokio::test]
16953    #[cfg(unix)]
16954    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16955        use std::os::fd::AsRawFd as _;
16956        let tmp = tempfile::tempdir().unwrap();
16957        let mut runner = registered_runner(tmp.path()).await;
16958        runner.state.prep_complete = Some(false);
16959        runner.state.config.graph.timeout_resource_wait = 30;
16960        runner.state.save().unwrap();
16961        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16962        assert_eq!(
16963            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16964            0
16965        );
16966        assert!(
16967            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16968                .await
16969                .is_err()
16970        );
16971        let disk = RunState::load(&runner.state.id).unwrap();
16972        assert!(disk.driver_exited);
16973        assert_eq!(disk.driver_pid, None);
16974        assert!(disk.status.resumable());
16975        assert!(runner.state.driver_exited);
16976        assert_eq!(runner.state.driver_pid, None);
16977        runner.state.save().unwrap();
16978        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16979    }
16980
16981    #[tokio::test]
16982    #[cfg(unix)]
16983    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16984        let tmp = tempfile::tempdir().unwrap();
16985        let mut runner = registered_runner(tmp.path()).await;
16986        let winner = runner.state.candidates[0].clone();
16987        let cache = tmp.path().join("cache");
16988        let started = tmp.path().join("pre-gate-started");
16989        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16990        runner.state.config.verify.gate =
16991            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16992        let home = crate::run::home();
16993        let owner =
16994            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16995        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16996            crate::cache::AcquireOutcome::Acquired(g) => g,
16997            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16998        };
16999        let mut gate = Box::pin(runner.run_gate(&winner));
17000        assert!(
17001            tokio::time::timeout(Duration::from_millis(150), &mut gate)
17002                .await
17003                .is_err()
17004        );
17005        assert!(!started.exists(), "pre-gate must wait for the cache too");
17006        // Simulate the wave that already owns the cache entering invoke.
17007        // It must obtain the editor reservation and finish without waiting
17008        // for the gate that is queued behind its cache.
17009        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
17010        let editor = crate::repo_lock::SeatLease::checkout_with(
17011            &winner.worktree,
17012            true,
17013            crate::config::test_coordination().as_ref(),
17014            &wait,
17015        )
17016        .await
17017        .unwrap();
17018        drop(editor);
17019        guard.release();
17020        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17021            .await
17022            .unwrap()
17023            .unwrap();
17024        drop(gate);
17025        assert!(outcomes.iter().all(CommandOutcome::ok));
17026        assert!(started.exists());
17027    }
17028
17029    #[tokio::test]
17030    #[cfg(unix)]
17031    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
17032        use std::os::fd::AsRawFd as _;
17033
17034        ask_test_home();
17035        let tmp = tempfile::tempdir().unwrap();
17036        let repo = tmp.path().join("repo");
17037        std::fs::create_dir_all(&repo).unwrap();
17038        init_repo(&repo);
17039        let common = repo.join(".git");
17040        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17041        let mut runner = runner_at(RunStatus::Prep);
17042        runner.state.repo = repo.clone();
17043        runner.state.config.coordination = crate::config::test_coordination();
17044        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17045        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17046        runner.state.config.graph.advise = false;
17047        runner.roles.implementers = vec![spec("implement")];
17048        runner.roles.judges = vec![spec("judge")];
17049        runner.prep().await.unwrap();
17050        let winner = runner.state.candidates[0].clone();
17051        // Emulate edits already left by a completed seat. The fixture CLI
17052        // only reports completion; it performs no repository operations.
17053        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
17054        let completed = tmp.path().join("seat-completed");
17055        runner.roles.implementers[0].command = vec![
17056            "sh".into(),
17057            "-c".into(),
17058            format!("touch '{}'; echo completed", completed.display()),
17059        ];
17060        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
17061        assert_eq!(
17062            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17063            0
17064        );
17065        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17066        let mut implement = Box::pin(runner.implement());
17067        tokio::select! {
17068            result = &mut implement => panic!("rescue must wait: {result:?}"),
17069            result = tokio::time::timeout(Duration::from_secs(10), async {
17070                while !completed.exists() {
17071                    tokio::time::sleep(Duration::from_millis(20)).await;
17072                }
17073            }) => result.unwrap(),
17074        }
17075        assert!(
17076            tokio::time::timeout(Duration::from_millis(200), &mut implement)
17077                .await
17078                .is_err()
17079        );
17080        assert_eq!(
17081            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17082            before
17083        );
17084        assert_eq!(
17085            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17086            0
17087        );
17088        tokio::time::timeout(Duration::from_secs(10), &mut implement)
17089            .await
17090            .unwrap()
17091            .unwrap();
17092        drop(implement);
17093        assert_ne!(
17094            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17095            before
17096        );
17097        assert!(git::is_clean(&winner.worktree).await.unwrap());
17098
17099        let started = tmp.path().join("pre-gate-started");
17100        let proceed = tmp.path().join("pre-gate-proceed");
17101        let checked = tmp.path().join("gate-ran");
17102        runner.state.config.verify.pre_gate = vec![format!(
17103            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17104            started.display(),
17105            proceed.display()
17106        )];
17107        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
17108        assert_eq!(
17109            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17110            0
17111        );
17112        let mut gate = Box::pin(runner.run_gate(&winner));
17113        assert!(
17114            tokio::time::timeout(Duration::from_millis(200), &mut gate)
17115                .await
17116                .is_err()
17117        );
17118        assert!(!started.exists());
17119        assert!(!checked.exists());
17120        assert!(git::is_clean(&winner.worktree).await.unwrap());
17121        assert_eq!(
17122            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17123            0
17124        );
17125        tokio::select! {
17126            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
17127            result = tokio::time::timeout(Duration::from_secs(10), async {
17128                while !started.exists() {
17129                    tokio::time::sleep(Duration::from_millis(20)).await;
17130                }
17131            }) => result.unwrap(),
17132        }
17133        assert_eq!(
17134            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17135            -1,
17136            "mechanical edits must hold the real lock"
17137        );
17138        std::fs::write(proceed, "ready").unwrap();
17139        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17140            .await
17141            .unwrap()
17142            .unwrap();
17143        drop(gate);
17144        assert!(outcomes.iter().all(CommandOutcome::ok));
17145        assert!(checked.exists());
17146        assert!(runner.state.pre_gate_commit.is_some());
17147        assert!(git::is_clean(&winner.worktree).await.unwrap());
17148        assert_eq!(
17149            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17150            0,
17151            "gate completion must release coordination"
17152        );
17153        drop(outsider);
17154        std::fs::remove_file(common.join("updater.lock")).unwrap();
17155        std::fs::create_dir(common.join("updater.lock")).unwrap();
17156        std::fs::remove_file(&started).unwrap();
17157        std::fs::remove_file(&checked).unwrap();
17158        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17159        let error = runner.run_gate(&winner).await.unwrap_err();
17160        assert!(
17161            error
17162                .to_string()
17163                .contains("acquire mandatory repository lock")
17164        );
17165        assert!(
17166            !started.exists(),
17167            "failed acquisition must prevent pre-gate"
17168        );
17169        assert!(!checked.exists(), "failed acquisition must prevent gate");
17170        assert!(git::is_clean(&winner.worktree).await.unwrap());
17171        assert_eq!(
17172            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17173            head
17174        );
17175    }
17176
17177    #[tokio::test]
17178    #[cfg(unix)]
17179    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
17180        use std::os::fd::AsRawFd as _;
17181        use std::time::Duration;
17182
17183        ask_test_home();
17184        let tmp = tempfile::tempdir().unwrap();
17185        let repo = tmp.path().join("repo");
17186        std::fs::create_dir_all(&repo).unwrap();
17187        init_repo(&repo);
17188        let common = repo.join(".git");
17189        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17190        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
17191        assert_eq!(
17192            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17193            0
17194        );
17195        let mut runner = runner_at(RunStatus::Prep);
17196        runner.state.repo = repo.clone();
17197        runner.state.config.coordination = crate::config::test_coordination();
17198        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17199        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17200        runner.state.config.graph.advise = true;
17201        runner.state.config.graph.advisors = 1;
17202        runner.roles.implementers = vec![spec("implement")];
17203        runner.roles.judges = vec![spec("judge")];
17204        let root = runner.state.worktree_root();
17205        let started = tmp.path().join("setup-started");
17206        let proceed = tmp.path().join("setup-proceed");
17207        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17208            run: Some(format!(
17209                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17210                started.display(),
17211                proceed.display()
17212            )),
17213            ..Default::default()
17214        }];
17215        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
17216        let config = git::git(&repo, &["config", "--local", "--list"])
17217            .await
17218            .unwrap();
17219        let mut prep = Box::pin(runner.prep());
17220        assert!(
17221            tokio::time::timeout(Duration::from_millis(200), &mut prep)
17222                .await
17223                .is_err()
17224        );
17225        assert!(
17226            !root.exists(),
17227            "contention must prevent even checkout creation"
17228        );
17229        assert!(!started.exists(), "contention must prevent setup");
17230        assert_eq!(
17231            git::git(&repo, &["branch", "--list"]).await.unwrap(),
17232            branches
17233        );
17234        assert_eq!(
17235            git::git(&repo, &["config", "--local", "--list"])
17236                .await
17237                .unwrap(),
17238            config
17239        );
17240        drop(lock);
17241        tokio::select! {
17242            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
17243            result = tokio::time::timeout(Duration::from_secs(10), async {
17244                while !started.exists() {
17245                    tokio::time::sleep(Duration::from_millis(20)).await;
17246                }
17247            }) => result.unwrap(),
17248        }
17249        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17250        assert_eq!(
17251            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17252            -1
17253        );
17254        assert!(
17255            tokio::time::timeout(
17256                Duration::from_millis(100),
17257                crate::repo_lock::SeatLease::for_checkout(
17258                    &repo,
17259                    true,
17260                    crate::config::test_coordination().as_ref()
17261                )
17262            )
17263            .await
17264            .is_err(),
17265            "preparation must also exclude local editors"
17266        );
17267        std::fs::write(proceed, "ready").unwrap();
17268        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17269            .await
17270            .unwrap()
17271            .unwrap();
17272        drop(prep);
17273        assert_eq!(runner.state.prep_complete, Some(true));
17274        assert!(root.join("judge-1").exists());
17275        assert!(root.join("advisor-1").exists());
17276        assert_eq!(
17277            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17278            0
17279        );
17280    }
17281
17282    #[tokio::test]
17283    #[cfg(unix)]
17284    async fn preparation_lock_failure_prevents_repository_changes() {
17285        ask_test_home();
17286        let tmp = tempfile::tempdir().unwrap();
17287        let repo = tmp.path().join("repo");
17288        std::fs::create_dir_all(&repo).unwrap();
17289        init_repo(&repo);
17290        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17291        // A directory at the required lock path makes opening the real lock
17292        // fail, rather than merely exercising an invalid registration.
17293        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17294        let mut runner = runner_at(RunStatus::Prep);
17295        runner.state.repo = repo.clone();
17296        runner.state.config.coordination = crate::config::test_coordination();
17297        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17298        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17299        runner.roles.implementers = vec![spec("implement")];
17300        let error = runner.prep().await.unwrap_err();
17301        assert!(
17302            error
17303                .to_string()
17304                .contains("acquire mandatory repository lock")
17305        );
17306        assert!(!runner.state.worktree_root().exists());
17307        assert!(runner.state.candidates.is_empty());
17308        assert!(!repo.join(".git/config.worktree").exists());
17309        assert_eq!(
17310            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17311            "* main"
17312        );
17313    }
17314
17315    #[tokio::test]
17316    async fn preparation_records_creation_intent_before_git_can_fail() {
17317        ask_test_home();
17318        let tmp = tempfile::tempdir().unwrap();
17319        let repo = tmp.path().join("repo");
17320        std::fs::create_dir_all(&repo).unwrap();
17321        init_repo(&repo);
17322        let mut runner = runner_at(RunStatus::Prep);
17323        runner.state.repo = repo.clone();
17324        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17325        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17326        runner.state.config.blind.commit_msg_hook = false;
17327        runner.roles.implementers = vec![spec("one")];
17328        let label = blind::assign_labels(1, runner.state.seed)[0];
17329        let branch = runner.state.branch_for(label);
17330        // A conflicting branch makes Git refuse creation before a candidate
17331        // can be registered. The durable intent must still identify it.
17332        git::git(&repo, &["branch", &branch]).await.unwrap();
17333        assert!(runner.prep().await.is_err());
17334        let saved = RunState::load(&runner.state.id).unwrap();
17335        assert!(saved.candidates.is_empty());
17336        let event = saved
17337            .events
17338            .iter()
17339            .find(|e| e.node == "prep-intent")
17340            .unwrap();
17341        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17342        assert_eq!(intent["branch"], branch);
17343        assert_eq!(intent["start"], runner.state.base_commit);
17344        assert_eq!(
17345            intent["worktree"],
17346            runner
17347                .state
17348                .worktree_root()
17349                .join(format!("cand-{label}"))
17350                .to_string_lossy()
17351                .as_ref()
17352        );
17353        assert_eq!(intent["picks"], serde_json::json!([]));
17354    }
17355
17356    #[tokio::test]
17357    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17358        ask_test_home();
17359        let tmp = tempfile::tempdir().unwrap();
17360        let repo = tmp.path().join("repo");
17361        std::fs::create_dir_all(&repo).unwrap();
17362        init_repo(&repo);
17363        let mut runner = runner_at(RunStatus::Prep);
17364        runner.state.repo = repo.clone();
17365        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17366        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17367        runner.state.sources.pick_commits.push(refs::Input {
17368            token: "missing".into(),
17369            sha: "0".repeat(40),
17370            provenance: refs::Provenance::ExplicitCli,
17371        });
17372        assert!(runner.prep().await.is_err());
17373        assert!(runner.state.candidates.is_empty());
17374        assert!(!runner.state.worktree_root().exists());
17375    }
17376
17377    #[tokio::test]
17378    async fn prose_and_legacy_inference_never_import_into_candidates() {
17379        ask_test_home();
17380        let tmp = tempfile::tempdir().unwrap();
17381        let repo = tmp.path().join("repo");
17382        std::fs::create_dir_all(&repo).unwrap();
17383        init_repo(&repo);
17384        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17385        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17386            .await
17387            .unwrap();
17388        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17389        git::git(&repo, &["add", "."]).await.unwrap();
17390        git::git(&repo, &["commit", "-m", "historical implementation"])
17391            .await
17392            .unwrap();
17393        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17394        git::git(&repo, &["checkout", "main"]).await.unwrap();
17395        for instruction in [
17396            format!("Example: magi/history/A at {source}"),
17397            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17398            format!("Never import magi/history/A or {source}"),
17399            format!("Conversation answer: I mentioned {source} only as background"),
17400        ] {
17401            let mut runner = runner_at(RunStatus::Prep);
17402            runner.state.repo = repo.clone();
17403            runner.state.base_commit = base.clone();
17404            runner.state.instruction = instruction.clone();
17405            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17406            runner.state.config.blind.commit_msg_hook = false;
17407            runner.state.seeds = vec![refs::Seed {
17408                token: "magi/history/A".into(),
17409                sha: source.clone(),
17410                kind: refs::SeedKind::Unmerged,
17411                branch: true,
17412                detail: String::new(),
17413            }];
17414            runner.roles.implementers = vec![spec("one")];
17415            assert_eq!(seeded_instruction(&runner.state), instruction);
17416            // Model an old record with inferred seeds but no structured input field.
17417            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17418            legacy.as_object_mut().unwrap().remove("sources");
17419            runner.state = serde_json::from_value(legacy).unwrap();
17420            assert_eq!(runner.state.sources, refs::Sources::default());
17421            runner.state.save().unwrap();
17422            runner.state = RunState::load(&runner.state.id).unwrap();
17423            runner.prep().await.unwrap();
17424            for candidate in &runner.state.candidates {
17425                assert_eq!(
17426                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17427                    base
17428                );
17429                assert!(!candidate.worktree.join("unwanted").exists());
17430            }
17431        }
17432    }
17433
17434    #[tokio::test]
17435    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17436        ask_test_home();
17437        let tmp = tempfile::tempdir().unwrap();
17438        let repo = tmp.path().join("repo");
17439        std::fs::create_dir_all(&repo).unwrap();
17440        init_repo(&repo);
17441        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17442        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17443        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17444        git::git(&repo, &["add", "."]).await.unwrap();
17445        git::git(&repo, &["commit", "-m", "required seed"])
17446            .await
17447            .unwrap();
17448        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17449        git::git(&repo, &["checkout", "main"]).await.unwrap();
17450        let mut runner = runner_at(RunStatus::Prep);
17451        runner.state.repo = repo.clone();
17452        runner.state.base_commit = base.clone();
17453        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17454        runner.state.config.graph.advise = false;
17455        runner.state.config.blind.commit_msg_hook = false;
17456        runner.state.sources =
17457            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17458                .await
17459                .unwrap();
17460        runner.roles.implementers = vec![spec("one"), spec("two")];
17461        runner.roles.judges = vec![spec("judge")];
17462        let label = blind::assign_labels(2, runner.state.seed)[0];
17463        let branch = runner.state.branch_for(label);
17464        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17465        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17466            .await
17467            .unwrap();
17468        runner.state.candidates.push(Candidate {
17469            index: 0,
17470            label,
17471            agent: "one".into(),
17472            branch,
17473            worktree,
17474            summary: String::new(),
17475            stat: String::new(),
17476            files: 0,
17477            commits: 0,
17478            empty: false,
17479            failed: None,
17480            verified_noop: None,
17481            duration_ms: 0,
17482            folded: false,
17483        });
17484        runner.state.save().unwrap();
17485        // Reload the checkpoint immediately before its first cherry-pick.
17486        runner.state = RunState::load(&runner.state.id).unwrap();
17487        assert_eq!(runner.state.prep_complete, Some(false));
17488        runner.prep().await.unwrap();
17489        assert_eq!(runner.state.prep_complete, Some(true));
17490        assert_eq!(runner.state.candidates.len(), 2);
17491        for candidate in &runner.state.candidates {
17492            assert_eq!(
17493                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17494                git::tree_of(&repo, &seed).await.unwrap()
17495            );
17496            assert_eq!(
17497                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17498                "required commit"
17499            );
17500        }
17501        assert!(runner.state.worktree_root().join("judge-1").exists());
17502        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17503        runner.prep().await.unwrap();
17504        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17505
17506        runner.state.prep_complete = Some(false);
17507        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17508            run: Some(format!(
17509                "test -f '{}'",
17510                tmp.path().join("dependency-ready").display()
17511            )),
17512            ..Default::default()
17513        }];
17514        assert!(runner.prep().await.is_err());
17515        assert!(runner.state.prep_failure.is_some());
17516        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17517        runner.state = RunState::load(&runner.state.id).unwrap();
17518        assert!(
17519            runner.prep().await.is_err(),
17520            "correcting the cause alone must not auto-retry"
17521        );
17522        let failed_at = runner.state.events.last().unwrap().at;
17523        assert!(
17524            runner.retry_preparation(failed_at).is_err(),
17525            "old approvals cannot unlock the hold"
17526        );
17527        let mut task = crate::queue::Task::new(
17528            "retry".into(),
17529            "retry setup".into(),
17530            repo.clone(),
17531            crate::queue::Source::Human,
17532        );
17533        task.start(runner.state.id.clone());
17534        task.hold_machine(Some("setup failed".into()));
17535        task.release_operator("cli", None);
17536        runner
17537            .retry_preparation(task.resumption.as_ref().unwrap().at)
17538            .unwrap();
17539        runner.prep().await.unwrap();
17540        assert!(runner.state.prep_failure.is_none());
17541        assert_eq!(runner.state.prep_complete, Some(true));
17542        assert_eq!(runner.state.candidates.len(), 2);
17543        assert!(runner.state.worktree_root().join("judge-1").exists());
17544        for candidate in &runner.state.candidates {
17545            assert_eq!(
17546                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17547                git::tree_of(&repo, &seed).await.unwrap()
17548            );
17549        }
17550    }
17551
17552    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17553        let mut heads = Vec::new();
17554        for candidate in candidates {
17555            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17556        }
17557        heads
17558    }
17559
17560    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17561        ask_test_home();
17562        let tmp = tempfile::tempdir().unwrap();
17563        let repo = tmp.path().join("repo");
17564        std::fs::create_dir(&repo).unwrap();
17565        init_repo(&repo);
17566        let mut runner = runner_at(RunStatus::Reviewing);
17567        runner.state.repo = repo.clone();
17568        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17569        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17570        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17571            let branch = format!("candidate-{label}");
17572            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17573            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17574                .await
17575                .unwrap();
17576            if label == 'B' {
17577                std::fs::write(worktree.join("change"), "winner").unwrap();
17578                git::rescue_commit(&worktree, "candidate change")
17579                    .await
17580                    .unwrap();
17581            }
17582            runner.state.candidates.push(Candidate {
17583                index,
17584                label,
17585                agent: "alpha".into(),
17586                branch,
17587                worktree,
17588                summary: "completed reply".into(),
17589                stat: String::new(),
17590                files: usize::from(label == 'B'),
17591                commits: usize::from(label == 'B'),
17592                empty: label == 'A',
17593                failed: None,
17594                verified_noop: None,
17595                duration_ms: 1,
17596                folded: false,
17597            });
17598        }
17599        runner.state.judge_skipped = true;
17600        runner.state.tally = Some(Tally {
17601            first_choice: BTreeMap::new(),
17602            borda: BTreeMap::new(),
17603            winner: 'B',
17604            rankings: 0,
17605            unanimous_initial: false,
17606            deliberated: false,
17607            changed_votes: 0,
17608            unanimous_final: false,
17609            tie_break: None,
17610            judges: 0,
17611            present: 0,
17612            quorum: 0,
17613            met_quorum: true,
17614            uncontested: Some("only B produced a change".into()),
17615        });
17616        runner.state.save().unwrap();
17617        (tmp, runner)
17618    }
17619
17620    #[tokio::test]
17621    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17622        let (_tmp, mut runner) = preservation_resume_fixture().await;
17623        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17624        runner.state.config.disk.cache_limit_bytes = 0;
17625        runner.state.config.graph.advise = true;
17626        runner.state.config.graph.advisors = 1;
17627        let advisor = runner.state.worktree_root().join("advisor-1");
17628        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17629            .await
17630            .unwrap();
17631        let home = crate::run::home();
17632        let loser =
17633            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17634        let winner =
17635            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17636        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17637        for target in [&loser, &winner, &advisor] {
17638            std::fs::write(target.join("build-output"), "compiled").unwrap();
17639        }
17640
17641        runner.fold_losers().await.unwrap();
17642
17643        assert!(!loser.join("build-output").exists());
17644        assert!(!advisor.join("build-output").exists());
17645        assert!(winner.join("build-output").is_file());
17646    }
17647
17648    #[tokio::test]
17649    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17650        let (_tmp, mut runner) = preservation_resume_fixture().await;
17651        runner.state.candidates[0].folded = true;
17652        runner.state.config.graph.advise = true;
17653        runner.state.config.graph.advisors = 2;
17654        let repo = runner.state.repo.clone();
17655        let root = runner.state.worktree_root();
17656        let discarded = root.join("advisor-1");
17657        git::worktree_add_detached(&repo, &discarded, "main")
17658            .await
17659            .unwrap();
17660        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17661        let protected = root.join("advisor-2");
17662        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17663            .await
17664            .unwrap();
17665        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17666        runner.state.save().unwrap();
17667
17668        assert!(runner.fold_losers().await.is_err());
17669        assert!(!discarded.exists());
17670        assert!(protected.join("keep").exists());
17671        let saved = RunState::load(&runner.state.id).unwrap();
17672        assert!(saved.events.iter().any(|event| {
17673            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17674        }));
17675    }
17676
17677    #[tokio::test]
17678    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17679        let (tmp, mut runner) = preservation_resume_fixture().await;
17680        let repo = runner.state.repo.clone();
17681        let root = runner.state.worktree_root();
17682        for name in ["advisor-3", "judge-1", "review-2"] {
17683            let path = root.join(name);
17684            git::worktree_add_detached(&repo, &path, "main")
17685                .await
17686                .unwrap();
17687            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17688            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17689            remove_read_seat_worktree(&mut runner.state, &path)
17690                .await
17691                .unwrap();
17692            assert!(!path.exists());
17693        }
17694        let outside = tmp.path().join("advisor-1");
17695        let unknown = root.join("unknown");
17696        let attached = root.join("advisor-4");
17697        git::worktree_add_detached(&repo, &outside, "main")
17698            .await
17699            .unwrap();
17700        git::worktree_add_detached(&repo, &unknown, "main")
17701            .await
17702            .unwrap();
17703        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17704            .await
17705            .unwrap();
17706        let foreign = tmp.path().join("foreign");
17707        std::fs::create_dir(&foreign).unwrap();
17708        init_repo(&foreign);
17709        let wrong_repo = root.join("judge-2");
17710        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17711            .await
17712            .unwrap();
17713        let candidate = runner.state.candidates[0].worktree.clone();
17714        for path in [outside, unknown, attached, wrong_repo, candidate] {
17715            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17716            assert!(
17717                remove_read_seat_worktree(&mut runner.state, &path)
17718                    .await
17719                    .is_err()
17720            );
17721            assert_eq!(
17722                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17723                "keep"
17724            );
17725        }
17726    }
17727
17728    #[tokio::test]
17729    #[cfg(unix)]
17730    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17731        for (solo, failed_checkpoint) in
17732            [(true, false), (false, false), (true, true), (false, true)]
17733        {
17734            let (_tmp, mut runner) = preservation_resume_fixture().await;
17735            if solo {
17736                runner.state.candidates.retain(|c| c.label == 'A');
17737            }
17738            runner.state.candidates[0].empty = false;
17739            runner.state.candidates[0].summary.clear();
17740            runner.state.tally = None;
17741            runner.state.judge_skipped = false;
17742            runner.state.status = RunStatus::Implementing;
17743            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17744            let mut implementer = spec("alpha");
17745            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17746            runner.roles.implementers = vec![implementer];
17747            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17748            if failed_checkpoint {
17749                std::fs::create_dir_all(&patch).unwrap();
17750            }
17751            runner.state.save().unwrap();
17752            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17753            drop(pressure);
17754            runner.state = RunState::load(&runner.state.id).unwrap();
17755            assert_eq!(runner.state.status, RunStatus::Blocked);
17756            assert!(runner.state.interrupted_implementations.contains(&'A'));
17757            assert_eq!(runner.state.candidates[0].commits, 0);
17758            assert!(!runner.state.candidates[0].empty);
17759            assert!(runner.state.candidates[0].failed.is_none());
17760            if failed_checkpoint {
17761                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17762                std::fs::remove_dir(patch).unwrap();
17763            }
17764            runner.state.resource_block = None;
17765            runner.state.config.disk.min_free_bytes = 0;
17766            runner.roles.implementers[0].command = vec![
17767                "sh".into(),
17768                "-c".into(),
17769                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17770            ];
17771            runner.implement().await.unwrap();
17772            assert!(runner.state.interrupted_implementations.is_empty());
17773            assert!(runner.state.candidate_preservation.is_empty());
17774            assert_eq!(runner.state.candidates[0].commits, 1);
17775            assert!(!runner.state.candidates[0].empty);
17776            assert!(
17777                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17778                    .unwrap()
17779                    .contains("retried empty interrupted seat")
17780            );
17781            if !solo {
17782                assert_eq!(runner.state.candidates[1].commits, 1);
17783            }
17784        }
17785    }
17786
17787    #[tokio::test]
17788    #[cfg(unix)]
17789    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17790        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17791            let (_tmp, mut runner) = preservation_resume_fixture().await;
17792            runner.state.candidates.retain(|c| c.label == 'A');
17793            runner.state.candidates[0].empty = false;
17794            runner.state.candidates[0].summary.clear();
17795            runner.state.tally = None;
17796            runner.state.judge_skipped = false;
17797            runner.state.status = RunStatus::Implementing;
17798            // Force only the real post-spawn watchdog, without failing the
17799            // separate admission check. Existing edits predate its measurement.
17800            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17801            let wt = runner.state.candidates[0].worktree.clone();
17802            std::fs::write(
17803                wt.join("interrupted-source"),
17804                "retain implementation work\n",
17805            )
17806            .unwrap();
17807            if committed {
17808                git::rescue_commit(&wt, "implementation checkpoint")
17809                    .await
17810                    .unwrap();
17811            }
17812            let lock = git::git(
17813                &wt,
17814                &[
17815                    "rev-parse",
17816                    "--path-format=absolute",
17817                    "--git-path",
17818                    "index.lock",
17819                ],
17820            )
17821            .await
17822            .unwrap();
17823            if block_rescue {
17824                std::fs::write(&lock, "fixture-owned lock").unwrap();
17825            }
17826            let mut implementer = spec("alpha");
17827            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17828            runner.roles.implementers = vec![implementer];
17829            runner.state.save().unwrap();
17830            let result = runner.implement().await;
17831            drop(pressure);
17832            assert_eq!(result.is_err(), block_rescue);
17833            assert_eq!(
17834                runner.state.resource_block.as_ref().unwrap().kind,
17835                "disk pressure"
17836            );
17837            assert!(
17838                runner
17839                    .state
17840                    .events
17841                    .iter()
17842                    .any(|e| e.message.contains("agent execution interrupted"))
17843            );
17844            assert!(
17845                runner
17846                    .state
17847                    .dir()
17848                    .join("artifacts/candidate-A-recovery/staged.patch")
17849                    .exists()
17850            );
17851            if block_rescue {
17852                let saved = RunState::load(&runner.state.id).unwrap();
17853                assert!(saved.candidate_preservation.contains_key(&'A'));
17854                assert!(!saved.candidates[0].empty);
17855                assert_eq!(
17856                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17857                    "retain implementation work\n"
17858                );
17859                std::fs::remove_file(lock).unwrap();
17860                runner.state = saved;
17861            } else {
17862                assert_eq!(runner.state.status, RunStatus::Blocked);
17863                assert_eq!(runner.state.candidates[0].commits, 1);
17864            }
17865            // Recovery must save the candidate before deciding whether another
17866            // implementation is needed. No implementer is available on retry.
17867            runner.roles.implementers.clear();
17868            runner.state.config.disk.min_free_bytes = 0;
17869            runner.state.resource_block = None;
17870            runner.implement().await.unwrap();
17871            assert!(runner.state.candidate_preservation.is_empty());
17872            assert_eq!(runner.state.candidates[0].commits, 1);
17873            assert!(!runner.state.candidates[0].empty);
17874            assert!(git::is_clean(&wt).await.unwrap());
17875            assert!(
17876                crate::run::read_artifact(&runner.state, "cand-A.patch")
17877                    .unwrap()
17878                    .contains("retain implementation work")
17879            );
17880        }
17881    }
17882
17883    #[tokio::test]
17884    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17885        let (_tmp, mut runner) = preservation_resume_fixture().await;
17886        // Schema 15 already confirmed the unfolded no-change result.
17887        runner.implement().await.unwrap();
17888        assert!(runner.state.candidate_preservation.is_empty());
17889        assert!(
17890            !runner
17891                .state
17892                .dir()
17893                .join("artifacts/candidate-A-recovery")
17894                .exists()
17895        );
17896        runner.fold_losers().await.unwrap();
17897        assert!(!runner.state.candidates[0].worktree.exists());
17898        for schema in [14, crate::run::SCHEMA] {
17899            runner.state.schema = schema;
17900            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17901            runner.state.save().unwrap();
17902            runner.state = RunState::load(&runner.state.id).unwrap();
17903            runner.implement().await.unwrap();
17904            assert!(runner.state.candidate_preservation.is_empty());
17905            assert!(runner.state.candidates[0].folded);
17906            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17907        }
17908    }
17909
17910    #[tokio::test]
17911    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17912        let (_tmp, mut runner) = preservation_resume_fixture().await;
17913        runner.state.candidates.retain(|c| c.label == 'A');
17914        runner.state.tally = None;
17915        runner.state.judge_skipped = false;
17916        let candidate = &mut runner.state.candidates[0];
17917        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17918        candidate.failed = Some("deployment validation unavailable".into());
17919        std::fs::write(
17920            candidate.worktree.join("repair"),
17921            "future launcher policy\n",
17922        )
17923        .unwrap();
17924        runner
17925            .state
17926            .candidate_preservation
17927            .insert('A', "awaiting persistence".into());
17928        runner.persist_candidates().await.unwrap();
17929        let candidate = &runner.state.candidates[0];
17930        assert!(!candidate.empty);
17931        assert_eq!(candidate.commits, 1);
17932        assert_eq!(candidate.files, 1);
17933        assert!(candidate.failed.is_none());
17934        assert!(candidate.summary.contains("EPERM"));
17935        assert!(
17936            crate::run::read_artifact(&runner.state, "cand-A.patch")
17937                .unwrap()
17938                .contains("future launcher policy")
17939        );
17940        assert!(runner.state.candidate_preservation.is_empty());
17941    }
17942
17943    #[tokio::test]
17944    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17945        let (_tmp, mut runner) = preservation_resume_fixture().await;
17946        let wt = runner.state.candidates[0].worktree.clone();
17947        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17948        runner.state.schema = 14;
17949        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17950        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17951        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17952        for _ in 0..2 {
17953            assert!(runner.implement().await.is_err());
17954            assert_eq!(runner.state.status, RunStatus::Blocked);
17955            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17956            assert!(
17957                runner.state.candidates[0].empty,
17958                "old verdict must remain unusable"
17959            );
17960            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17961            assert!(runner.state.judge_skipped);
17962            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17963            assert!(
17964                crate::run::read_artifact(&runner.state, "cand-A.patch")
17965                    .unwrap()
17966                    .contains("owned edits")
17967            );
17968            assert!(wt.exists());
17969            assert_eq!(
17970                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17971                    .await
17972                    .unwrap(),
17973                1
17974            );
17975            runner.state = RunState::load(&runner.state.id).unwrap();
17976        }
17977    }
17978
17979    #[tokio::test]
17980    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17981        let (_tmp, mut runner) = preservation_resume_fixture().await;
17982        let wt = runner.state.candidates[0].worktree.clone();
17983        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17984        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17985        let index_lock = PathBuf::from(
17986            git::git(
17987                &wt,
17988                &[
17989                    "rev-parse",
17990                    "--path-format=absolute",
17991                    "--git-path",
17992                    "index.lock",
17993                ],
17994            )
17995            .await
17996            .unwrap(),
17997        );
17998        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17999        runner.state.schema = 14;
18000        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
18001        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18002        assert!(runner.implement().await.is_err());
18003        assert!(runner.after_implement().is_err());
18004        assert!(runner.fold_losers().await.is_err());
18005        assert_eq!(
18006            std::fs::read_to_string(wt.join("recovered")).unwrap(),
18007            "failed seat edits"
18008        );
18009        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18010        runner.state = RunState::load(&runner.state.id).unwrap();
18011        std::fs::remove_file(index_lock).unwrap();
18012        // Recovery finds changes that the old uncontested result never judged.
18013        assert!(runner.implement().await.is_err());
18014        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
18015        assert!(runner.state.candidates[0].empty);
18016        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
18017        assert!(
18018            crate::run::read_artifact(&runner.state, "cand-A.patch")
18019                .unwrap()
18020                .contains("failed seat edits")
18021        );
18022        assert!(wt.exists());
18023    }
18024
18025    #[tokio::test]
18026    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
18027        let (_tmp, mut runner) = preservation_resume_fixture().await;
18028        let repo = runner.state.repo.clone();
18029        let common = git::git(
18030            &repo,
18031            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
18032        )
18033        .await
18034        .unwrap();
18035        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
18036        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
18037        assert!(runner.fold_losers().await.is_err());
18038        assert!(!runner.state.candidates[0].worktree.exists());
18039        assert!(!runner.state.candidates[0].folded);
18040        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
18041        runner.state = RunState::load(&runner.state.id).unwrap();
18042        std::fs::remove_file(branch_lock).unwrap();
18043        let judge = runner.state.worktree_root().join("judge-1");
18044        git::worktree_add_detached(&repo, &judge, "main")
18045            .await
18046            .unwrap();
18047        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
18048        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
18049            .await
18050            .unwrap();
18051        runner.roles.judges = vec![spec("judge")];
18052        assert!(runner.fold_losers().await.is_err());
18053        runner.state = RunState::load(&runner.state.id).unwrap();
18054        assert!(
18055            runner.state.candidates[0].folded,
18056            "candidate progress saved before judge failure"
18057        );
18058        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
18059        assert!(judge.join("uncommitted").exists());
18060        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
18061            .await
18062            .unwrap();
18063        runner.fold_losers().await.unwrap();
18064        assert!(!judge.exists());
18065        runner.fold_losers().await.unwrap();
18066    }
18067
18068    #[tokio::test]
18069    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
18070        let (_tmp, mut runner) = preservation_resume_fixture().await;
18071        runner.state.candidates.retain(|c| c.label == 'B');
18072        runner.state.tally = None;
18073        runner.state.judge_skipped = false;
18074        runner.state.prep_complete = Some(true);
18075        runner.state.config.graph.advise = false;
18076        runner.state.config.graph.selected_implementer = Some("alpha".into());
18077        let wt = runner.state.candidates[0].worktree.clone();
18078        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
18079        runner
18080            .state
18081            .candidate_preservation
18082            .insert('B', "awaiting persistence".into());
18083        let index_lock = git::git(
18084            &wt,
18085            &[
18086                "rev-parse",
18087                "--path-format=absolute",
18088                "--git-path",
18089                "index.lock",
18090            ],
18091        )
18092        .await
18093        .unwrap();
18094        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18095        runner.state.save().unwrap();
18096        assert!(runner.execute_graph().await.is_err());
18097        assert_eq!(runner.state.status, RunStatus::Blocked);
18098        assert!(runner.state.candidate_preservation.contains_key(&'B'));
18099        std::fs::remove_file(index_lock).unwrap();
18100        // Park at the next graph boundary: this tests the real selected-seat
18101        // hold guard without dispatching reviewers or publishing anything.
18102        for _ in 0..2 {
18103            runner.state = RunState::load(&runner.state.id).unwrap();
18104            runner.pause.park();
18105            runner.execute_graph().await.unwrap();
18106            assert_eq!(runner.state.status, RunStatus::Implementing);
18107            assert!(runner.state.candidate_preservation.is_empty());
18108            assert_eq!(runner.state.candidates[0].commits, 2);
18109            assert!(runner.state.tally.is_none());
18110        }
18111        runner.implement().await.unwrap();
18112        assert_eq!(runner.state.status, RunStatus::Judging);
18113        // A genuine selected-implementer hold must still require release.
18114        runner.state.status = RunStatus::Blocked;
18115        runner.state.candidates[0].failed = Some("implementation failed".into());
18116        runner.state.save().unwrap();
18117        let error = runner.execute_graph().await.unwrap_err();
18118        assert!(
18119            error
18120                .to_string()
18121                .contains("selected implementation is held")
18122        );
18123    }
18124
18125    #[tokio::test]
18126    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
18127        let (_tmp, mut runner) = preservation_resume_fixture().await;
18128        let repo = runner.state.repo.clone();
18129        let candidate = runner.state.candidates[0].clone();
18130        // Remove only the disposable fixture directory, leaving Git's linked
18131        // worktree registration and branch intact, as in a vanished checkout.
18132        let registered = git::worktree_holding(&repo, &candidate.branch)
18133            .await
18134            .unwrap()
18135            .unwrap();
18136        assert_eq!(
18137            registered.canonicalize().unwrap(),
18138            candidate.worktree.canonicalize().unwrap()
18139        );
18140        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18141        assert_eq!(
18142            git::worktree_holding(&repo, &candidate.branch)
18143                .await
18144                .unwrap(),
18145            Some(registered)
18146        );
18147        assert!(
18148            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
18149            "the stale registration initially keeps the branch checked out"
18150        );
18151        runner.fold_losers().await.unwrap();
18152        assert!(runner.state.candidates[0].folded);
18153        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18154        assert_eq!(
18155            git::worktree_holding(&repo, &candidate.branch)
18156                .await
18157                .unwrap(),
18158            None
18159        );
18160        runner.state = RunState::load(&runner.state.id).unwrap();
18161        runner.fold_losers().await.unwrap();
18162    }
18163
18164    #[tokio::test]
18165    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
18166        let (_tmp, mut runner) = preservation_resume_fixture().await;
18167        let repo = runner.state.repo.clone();
18168        let candidate = runner.state.candidates[0].clone();
18169        let winner = runner.state.candidates[1].clone();
18170        let registered = git::worktree_holding(&repo, &candidate.branch)
18171            .await
18172            .unwrap()
18173            .unwrap();
18174        assert_eq!(
18175            registered.canonicalize().unwrap(),
18176            candidate.worktree.canonicalize().unwrap()
18177        );
18178        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18179        assert_eq!(
18180            git::worktree_holding(&repo, &candidate.branch)
18181                .await
18182                .unwrap(),
18183            Some(registered)
18184        );
18185        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
18186
18187        for _ in 0..2 {
18188            fold_run(&mut runner.state, false, &crate::run::home())
18189                .await
18190                .unwrap();
18191            runner.state = RunState::load(&runner.state.id).unwrap();
18192            assert!(runner.state.candidates[0].folded);
18193            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18194            assert_eq!(
18195                git::worktree_holding(&repo, &candidate.branch)
18196                    .await
18197                    .unwrap(),
18198                None
18199            );
18200            assert!(!runner.state.candidates[1].folded);
18201            assert!(winner.worktree.exists());
18202            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
18203        }
18204    }
18205
18206    /// The recovery-retention override, refused for the rule under test. The
18207    /// arrangement is saved in `home` before each call, so `record gone` or
18208    /// `unreadable` would be the fixture's mistake and fails here.
18209    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
18210        let error = fold_run_overriding_recovery_retention(state, true, home)
18211            .await
18212            .expect_err("the override is refused");
18213        assert!(
18214            !matches!(
18215                error.downcast_ref::<FoldRefusal>(),
18216                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
18217            ),
18218            "refused for the wrong reason: {error:#}"
18219        );
18220        error
18221    }
18222
18223    #[tokio::test]
18224    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
18225        for sidecar in [false, true] {
18226            let tmp = tempfile::tempdir().unwrap();
18227            let home = tmp.path().join("home");
18228            let repo = tmp.path().join("repo");
18229            std::fs::create_dir(&repo).unwrap();
18230            init_repo(&repo);
18231            let mut state = runner_at(RunStatus::Superseded).state;
18232            state.repo = repo.clone();
18233            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18234            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18235            state.driver_exited = true;
18236            state.reserve_under(&home).unwrap();
18237            git::git(
18238                &repo,
18239                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
18240            )
18241            .await
18242            .unwrap();
18243            let wt = state.worktree_root().join("cand-A");
18244            git::worktree_add_branch(&repo, &wt, "candidate", "main")
18245                .await
18246                .unwrap();
18247            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18248            git::commit_all(&wt, "fixture: independent source")
18249                .await
18250                .unwrap();
18251            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18252            state.candidates.push(Candidate {
18253                index: 0,
18254                label: 'A',
18255                agent: "fixture".into(),
18256                branch: "candidate".into(),
18257                worktree: wt.clone(),
18258                summary: String::new(),
18259                stat: String::new(),
18260                files: 0,
18261                commits: 0,
18262                empty: false,
18263                failed: None,
18264                verified_noop: None,
18265                duration_ms: 0,
18266                folded: false,
18267            });
18268            let mut task = crate::queue::Task::new(
18269                "task".into(),
18270                "task".into(),
18271                repo.clone(),
18272                crate::queue::Source::Human,
18273            );
18274            task.runs.push(state.id.clone());
18275            crate::queue::Queue::at(home.join("queue"))
18276                .put(&mut task)
18277                .unwrap();
18278            if sidecar {
18279                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18280            }
18281            state.save_under(&home).unwrap();
18282            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18283            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18284            assert!(
18285                matches!(
18286                    refusal.downcast_ref::<FoldRefusal>(),
18287                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18288                ),
18289                "{refusal:#}"
18290            );
18291            let mut disk = state.config.disk.clone();
18292            disk.fold_grace_secs = 0;
18293            assert_eq!(
18294                crate::clean::fold_due(
18295                    &home.join("runs"),
18296                    &home,
18297                    &state.worktree_root(),
18298                    &disk,
18299                    Timestamp::now() + std::time::Duration::from_secs(10),
18300                )
18301                .await
18302                .unwrap(),
18303                (0, 0)
18304            );
18305            assert!(wt.exists());
18306            state.status = RunStatus::Blocked;
18307            state.save_under(&home).unwrap();
18308            let error = override_refusal(&mut state, &home).await;
18309            assert!(
18310                error
18311                    .to_string()
18312                    .contains("requires a finished, non-resumable run"),
18313                "{error:#}"
18314            );
18315            state.status = RunStatus::Superseded;
18316            state.driver_exited = false;
18317            state.driver_claimed = None;
18318            state.save_under(&home).unwrap();
18319            let error = override_refusal(&mut state, &home).await;
18320            assert!(
18321                error
18322                    .to_string()
18323                    .contains("run is live or its ownership is unknown"),
18324                "{error:#}"
18325            );
18326            state.driver_pid = Some(std::process::id());
18327            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18328            state.save_under(&home).unwrap();
18329            let error = override_refusal(&mut state, &home).await;
18330            assert!(
18331                error
18332                    .to_string()
18333                    .contains("run is live or its ownership is unknown"),
18334                "{error:#}"
18335            );
18336            state.driver_exited = true;
18337            state.driver_pid = None;
18338            state.driver_started_at = None;
18339            state.save_under(&home).unwrap();
18340            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18341            let error = override_refusal(&mut state, &home).await;
18342            assert!(
18343                matches!(
18344                    error.downcast_ref::<FoldRefusal>(),
18345                    Some(FoldRefusal::Live(_))
18346                ),
18347                "{error:#}"
18348            );
18349            drop(lease);
18350            #[cfg(unix)]
18351            {
18352                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18353                let error = override_refusal(&mut state, &home).await;
18354                assert!(
18355                    matches!(
18356                        error.downcast_ref::<FoldRefusal>(),
18357                        Some(FoldRefusal::Live(_))
18358                    ),
18359                    "{error:#}"
18360                );
18361                drop(output);
18362            }
18363            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18364            let error = override_refusal(&mut state, &home).await;
18365            assert!(
18366                matches!(
18367                    error.downcast_ref::<FoldRefusal>(),
18368                    Some(FoldRefusal::Live(_))
18369                ),
18370                "{error:#}"
18371            );
18372            drop(owner);
18373            let checkpoint = git::git(
18374                &wt,
18375                &[
18376                    "rev-parse",
18377                    "--path-format=absolute",
18378                    "--git-path",
18379                    "CHERRY_PICK_HEAD",
18380                ],
18381            )
18382            .await
18383            .unwrap();
18384            std::fs::write(&checkpoint, &head).unwrap();
18385            let error = override_refusal(&mut state, &home).await;
18386            assert!(
18387                matches!(
18388                    error.downcast_ref::<FoldRefusal>(),
18389                    Some(FoldRefusal::ProofIncomplete(detail))
18390                        if detail.contains("Git recovery checkpoint retained")
18391                ),
18392                "{error:#}"
18393            );
18394            std::fs::remove_file(checkpoint).unwrap();
18395            std::fs::write(wt.join("dirty"), "keep").unwrap();
18396            let error = override_refusal(&mut state, &home).await;
18397            assert!(
18398                matches!(
18399                    error.downcast_ref::<FoldRefusal>(),
18400                    Some(FoldRefusal::ProofIncomplete(_))
18401                ),
18402                "{error:#}"
18403            );
18404            assert!(wt.join("dirty").exists());
18405            std::fs::remove_file(wt.join("dirty")).unwrap();
18406            let evidence = home
18407                .join("runs")
18408                .join(&state.id)
18409                .join("artifacts/fold-evidence");
18410            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18411            std::fs::write(&evidence, "blocked archive").unwrap();
18412            let error = override_refusal(&mut state, &home).await;
18413            assert!(
18414                matches!(
18415                    error.downcast_ref::<FoldRefusal>(),
18416                    Some(FoldRefusal::ProofIncomplete(_))
18417                ),
18418                "{error:#}"
18419            );
18420            assert!(wt.exists());
18421            assert!(
18422                !RunState::load_under(&state.id, &home)
18423                    .unwrap()
18424                    .events
18425                    .iter()
18426                    .any(|event| event.message.contains("--override-recovery-retention"))
18427            );
18428            std::fs::remove_file(&evidence).unwrap();
18429            fold_run_overriding_recovery_retention(&mut state, true, &home)
18430                .await
18431                .unwrap();
18432            assert!(!wt.exists());
18433            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18434            assert!(
18435                git::worktree_holding(&repo, "candidate")
18436                    .await
18437                    .unwrap()
18438                    .is_none()
18439            );
18440            assert!(
18441                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18442                    .unwrap()
18443                    .contains("retained implementation")
18444            );
18445            assert!(evidence.join(format!("{head}.index")).is_file());
18446            let saved = RunState::load_under(&state.id, &home).unwrap();
18447            assert_eq!(saved.status, RunStatus::Superseded);
18448            assert!(saved.candidates[0].folded);
18449            assert!(saved.events.iter().any(|event| {
18450                event.message.contains("--override-recovery-retention")
18451                    && event.message.contains(&state.id)
18452                    && event.message.contains(&reason)
18453            }));
18454            assert_eq!(
18455                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18456                sidecar
18457            );
18458        }
18459    }
18460
18461    #[tokio::test]
18462    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18463        ask_test_home();
18464        let tmp = tempfile::tempdir().unwrap();
18465        let repo = tmp.path().join("repo");
18466        std::fs::create_dir(&repo).unwrap();
18467        init_repo(&repo);
18468        let mut runner = runner_at(RunStatus::Implementing);
18469        runner.state.repo = repo.clone();
18470        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18471        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18472        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18473            let branch = format!("candidate-{label}");
18474            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18475            git::worktree_add_branch(&repo, &wt, &branch, "main")
18476                .await
18477                .unwrap();
18478            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18479            git::git(&wt, &["add", "README.md"]).await.unwrap();
18480            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18481            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18482            runner.state.candidates.push(Candidate {
18483                index,
18484                label,
18485                agent: "alpha".to_owned(),
18486                branch,
18487                worktree: wt,
18488                summary: "completed implementation".to_owned(),
18489                stat: String::new(),
18490                files: 0,
18491                commits: 0,
18492                empty: false,
18493                failed: None,
18494                verified_noop: None,
18495                duration_ms: 42,
18496                folded: false,
18497            });
18498            runner
18499                .state
18500                .candidate_preservation
18501                .insert(label, "awaiting persistence".to_owned());
18502        }
18503        let wt = runner.state.candidates[0].worktree.clone();
18504        let index_lock = git::git(
18505            &wt,
18506            &[
18507                "rev-parse",
18508                "--path-format=absolute",
18509                "--git-path",
18510                "index.lock",
18511            ],
18512        )
18513        .await
18514        .unwrap();
18515        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18516        runner.state.save().unwrap();
18517        assert!(runner.persist_candidates().await.is_err());
18518        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18519        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18520        assert_eq!(
18521            runner.state.candidates[1].commits, 1,
18522            "other results are still collected"
18523        );
18524        assert!(
18525            !runner.state.candidates[0].empty,
18526            "failed rescue is not no change"
18527        );
18528        assert_eq!(
18529            runner.state.candidates[0].summary,
18530            "completed implementation"
18531        );
18532        assert!(runner.after_implement().is_err());
18533        // The record the fold locks is the one on disk, so the arrangement is
18534        // saved first; the refusal asserted is the preservation rule's own,
18535        // never `record gone`.
18536        runner.state.save().unwrap();
18537        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18538            .await
18539            .unwrap_err();
18540        assert!(
18541            matches!(
18542                refusal.downcast_ref::<FoldRefusal>(),
18543                Some(FoldRefusal::ProofIncomplete(detail))
18544                    if detail.contains("candidate preservation incomplete")
18545            ),
18546            "{refusal:#}"
18547        );
18548        assert!(wt.join("new-file").exists());
18549        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18550        assert!(recovery.join("staged.patch").exists());
18551        assert!(recovery.join("unstaged.patch").exists());
18552        assert_eq!(
18553            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18554            "untracked edits\n"
18555        );
18556        runner.state.begin_pass();
18557        runner.state.end_pass_parked(ParkCause::Upgrade {
18558            from: "1.0".into(),
18559            to: Some("1.1".into()),
18560        });
18561        runner.state.save().unwrap();
18562        runner.state = RunState::load(&runner.state.id).unwrap();
18563        assert!(matches!(
18564            runner.state.passes.last().unwrap().end,
18565            Some(crate::run::PassEnd::Parked {
18566                cause: ParkCause::Upgrade { .. }
18567            })
18568        ));
18569        std::fs::remove_file(index_lock).unwrap();
18570        // No implementer is configured: a persistence retry cannot dispatch a seat.
18571        runner.implement().await.unwrap();
18572        assert!(runner.state.candidate_preservation.is_empty());
18573        assert!(
18574            runner
18575                .state
18576                .candidates
18577                .iter()
18578                .all(|c| c.commits == 1 && !c.empty)
18579        );
18580        assert!(git::is_clean(&wt).await.unwrap());
18581        assert!(
18582            crate::run::read_artifact(&runner.state, "cand-A.patch")
18583                .unwrap()
18584                .contains("later tracked edits")
18585        );
18586    }
18587
18588    #[tokio::test]
18589    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18590        ask_test_home();
18591        let tmp = tempfile::tempdir().unwrap();
18592        let repo = tmp.path().join("repo");
18593        std::fs::create_dir(&repo).unwrap();
18594        init_repo(&repo);
18595        let wt = tmp.path().join("candidate");
18596        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18597            .await
18598            .unwrap();
18599        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18600        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18601        assert!(wt.join("uncommitted").exists());
18602        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18603        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18604        let mut runner = runner_at(RunStatus::Implementing);
18605        runner.state.repo = repo.clone();
18606        runner.state.base_commit = "missing-base".to_owned();
18607        runner.state.candidates.push(Candidate {
18608            index: 0,
18609            label: 'A',
18610            agent: "alpha".into(),
18611            branch: "candidate".into(),
18612            worktree: wt.clone(),
18613            summary: "completed".into(),
18614            stat: String::new(),
18615            files: 0,
18616            commits: 0,
18617            empty: false,
18618            failed: None,
18619            verified_noop: None,
18620            duration_ms: 1,
18621            folded: false,
18622        });
18623        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18624        // Saved in the home the fold uses: without a record the fold would
18625        // refuse as `record gone` and say nothing about the dirty tree.
18626        let home = tmp.path().join("home");
18627        runner.state.save_under(&home).unwrap();
18628        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18629        assert!(
18630            refusal
18631                .to_string()
18632                .contains("worktree has uncommitted work; refusing removal"),
18633            "{refusal:#}"
18634        );
18635        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18636        assert!(!runner.state.candidates[0].folded);
18637        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18638        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18639        runner
18640            .state
18641            .candidate_preservation
18642            .insert('A', "pending".into());
18643        assert!(runner.persist_candidates().await.is_err());
18644        assert!(!runner.state.candidates[0].empty);
18645        assert!(!runner.state.candidates[0].folded);
18646        assert!(wt.exists());
18647        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18648        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18649        std::fs::create_dir_all(&patch_path).unwrap();
18650        assert!(
18651            runner.persist_candidates().await.is_err(),
18652            "artifact failure stays pending"
18653        );
18654        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18655        assert!(!runner.state.candidates[0].empty);
18656        std::fs::remove_dir(patch_path).unwrap();
18657        runner.persist_candidates().await.unwrap();
18658        assert!(
18659            runner.state.candidates[0].empty,
18660            "only successful inspection confirms no change"
18661        );
18662    }
18663
18664    fn init_repo(dir: &Path) {
18665        let run = |args: &[&str]| {
18666            let out = std::process::Command::new("git")
18667                .args(args)
18668                .current_dir(dir)
18669                .quiet()
18670                .output()
18671                .expect("spawn git");
18672            assert!(
18673                out.status.success(),
18674                "git {args:?} failed: {}",
18675                String::from_utf8_lossy(&out.stderr)
18676            );
18677        };
18678        run(&["init", "-b", "main"]);
18679        run(&["config", "user.name", "magi test"]);
18680        run(&["config", "user.email", "magi@example.com"]);
18681        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18682        run(&["add", "-A"]);
18683        run(&["commit", "-m", "init"]);
18684    }
18685
18686    // `settle_questions` is what closes the ghost the phone showed: a run's
18687    // seat asked something, the run then ended, and nothing was left to
18688    // abandon the question it left `open`. `HOME` is a process-wide
18689    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18690    // first time it runs in the binary — every test below still reaches the
18691    // same directory whichever call won, and each gets its own run id from
18692    // `RunState::new`, so they never collide there.
18693    fn ask_test_home() {
18694        crate::run::pin_test_home();
18695    }
18696
18697    #[test]
18698    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18699        ask_test_home();
18700        let mut runner = runner_at(RunStatus::Prep);
18701        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18702        // A blocked temporary output path makes the terminal save fail while
18703        // preserving the already published reservation.
18704        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18705        let error = guard
18706            .finish(
18707                &mut runner.state,
18708                Err(
18709                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18710                        .into(),
18711                ),
18712            )
18713            .unwrap_err();
18714        assert_eq!(
18715            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18716            std::io::ErrorKind::PermissionDenied
18717        );
18718        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18719        let message = format!("{error:#}");
18720        assert!(message.contains("original refusal"));
18721        assert!(!message.contains("could not save terminal"));
18722        assert_eq!(
18723            error.chain().count(),
18724            2,
18725            "only startup attribution wraps the original error"
18726        );
18727        let saved = RunState::load(&runner.state.id).unwrap();
18728        assert_eq!(saved.status, RunStatus::Blocked);
18729        assert!(!saved.startup.unwrap().complete);
18730    }
18731
18732    #[test]
18733    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18734        ask_test_home();
18735        let mut runner = runner_at(RunStatus::Prep);
18736        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18737        let id = runner.state.id.clone();
18738        drop(guard);
18739        let saved = RunState::load(&id).unwrap();
18740        assert_eq!(saved.status, RunStatus::Blocked);
18741        assert!(!saved.startup.as_ref().unwrap().complete);
18742        assert!(
18743            saved
18744                .startup
18745                .unwrap()
18746                .failure
18747                .unwrap()
18748                .contains("interrupted")
18749        );
18750        assert!(Runner::resume(&id).is_err());
18751    }
18752
18753    #[test]
18754    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18755        ask_test_home();
18756        let mut runner = runner_at(RunStatus::Prep);
18757        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18758        let error = guard
18759            .finish(
18760                &mut runner.state,
18761                Err(
18762                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18763                        .into(),
18764                ),
18765            )
18766            .unwrap_err();
18767        assert_eq!(
18768            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18769            std::io::ErrorKind::PermissionDenied
18770        );
18771        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18772        let mut task = crate::queue::Task::new(
18773            "review".into(),
18774            "criteria".into(),
18775            runner.state.repo.clone(),
18776            crate::queue::Source::Human,
18777        );
18778        task.record_startup_failure(failure.clone());
18779        task.record_startup_failure(failure.clone());
18780        assert_eq!(task.startup_failures.len(), 1);
18781        assert!(task.runs.is_empty());
18782        assert_eq!(task.attempts, 0);
18783    }
18784
18785    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18786        ask_test_home();
18787        let tmp = tempfile::tempdir().unwrap();
18788        let repo = tmp.path().join("repo");
18789        std::fs::create_dir(&repo).unwrap();
18790        init_repo(&repo);
18791        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18792        let origin = tmp.path().join("origin.git");
18793        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18794            .await
18795            .unwrap();
18796        git::git(
18797            &repo,
18798            &["remote", "add", "origin", origin.to_str().unwrap()],
18799        )
18800        .await
18801        .unwrap();
18802        git::git(&repo, &["checkout", "-b", "fix/retained"])
18803            .await
18804            .unwrap();
18805        std::fs::write(repo.join("retained"), "retained change").unwrap();
18806        git::git(&repo, &["add", "."]).await.unwrap();
18807        git::git(&repo, &["commit", "-m", "retained implementation"])
18808            .await
18809            .unwrap();
18810        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18811        git::git(&repo, &["checkout", "main"]).await.unwrap();
18812        std::fs::write(repo.join("base-change"), "new base").unwrap();
18813        git::git(&repo, &["add", "."]).await.unwrap();
18814        git::git(&repo, &["commit", "-m", "base moved"])
18815            .await
18816            .unwrap();
18817        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18818        git::git(&repo, &["checkout", "fix/retained"])
18819            .await
18820            .unwrap();
18821        let mut runner = runner_at(RunStatus::Voting);
18822        runner.state.repo = repo.clone();
18823        runner.state.base_commit = base;
18824        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18825        runner.state.config.disk.min_free_bytes = 0;
18826        runner.state.config.graph.review_rounds = 1;
18827        runner.state.config.verify.e2e = vec!["true".into()];
18828        runner.state.config.verify.gate = vec!["true".into()];
18829        runner.state.candidates = vec![Candidate {
18830            index: 0,
18831            label: 'A',
18832            agent: "fixture".into(),
18833            branch: "fix/retained".into(),
18834            worktree: repo.clone(),
18835            summary: String::new(),
18836            stat: String::new(),
18837            files: 1,
18838            commits: 1,
18839            empty: false,
18840            failed: None,
18841            verified_noop: None,
18842            duration_ms: 0,
18843            folded: false,
18844        }];
18845        runner.state.tally = Some(Tally {
18846            first_choice: BTreeMap::new(),
18847            borda: BTreeMap::new(),
18848            winner: 'A',
18849            rankings: 0,
18850            unanimous_initial: true,
18851            deliberated: false,
18852            changed_votes: 0,
18853            unanimous_final: true,
18854            tie_break: None,
18855            judges: 0,
18856            present: 0,
18857            quorum: 0,
18858            met_quorum: true,
18859            uncontested: Some("review-only".into()),
18860        });
18861        let mut task = crate::queue::Task::new(
18862            "fixture".into(),
18863            "fixture".into(),
18864            repo,
18865            crate::queue::Source::Human,
18866        );
18867        task.link_run(&runner.state.id);
18868        crate::queue::Queue::open().put(&mut task).unwrap();
18869        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18870        runner.state.base_sync = Some(BaseSync {
18871            tip: String::new(),
18872            behind: 1,
18873            attempts: BASE_SYNC_ROUNDS,
18874            conflict: None,
18875            already_in: None,
18876        });
18877        runner.sync_to_base().await.unwrap();
18878        assert_eq!(runner.state.status, RunStatus::Blocked);
18879        (tmp, runner, head, task.id)
18880    }
18881
18882    #[tokio::test]
18883    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18884        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18885        runner.state.status = RunStatus::Voting;
18886        runner.state.base_sync = None;
18887        runner.state.base_sync_recovery = Default::default();
18888        let scratch = runner.state.dir().join("base-sync");
18889        std::fs::create_dir_all(&scratch).unwrap();
18890        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18891        runner.sync_to_base().await.unwrap();
18892        assert!(runner.state.resource_block.is_some());
18893        assert!(!runner.state.base_sync_blocked());
18894        assert!(runner.state.base_sync.is_none());
18895        assert_eq!(
18896            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18897            "keep"
18898        );
18899        assert_eq!(runner.state.base_episode_used(), 0);
18900        assert!(runner.state.base_sync_recovery.operations.is_empty());
18901        assert!(runner.state.rebase_fixes.is_empty());
18902        assert_eq!(
18903            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18904            head
18905        );
18906        std::fs::remove_dir_all(&scratch).unwrap();
18907        runner.state.resource_block = None;
18908        runner.sync_to_base().await.unwrap();
18909        assert!(!runner.state.base_sync_blocked());
18910        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18911        assert_eq!(runner.state.base_episode_used(), 1);
18912        assert!(runner.state.base_sync_recovery.operations[0].finished);
18913        assert!(runner.state.rebase_fixes.is_empty());
18914        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18915        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18916    }
18917
18918    #[tokio::test]
18919    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18920        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18921        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18922        runner.state.base_sync_recovery = Default::default();
18923        runner.state.task_instruction = Some("fixture".into());
18924        runner.state.config.agents = vec![spec("fixture")];
18925        runner.state.config.graph.review_rounds = 0;
18926        runner.state.config.merge.mode = MergeMode::None;
18927        runner.state.driver_exited = true;
18928        let sync = runner.state.base_sync.as_mut().unwrap();
18929        sync.conflict = None;
18930        sync.attempts = 0;
18931        runner.state.reserve_base_operation(&head, &tip);
18932        runner.state.finish_base_operation(None);
18933        let detail = format!(
18934            "fix/retained conflicts with origin/main and did not rebase: \
18935             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18936             remaining conflicted path(s): none recorded; git said: \
18937             warning: execution failed: {}",
18938            git::REBASE_EXEC
18939        );
18940        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18941        runner.state.record_base_sync_stop(&head);
18942        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18943            unstarted: false,
18944            agent: "fixture".into(),
18945            paths: Vec::new(),
18946            from: Some(head.clone()),
18947            finished: true,
18948            error: None,
18949            stop: None,
18950            onto: None,
18951            index_outside: None,
18952            launcher: None,
18953            infra: None,
18954            outage: None,
18955        });
18956        runner.state.save().unwrap();
18957        assert_eq!(
18958            crate::resume::validate(&crate::run::home(), &runner.state.id)
18959                .unwrap()
18960                .id,
18961            runner.state.id
18962        );
18963
18964        let dirty = runner.state.repo.join("owner-work");
18965        std::fs::write(&dirty, "keep").unwrap();
18966        runner.sync_to_base().await.unwrap();
18967        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18968        assert!(runner.state.base_sync_recovery.operations[0].finished);
18969        assert!(runner.state.base_sync_blocked());
18970        std::fs::remove_file(dirty).unwrap();
18971
18972        let queue = crate::queue::Queue::open();
18973        let id = runner.state.id.clone();
18974        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18975        let _claim = queue.claim(&owner).unwrap();
18976        let mut task = queue.get(&owner).unwrap();
18977        let config = tmp.path().join("test-config.toml");
18978        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18979        let opts = crate::daemon::Opts {
18980            repo: task.repo.clone(),
18981            config: Some(config),
18982            ..Default::default()
18983        };
18984        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18985        let task = queue.get(&owner).unwrap();
18986        assert_eq!(
18987            task.runs.as_slice(),
18988            std::slice::from_ref(&id),
18989            "{:?}",
18990            task.hold_reason
18991        );
18992        runner.state = RunState::load(&id).unwrap();
18993        assert!(!runner.state.base_sync_blocked());
18994        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18995        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18996        assert!(runner.state.base_sync_recovery.operations[0].finished);
18997        assert_eq!(
18998            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18999            detail
19000        );
19001        assert_eq!(runner.state.rebase_fixes.len(), 1);
19002        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
19003    }
19004
19005    #[cfg(unix)]
19006    #[tokio::test]
19007    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
19008        for routed in [false, true] {
19009            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
19010            let home = crate::run::home();
19011            let queue = crate::queue::Queue::open();
19012            let task = queue.get(&owner).unwrap();
19013            runner.state.task_instruction = Some(task.instruction.clone());
19014            runner.state.driver_exited = true;
19015            runner.state.save().unwrap();
19016            let questions = crate::ask::Questions::at(home.join("questions"));
19017            let mut q = crate::ask::Question::new(
19018                runner.state.id.clone(),
19019                "base-recovery".into(),
19020                "owner".into(),
19021                "Recover bounded base movement?".into(),
19022                String::new(),
19023                vec!["recover".into()],
19024            );
19025            q.actions.insert(
19026                "recover".into(),
19027                crate::ask::ChoiceAction::RecoverBase {
19028                    run: runner.state.id.clone(),
19029                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
19030                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
19031                },
19032            );
19033            q.routed_task = Some(owner.clone());
19034            q.answer(crate::ask::Answer::Choice("recover".into()))
19035                .unwrap();
19036            questions.put(&mut q).unwrap();
19037            crate::base_recovery_control::recover(
19038                &queue,
19039                &home,
19040                crate::base_recovery_control::Request {
19041                    run: runner.state.id.clone(),
19042                    head: head.clone(),
19043                    actor: "decisions".into(),
19044                    request: q.id.clone(),
19045                    decision: Some((owner.clone(), q.answered_at.unwrap())),
19046                    expected_stop: Some((
19047                        runner.state.base_sync_recovery.stop.clone().unwrap(),
19048                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
19049                    )),
19050                    evidence_digest: None,
19051                },
19052            )
19053            .await
19054            .unwrap();
19055            if routed {
19056                questions
19057                    .update(&q.id, |q| {
19058                        q.routed_task = Some("another-owner".into());
19059                        Ok(())
19060                    })
19061                    .unwrap();
19062            } else {
19063                let mut task = queue.get(&owner).unwrap();
19064                task.hold_manual(Some("new owner decision".into()));
19065                // Keep the generation to exercise the separate owner-decision binding.
19066                task.status = crate::queue::TaskStatus::Queued;
19067                queue.put(&mut task).unwrap();
19068            }
19069            runner.state = RunState::load(&runner.state.id).unwrap();
19070            runner.sync_to_base().await.unwrap();
19071            let approval = runner
19072                .state
19073                .base_sync_recovery
19074                .authorizations
19075                .last()
19076                .unwrap();
19077            assert!(approval.consumed);
19078            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
19079                "routing"
19080            } else {
19081                "owner decision"
19082            }));
19083            assert_eq!(
19084                runner.state.base_sync.as_ref().unwrap().attempts,
19085                BASE_SYNC_ROUNDS
19086            );
19087            assert_eq!(
19088                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19089                head
19090            );
19091        }
19092    }
19093
19094    #[cfg(unix)]
19095    #[tokio::test]
19096    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
19097        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
19098        if std::env::var_os(CHILD).is_none() {
19099            let home = tempfile::tempdir().unwrap();
19100            let output = std::process::Command::new(std::env::current_exe().unwrap())
19101                .args([
19102                    "--exact",
19103                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
19104                    "--nocapture",
19105                ])
19106                .env(CHILD, "1")
19107                .env("MAGI_HOME", home.path())
19108                .env("MAGI_WORKER_HOME", home.path())
19109                .env("MAGI_WORKER_ID", "abcdef")
19110                .output()
19111                .unwrap();
19112            assert!(
19113                output.status.success()
19114                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19115                "{}\n{}",
19116                String::from_utf8_lossy(&output.stdout),
19117                String::from_utf8_lossy(&output.stderr)
19118            );
19119            return;
19120        }
19121        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
19122        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19123        let home = crate::run::home();
19124        let queue = crate::queue::Queue::open();
19125        let mut owner = queue.get(&task).unwrap();
19126        owner.release_operator("test-release", None);
19127        owner.start(runner.state.id.clone());
19128        queue.put(&mut owner).unwrap();
19129        runner.state.driver_exited = true;
19130        runner.state.task_instruction = Some(owner.instruction.clone());
19131        runner.state.save().unwrap();
19132        let _claim = queue.claim(&task).unwrap();
19133        let reserve = |id: &str| {
19134            let directory = home.join("workers/jobs").join(id);
19135            std::fs::create_dir_all(&directory).unwrap();
19136            let job = crate::worker::Job {
19137                id: id.into(),
19138                sequence: 1,
19139                kind: "task".into(),
19140                key: format!("task:{task}"),
19141                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
19142                generation: "fixture-generation".into(),
19143                version: None,
19144                status: crate::worker::Status::Running,
19145                result: None,
19146                pid: Some(std::process::id()),
19147                created_at: 0,
19148                finished_at: None,
19149            };
19150            std::fs::write(
19151                directory.join("job.json"),
19152                serde_json::to_vec(&job).unwrap(),
19153            )
19154            .unwrap();
19155            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
19156        };
19157        let _own = reserve("abcdef");
19158        let other = reserve("fedcba");
19159        assert!(
19160            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19161                .await
19162                .is_err()
19163        );
19164        assert!(
19165            RunState::load(&runner.state.id)
19166                .unwrap()
19167                .base_sync_recovery
19168                .authorizations
19169                .is_empty()
19170        );
19171        drop(other);
19172        assert!(crate::daemon::is_working_on(
19173            &home,
19174            &runner.state.id,
19175            Timestamp::now()
19176        ));
19177        assert!(
19178            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
19179        );
19180        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19181            .await
19182            .unwrap();
19183        assert!(
19184            RunState::load(&runner.state.id)
19185                .unwrap()
19186                .base_recovery_pending()
19187        );
19188    }
19189
19190    #[cfg(unix)]
19191    #[tokio::test]
19192    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
19193        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19194        let home = crate::run::home();
19195        runner.state.driver_pid = Some(std::process::id());
19196        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
19197        runner.state.driver_exited = false;
19198        runner.state.begin_pass();
19199        runner.state.save().unwrap();
19200        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
19201        driver.record(&runner.state).unwrap();
19202        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
19203        // Preserve the durable claim as if the process died before Drop saved.
19204        drop(driver);
19205        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
19206        assert_eq!(
19207            runner.state.liveness_under(&home, false),
19208            crate::run::Liveness::Dead
19209        );
19210        let queue = crate::queue::Queue::open();
19211        let _claim = queue.claim(&task).unwrap();
19212        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19213            .await
19214            .unwrap();
19215        let disk = RunState::load(&runner.state.id).unwrap();
19216        assert!(!disk.driver_exited);
19217        assert!(disk.base_recovery_pending());
19218    }
19219
19220    #[cfg(unix)]
19221    #[tokio::test]
19222    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
19223        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
19224        if std::env::var_os(CHILD).is_none() {
19225            use std::os::unix::fs::PermissionsExt;
19226            let tmp = tempfile::tempdir().unwrap();
19227            let gh = tmp.path().join("gh");
19228            std::fs::write(&gh, r#"#!/bin/sh
19229case "$1 $2" in
19230  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
19231  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
19232  *) exit 2 ;;
19233esac
19234"#).unwrap();
19235            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
19236            let mut paths = vec![tmp.path().to_path_buf()];
19237            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
19238            let output = std::process::Command::new(std::env::current_exe().unwrap())
19239                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
19240                .env(CHILD, "1")
19241                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
19242                .env("PATH", std::env::join_paths(paths).unwrap())
19243                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
19244                .output().unwrap();
19245            assert!(
19246                output.status.success()
19247                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19248                "{}\n{}",
19249                String::from_utf8_lossy(&output.stdout),
19250                String::from_utf8_lossy(&output.stderr)
19251            );
19252            return;
19253        }
19254        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19255        let repo = runner.state.repo.clone();
19256        git::git(&repo, &["checkout", "main"]).await.unwrap();
19257        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19258        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19259        git::git(&repo, &["checkout", "fix/retained"])
19260            .await
19261            .unwrap();
19262        runner.state.pr = Some(crate::run::PrRecord {
19263            url: "https://example.test/project/pull/1".into(),
19264            number: 1,
19265            state: "open".into(),
19266            checks: "unknown".into(),
19267            round: 0,
19268            rounds: 1,
19269            red_at_merge: Vec::new(),
19270        });
19271        runner.sync_to_base().await.unwrap();
19272        assert_eq!(runner.state.status, RunStatus::Blocked);
19273        assert_eq!(
19274            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19275            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19276        );
19277        assert!(runner.state.base_sync_closure_pending());
19278        assert!(crate::handover::can_resume(&runner.state));
19279        let queue = crate::queue::Queue::open();
19280        assert!(!crate::base_sync_recovery::held_task(
19281            &queue,
19282            &queue.get(&task).unwrap()
19283        ));
19284        assert!(runner.state.authorize_base_sync(&task).is_err());
19285        // Legacy closure stops have no typed stop but must retain the checkpoint.
19286        runner.state.base_sync_recovery.stop = None;
19287        runner.state.status = RunStatus::Voting;
19288        runner.state.gate_ran = true;
19289        runner.state.config.graph.review_rounds = 0;
19290        runner.state.save().unwrap();
19291        assert!(crate::handover::can_resume(&runner.state));
19292        runner.state = RunState::load(&runner.state.id).unwrap();
19293        runner.execute_graph().await.unwrap();
19294        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19295        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19296        assert_eq!(
19297            runner.state.base_sync.as_ref().unwrap().attempts,
19298            BASE_SYNC_ROUNDS
19299        );
19300        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19301        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19302        assert!(runner.state.reviews.is_empty());
19303        assert!(runner.state.gate.is_empty());
19304    }
19305
19306    #[cfg(unix)]
19307    #[tokio::test]
19308    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19309        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19310        runner.state.driver_exited = true;
19311        runner.state.save().unwrap();
19312        let home = crate::run::home();
19313        let queue = crate::queue::Queue::open();
19314        let _claim = queue.claim(&task).unwrap();
19315        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19316        assert!(
19317            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19318                .await
19319                .is_err()
19320        );
19321        drop(lease);
19322        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19323        assert!(
19324            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19325                .await
19326                .is_err()
19327        );
19328        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19329        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19330            .await
19331            .unwrap();
19332        let disk = RunState::load(&runner.state.id).unwrap();
19333        assert!(disk.base_recovery_pending());
19334        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19335        assert!(
19336            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19337                .await
19338                .is_err()
19339        );
19340        assert_eq!(
19341            RunState::load(&runner.state.id)
19342                .unwrap()
19343                .base_sync_recovery
19344                .authorizations
19345                .len(),
19346            1
19347        );
19348        let mut owner = queue.get(&task).unwrap();
19349        owner.runs.push("20260101-000000-ffff".into());
19350        queue.put(&mut owner).unwrap();
19351        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19352            .await
19353            .unwrap_err();
19354        assert!(error.to_string().contains("run task ownership changed"));
19355    }
19356
19357    #[cfg(unix)]
19358    #[tokio::test]
19359    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19360        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19361        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19362        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19363        legacy["status"] = serde_json::json!("voting");
19364        runner.state = serde_json::from_value(legacy).unwrap();
19365        runner.state.save().unwrap();
19366        for _ in 0..3 {
19367            runner.execute_graph().await.unwrap();
19368            assert_eq!(runner.state.status, RunStatus::Blocked);
19369            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19370            assert!(!crate::handover::can_resume(&runner.state));
19371            assert_eq!(
19372                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19373                head
19374            );
19375            assert!(runner.state.reviews.is_empty());
19376            assert!(!runner.state.gate_ran);
19377        }
19378        let notice = crate::notices::run_ended(&runner.state).unwrap();
19379        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19380        runner.state.begin_pass();
19381        runner.state.status = RunStatus::Voting;
19382        runner.deliberate().await.unwrap();
19383        runner.vote().await.unwrap();
19384        runner.finish_after_tally().await.unwrap();
19385        assert_eq!(runner.state.status, RunStatus::Blocked);
19386        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19387        assert_eq!(
19388            crate::notices::run_ended(&runner.state).unwrap().since,
19389            notice.since
19390        );
19391    }
19392
19393    #[cfg(unix)]
19394    #[tokio::test]
19395    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19396        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19397        for detail in [
19398            "fix/retained conflicts with origin/main and did not rebase: conflict",
19399            "rebased fix/retained locally but origin refused the push",
19400            "unknown failure",
19401        ] {
19402            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19403            runner.state.record_base_sync_stop(&head);
19404            assert!(runner.state.authorize_base_sync(&task).is_err());
19405            runner.state.status = RunStatus::Voting;
19406            runner.execute_graph().await.unwrap();
19407            assert_eq!(runner.state.status, RunStatus::Blocked);
19408            assert!(!crate::handover::can_resume(&runner.state));
19409            assert_eq!(
19410                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19411                head
19412            );
19413        }
19414    }
19415
19416    #[tokio::test]
19417    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19418        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19419        let state = &mut runner.state;
19420        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19421        let branch = state.winner().unwrap().branch.clone();
19422        state.base_sync_recovery = Default::default();
19423        state.base_sync.as_mut().unwrap().attempts = 0;
19424        state.reserve_base_operation(&head, &tip);
19425        state.finish_base_operation(None);
19426        let detail = format!(
19427            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19428        );
19429        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19430        state.event("land", detail);
19431        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19432        assert!(state.unknown_preparation_stop(&head));
19433        let digest = state.preparation_digest(&head).unwrap();
19434        state
19435            .base_sync_recovery
19436            .operations
19437            .last_mut()
19438            .unwrap()
19439            .validated_head = Some(head.clone());
19440        assert!(!state.unknown_preparation_stop(&head));
19441        state
19442            .base_sync_recovery
19443            .operations
19444            .last_mut()
19445            .unwrap()
19446            .validated_head = None;
19447        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19448        state.driver_exited = true;
19449        state.save().unwrap();
19450        let home = crate::run::home();
19451        let queue = crate::queue::Queue::open();
19452        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19453            .await
19454            .unwrap();
19455        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19456        assert_eq!(inspection["evidence_digest"], digest);
19457        let request = crate::base_recovery_control::Request {
19458            run: state.id.clone(),
19459            head: head.clone(),
19460            actor: "test".into(),
19461            request: "preparation".into(),
19462            decision: None,
19463            expected_stop: None,
19464            evidence_digest: Some(digest),
19465        };
19466        let mut stale = request.clone();
19467        stale.evidence_digest = Some("stale".into());
19468        assert!(
19469            crate::base_recovery_control::recover(&queue, &home, stale)
19470                .await
19471                .is_err()
19472        );
19473        let scratch = state.dir().join("base-sync");
19474        std::fs::create_dir(&scratch).unwrap();
19475        assert!(
19476            crate::base_recovery_control::recover(&queue, &home, request.clone())
19477                .await
19478                .is_err()
19479        );
19480        std::fs::remove_dir(&scratch).unwrap();
19481        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19482        git::git(
19483            &state.repo,
19484            &[
19485                "commit",
19486                "--allow-empty",
19487                "-m",
19488                "base advanced after inspection",
19489            ],
19490        )
19491        .await
19492        .unwrap();
19493        git::git(&state.repo, &["push", "origin", "main"])
19494            .await
19495            .unwrap();
19496        git::git(&state.repo, &["checkout", "fix/retained"])
19497            .await
19498            .unwrap();
19499        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19500            .await
19501            .unwrap();
19502        assert!(!outcome.repeated);
19503        assert!(
19504            crate::base_recovery_control::recover(&queue, &home, request)
19505                .await
19506                .unwrap()
19507                .repeated
19508        );
19509        runner.state = RunState::load(&runner.state.id).unwrap();
19510        assert!(runner.state.base_recovery_pending());
19511        runner.sync_to_base().await.unwrap();
19512        assert!(!runner.state.base_sync_blocked());
19513        assert!(!runner.state.consume_base_recovery(&head));
19514        assert_eq!(runner.state.base_episode_used(), 2);
19515        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19516        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19517        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19518    }
19519
19520    #[cfg(unix)]
19521    #[tokio::test]
19522    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19523        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19524        runner.state.authorize_base_sync(&task).unwrap();
19525        assert!(runner.state.consume_base_recovery(&head));
19526        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19527        runner.state.reserve_base_operation(&head, &tip);
19528        runner.state.save().unwrap();
19529        runner.state = RunState::load(&runner.state.id).unwrap();
19530        assert!(!runner.state.consume_base_recovery(&head));
19531        runner.sync_to_base().await.unwrap();
19532        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19533        assert_eq!(runner.state.base_episode_used(), 1);
19534        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19535        assert!(
19536            runner
19537                .state
19538                .base_sync_recovery
19539                .operations
19540                .last()
19541                .unwrap()
19542                .finished
19543        );
19544        assert!(!runner.state.base_sync_blocked());
19545        runner.sync_to_base().await.unwrap();
19546        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19547    }
19548
19549    #[cfg(unix)]
19550    #[tokio::test]
19551    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19552        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19553        // Both historical diagnostic spellings retain an exhaustion identity.
19554        let original = runner
19555            .state
19556            .base_sync
19557            .as_ref()
19558            .unwrap()
19559            .conflict
19560            .clone()
19561            .unwrap();
19562        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19563            original
19564                .replace("synchronization(s)", "rebase(s)")
19565                .replace("synchronizing", "rebasing"),
19566        );
19567        runner.state.base_sync_recovery = Default::default();
19568        runner.state.record_base_sync_stop(&head);
19569        assert_eq!(
19570            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19571            crate::base_sync_recovery::StopKind::Exhausted
19572        );
19573        runner.state.authorize_base_sync(&task).unwrap();
19574        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19575        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19576            .as_object_mut()
19577            .unwrap();
19578        auth.remove("interval");
19579        auth.remove("scope");
19580        runner.state = serde_json::from_value(legacy).unwrap();
19581        assert!(runner.state.consume_base_recovery(&head));
19582        assert_eq!(runner.state.base_episode_used(), 3);
19583        runner.sync_to_base().await.unwrap();
19584        assert_eq!(runner.state.base_episode_used(), 4);
19585        runner.state.resource_block = Some(crate::run::ResourceBlock {
19586            node: "gate".into(),
19587            kind: "cache".into(),
19588            detail: "legacy wait".into(),
19589            at: Timestamp::now(),
19590            cause: crate::run::ResourceBlockCause::Unrecorded,
19591        });
19592        runner.state.save().unwrap();
19593        assert!(
19594            runner
19595                .state
19596                .base_sync_recovery
19597                .episodes
19598                .last()
19599                .unwrap()
19600                .boundary
19601                .is_none()
19602        );
19603        runner.state.resource_block = None;
19604        advance_base_fixture(&runner).await;
19605        runner.sync_to_base().await.unwrap();
19606        assert!(runner.state.base_sync_blocked());
19607        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19608    }
19609
19610    #[cfg(unix)]
19611    async fn advance_base_fixture(runner: &Runner) {
19612        let repo = &runner.state.repo;
19613        for args in [
19614            vec!["checkout", "main"],
19615            vec!["commit", "--allow-empty", "-m", "base advanced"],
19616            vec!["push", "origin", "main"],
19617            vec!["checkout", "fix/retained"],
19618        ] {
19619            git::git(repo, &args).await.unwrap();
19620        }
19621    }
19622
19623    #[cfg(unix)]
19624    fn fresh_base_interval_fixture(runner: &mut Runner) {
19625        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19626        runner.state.base_sync.as_mut().unwrap().conflict = None;
19627        runner.state.base_sync_recovery = Default::default();
19628        runner.state.status = RunStatus::Voting;
19629    }
19630
19631    #[cfg(unix)]
19632    #[tokio::test]
19633    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19634        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19635        fresh_base_interval_fixture(&mut runner);
19636        runner.state.begin_pass();
19637        runner.sync_to_base().await.unwrap();
19638        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19639        runner.state.resource_block = Some(crate::run::ResourceBlock {
19640            node: "gate".into(),
19641            kind: "build cache".into(),
19642            detail: "busy".into(),
19643            at: Timestamp::now(),
19644            cause: crate::run::ResourceBlockCause::Timeout {
19645                waited_secs: 1,
19646                limit_secs: 1,
19647            },
19648        });
19649        runner.state.save().unwrap();
19650        let queue = crate::queue::Queue::open();
19651        let mut owner = queue.get(&task).unwrap();
19652        runner.state.task_instruction = Some(owner.instruction.clone());
19653        owner.release_operator("fixture-owner", None);
19654        queue.put(&mut owner).unwrap();
19655        let approval = owner.resumption.clone().unwrap();
19656        runner.state.resource_block = None;
19657        runner.state.save().unwrap();
19658        runner.state = RunState::load(&runner.state.id).unwrap();
19659        advance_base_fixture(&runner).await;
19660        runner.sync_to_base().await.unwrap();
19661        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19662        assert_eq!(runner.state.base_episode_used(), 1);
19663        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19664        assert!(
19665            runner.state.base_sync_recovery.episodes[0]
19666                .boundary
19667                .as_ref()
19668                .unwrap()
19669                .consumed
19670        );
19671        assert!(
19672            !runner
19673                .state
19674                .renew_base_episode(&task, &approval, &head, "base")
19675        );
19676        for _ in 0..3 {
19677            owner.release_operator("fixture-owner", None);
19678            queue.put(&mut owner).unwrap();
19679            runner.state = RunState::load(&runner.state.id).unwrap();
19680            runner.state.begin_pass();
19681            runner.sync_to_base().await.unwrap();
19682            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19683            assert_eq!(runner.state.base_episode_used(), 1);
19684        }
19685        runner.state.resource_block = Some(crate::run::ResourceBlock {
19686            node: "gate".into(),
19687            kind: "disk pressure".into(),
19688            detail: "free space required".into(),
19689            at: Timestamp::now(),
19690            cause: crate::run::ResourceBlockCause::Other,
19691        });
19692        runner.state.end_pass_parked(ParkCause::Interrupt {
19693            reason: "disk pressure".into(),
19694        });
19695        runner.state.save().unwrap();
19696        owner.release_operator("fixture-owner-after-disk", None);
19697        queue.put(&mut owner).unwrap();
19698        runner.state.resource_block = None;
19699        advance_base_fixture(&runner).await;
19700        runner.sync_to_base().await.unwrap();
19701        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19702        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19703        assert_eq!(runner.state.base_episode_used(), 1);
19704        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19705    }
19706
19707    #[cfg(unix)]
19708    #[tokio::test]
19709    async fn base_recovery_continuous_advancement_stops_at_four() {
19710        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19711        fresh_base_interval_fixture(&mut runner);
19712        for spent in 1..=BASE_SYNC_ROUNDS {
19713            runner.sync_to_base().await.unwrap();
19714            assert!(!runner.state.base_sync_blocked());
19715            assert_eq!(runner.state.base_episode_used(), spent);
19716            advance_base_fixture(&runner).await;
19717        }
19718        runner.sync_to_base().await.unwrap();
19719        assert_eq!(
19720            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19721            crate::base_sync_recovery::StopKind::Exhausted
19722        );
19723        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19724        assert!(stop.unverified_sync);
19725        let action = runner.state.base_sync_next_action();
19726        assert!(action.contains("never reached its gate"));
19727        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19728        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19729        runner.state = RunState::load(&runner.state.id).unwrap();
19730        runner.sync_to_base().await.unwrap();
19731        assert_eq!(runner.state.base_episode_used(), 4);
19732        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19733    }
19734
19735    #[cfg(unix)]
19736    #[tokio::test]
19737    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19738        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19739        runner.state.ensure_base_episode();
19740        // Verification progress alone is not evidence of a successful sync.
19741        runner.state.record_base_progress(&head);
19742        runner.state.base_sync_recovery.stop = None;
19743        runner.state.record_base_sync_stop(&head);
19744        assert!(
19745            !runner
19746                .state
19747                .base_sync_recovery
19748                .stop
19749                .as_ref()
19750                .unwrap()
19751                .unverified_sync
19752        );
19753
19754        runner.state.finish_base_operation(Some(&head));
19755        // A gate for another head cannot verify this synchronization.
19756        runner.state.gate_ran = true;
19757        runner.state.gate_head = Some("older-head".into());
19758        runner.state.base_sync_recovery.stop = None;
19759        runner.state.record_base_sync_stop(&head);
19760        runner.state.save().unwrap();
19761        runner.state = RunState::load(&runner.state.id).unwrap();
19762        assert!(
19763            runner
19764                .state
19765                .base_sync_recovery
19766                .stop
19767                .as_ref()
19768                .unwrap()
19769                .unverified_sync
19770        );
19771
19772        runner.state.gate_head = Some(head.clone());
19773        runner.state.base_sync_recovery.stop = None;
19774        runner.state.record_base_sync_stop(&head);
19775        assert!(
19776            !runner
19777                .state
19778                .base_sync_recovery
19779                .stop
19780                .as_ref()
19781                .unwrap()
19782                .unverified_sync
19783        );
19784        assert!(
19785            !runner
19786                .state
19787                .base_sync_next_action()
19788                .contains("never reached its gate")
19789        );
19790
19791        // Historical records cannot establish the missing synchronization evidence.
19792        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19793        legacy["base_sync_recovery"]["stop"]
19794            .as_object_mut()
19795            .unwrap()
19796            .remove("unverified_sync");
19797        legacy["base_sync_recovery"]["episodes"][0]
19798            .as_object_mut()
19799            .unwrap()
19800            .remove("last_sync_head");
19801        runner.state = serde_json::from_value(legacy).unwrap();
19802        assert!(
19803            !runner
19804                .state
19805                .base_sync_recovery
19806                .stop
19807                .as_ref()
19808                .unwrap()
19809                .unverified_sync
19810        );
19811        assert!(
19812            runner.state.base_sync_recovery.episodes[0]
19813                .last_sync_head
19814                .is_none()
19815        );
19816    }
19817
19818    #[cfg(unix)]
19819    #[tokio::test]
19820    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19821        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19822        runner.state.authorize_base_sync(&task).unwrap();
19823        assert!(
19824            runner
19825                .state
19826                .base_sync_next_action()
19827                .contains("Approval recorded")
19828        );
19829        assert!(
19830            runner
19831                .state
19832                .base_sync_next_action()
19833                .contains("4/4 in episode 0, 4 lifetime")
19834        );
19835        assert!(runner.state.consume_base_recovery(&head));
19836        assert!(
19837            runner
19838                .state
19839                .base_sync_next_action()
19840                .contains("0/4 in episode 1, 4 lifetime")
19841        );
19842    }
19843
19844    #[cfg(unix)]
19845    #[tokio::test]
19846    async fn base_recovery_changed_head_invalidates_without_spending() {
19847        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19848        runner.state.authorize_base_sync(&task).unwrap();
19849        git::git(
19850            &runner.state.repo,
19851            &["commit", "--allow-empty", "-m", "external head change"],
19852        )
19853        .await
19854        .unwrap();
19855        runner.sync_to_base().await.unwrap();
19856        let a = runner
19857            .state
19858            .base_sync_recovery
19859            .authorizations
19860            .last()
19861            .unwrap();
19862        assert!(a.consumed);
19863        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19864        runner.state = RunState::load(&runner.state.id).unwrap();
19865        assert!(
19866            runner
19867                .state
19868                .base_sync_next_action()
19869                .contains("Approval invalidated")
19870        );
19871        assert!(!runner.state.base_recovery_pending());
19872        assert!(runner.state.base_sync_blocked());
19873        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19874    }
19875
19876    #[cfg(unix)]
19877    #[tokio::test]
19878    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19879        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19880        runner.state.driver_exited = true;
19881        runner.state.save().unwrap();
19882        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19883            .await
19884            .unwrap();
19885        runner.state = RunState::load(&runner.state.id).unwrap();
19886        advance_base_fixture(&runner).await;
19887        runner.sync_to_base().await.unwrap();
19888        let a = runner
19889            .state
19890            .base_sync_recovery
19891            .authorizations
19892            .last()
19893            .unwrap();
19894        assert!(
19895            a.consumed
19896                && a.invalidated
19897                    .as_deref()
19898                    .unwrap()
19899                    .contains("fetched base changed")
19900        );
19901        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19902        assert_eq!(
19903            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19904            head
19905        );
19906        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19907            .await
19908            .unwrap();
19909        runner.state = RunState::load(&runner.state.id).unwrap();
19910        runner.sync_to_base().await.unwrap();
19911        assert!(!runner.state.base_sync_blocked());
19912        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19913    }
19914
19915    #[cfg(unix)]
19916    #[tokio::test]
19917    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19918        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19919        runner.state.authorize_base_sync(&task).unwrap();
19920        assert!(runner.state.consume_base_recovery(&head));
19921        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19922        runner.state.reserve_base_operation(&head, &tip);
19923        runner.state.save().unwrap();
19924        let scratch = runner.state.dir().join("base-sync");
19925        assert_eq!(
19926            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19927                .await
19928                .unwrap(),
19929            crate::rebase::Rebased::Applied
19930        );
19931        runner.state = RunState::load(&runner.state.id).unwrap();
19932        runner.sync_to_base().await.unwrap();
19933        assert!(
19934            runner
19935                .state
19936                .base_sync_recovery
19937                .operations
19938                .last()
19939                .unwrap()
19940                .finished
19941        );
19942        assert_eq!(runner.state.base_episode_used(), 1);
19943        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19944        assert!(!runner.state.base_sync_blocked());
19945    }
19946
19947    #[cfg(unix)]
19948    #[tokio::test]
19949    async fn base_recovery_crash_preserves_untracked_files() {
19950        for ignored in [false, true] {
19951            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19952            runner.state.authorize_base_sync(&task).unwrap();
19953            assert!(runner.state.consume_base_recovery(&head));
19954            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19955            runner.state.reserve_base_operation(&head, &tip);
19956            runner.state.save().unwrap();
19957            let scratch = runner.state.dir().join("base-sync");
19958            assert_eq!(
19959                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19960                    .await
19961                    .unwrap(),
19962                crate::rebase::Rebased::Applied
19963            );
19964            let repo = &runner.state.repo;
19965            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19966            assert_ne!(result, head);
19967            if ignored {
19968                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19969                    .await
19970                    .unwrap();
19971                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19972            }
19973            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19974            assert!(
19975                git::git_raw(repo, &["diff", "--quiet", &head])
19976                    .await
19977                    .unwrap()
19978                    .ok()
19979            );
19980            // Resume after the branch moved, before its checkout was reset.
19981            runner.state = RunState::load(&runner.state.id).unwrap();
19982            runner.sync_to_base().await.unwrap();
19983            assert!(runner.state.base_sync_blocked());
19984            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19985            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19986            assert_eq!(
19987                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19988                result
19989            );
19990            assert_eq!(
19991                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19992                "retained work\n"
19993            );
19994            assert!(
19995                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19996                    .await
19997                    .unwrap()
19998                    .ok()
19999            );
20000        }
20001    }
20002
20003    #[cfg(unix)]
20004    #[tokio::test]
20005    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
20006        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20007        runner.state.authorize_base_sync(&task).unwrap();
20008        assert!(runner.state.consume_base_recovery(&head));
20009        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
20010        runner.state.reserve_base_operation(&head, &tip);
20011        runner.state.save().unwrap();
20012        let scratch = runner.state.dir().join("base-sync");
20013        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
20014            .await
20015            .unwrap();
20016        git::sync_to_head(&runner.state.repo).await.unwrap();
20017        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
20018        git::git(&runner.state.repo, &["add", "foreign"])
20019            .await
20020            .unwrap();
20021        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
20022            .await
20023            .unwrap();
20024        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20025        runner.state = RunState::load(&runner.state.id).unwrap();
20026        runner.sync_to_base().await.unwrap();
20027        assert!(runner.state.base_sync_blocked());
20028        assert!(
20029            !runner
20030                .state
20031                .base_sync_recovery
20032                .operations
20033                .last()
20034                .unwrap()
20035                .finished
20036        );
20037        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20038        assert_eq!(
20039            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20040            foreign_head
20041        );
20042    }
20043
20044    #[cfg(unix)]
20045    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
20046    {
20047        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20048        fresh_base_interval_fixture(&mut runner);
20049        let repo = &runner.state.repo;
20050        git::git(repo, &["checkout", "main"]).await.unwrap();
20051        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
20052        git::git(repo, &["add", "retained"]).await.unwrap();
20053        git::git(repo, &["commit", "-m", "upstream retained change"])
20054            .await
20055            .unwrap();
20056        git::git(repo, &["push", "origin", "main"]).await.unwrap();
20057        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
20058        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
20059        let scratch = runner.state.dir().join("base-sync");
20060        assert!(matches!(
20061            git::rebase_start(repo, &scratch, "fix/retained", &tip)
20062                .await
20063                .unwrap(),
20064            git::RebaseStart::Conflicted(_)
20065        ));
20066        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
20067            unstarted: false,
20068            agent: "fixture".into(),
20069            paths: vec!["retained".into()],
20070            from: Some(head.clone()),
20071            onto: None,
20072            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
20073            index_outside: None,
20074            finished: false,
20075            error: None,
20076            launcher: None,
20077            infra: None,
20078            outage: None,
20079        });
20080        (tmp, runner, head, tip, scratch)
20081    }
20082
20083    #[cfg(unix)]
20084    #[tokio::test]
20085    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
20086        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20087        // A resource stop from before reservations existed, with resolved
20088        // contents left for the launcher's ordinary staging continuation.
20089        std::fs::write(
20090            scratch.join("retained"),
20091            "upstream and retained resolution\n",
20092        )
20093        .unwrap();
20094        runner.state.resource_block = Some(crate::run::ResourceBlock {
20095            node: "rebase".into(),
20096            kind: "repository coordination".into(),
20097            detail: "busy".into(),
20098            at: Timestamp::now(),
20099            cause: crate::run::ResourceBlockCause::Other,
20100        });
20101        runner.state.save().unwrap();
20102        // Advance the remote without moving either checkout participating
20103        // in the standing rebase.
20104        let newer = git::git(
20105            &runner.state.repo,
20106            &[
20107                "commit-tree",
20108                "main^{tree}",
20109                "-p",
20110                "main",
20111                "-m",
20112                "base advanced during wait",
20113            ],
20114        )
20115        .await
20116        .unwrap();
20117        git::git(
20118            &runner.state.repo,
20119            &[
20120                "push",
20121                "origin",
20122                &format!("{}:refs/heads/main", newer.trim()),
20123            ],
20124        )
20125        .await
20126        .unwrap();
20127        runner.state = RunState::load(&runner.state.id).unwrap();
20128        runner.state.resource_block = None;
20129        runner.sync_to_base().await.unwrap();
20130        assert!(!runner.state.base_sync_blocked());
20131        let op = &runner.state.base_sync_recovery.operations[0];
20132        assert_eq!(op.head, head);
20133        assert_eq!(op.tip, tip);
20134        assert!(op.finished);
20135        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20136        assert_eq!(runner.state.rebase_fixes.len(), 1);
20137        let latest = git::rev_parse(&runner.state.repo, "origin/main")
20138            .await
20139            .unwrap();
20140        assert_ne!(latest, tip);
20141        runner.state = RunState::load(&runner.state.id).unwrap();
20142        runner.sync_to_base().await.unwrap();
20143        assert!(!runner.state.base_sync_blocked());
20144        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
20145        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
20146        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
20147    }
20148
20149    #[cfg(unix)]
20150    #[tokio::test]
20151    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
20152        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20153        runner.state.reserve_base_operation(&head, &tip);
20154        runner.state.save().unwrap();
20155        std::fs::write(
20156            scratch.join("retained"),
20157            "upstream and retained resolution\n",
20158        )
20159        .unwrap();
20160        git::git(&scratch, &["add", "retained"]).await.unwrap();
20161        git::git(
20162            &scratch,
20163            &["-c", "core.editor=true", "rebase", "--continue"],
20164        )
20165        .await
20166        .unwrap();
20167        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20168        assert!(
20169            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20170                .await
20171                .unwrap()
20172                .is_empty()
20173        );
20174        assert_eq!(
20175            crate::rebase::finish(
20176                &mut runner.state,
20177                &scratch,
20178                "fix/retained",
20179                &head,
20180                &tip,
20181                &["retained".into()],
20182                ""
20183            )
20184            .await
20185            .unwrap(),
20186            crate::rebase::Rebased::Applied
20187        );
20188        assert!(!scratch.exists());
20189        // Simulate losing the caller before finish_base_operation/save.
20190        runner.state = RunState::load(&runner.state.id).unwrap();
20191        let op = &runner.state.base_sync_recovery.operations[0];
20192        assert!(!op.finished);
20193        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
20194        runner.sync_to_base().await.unwrap();
20195        assert!(!runner.state.base_sync_blocked());
20196        assert!(runner.state.base_sync_recovery.operations[0].finished);
20197        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20198        assert_eq!(runner.state.rebase_fixes.len(), 1);
20199        let winner = runner.state.winner().unwrap().clone();
20200        let wait = runner.repository_wait();
20201        assert!(
20202            verify_current_head(&mut runner.state, &winner, &wait)
20203                .await
20204                .unwrap()
20205        );
20206        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20207    }
20208
20209    #[cfg(unix)]
20210    #[tokio::test]
20211    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
20212        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
20213            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20214            runner.state.reserve_base_operation(&head, &tip);
20215            runner.state.save().unwrap();
20216            std::fs::write(
20217                scratch.join("retained"),
20218                "upstream and retained resolution\n",
20219            )
20220            .unwrap();
20221            git::git(&scratch, &["add", "retained"]).await.unwrap();
20222            git::git(
20223                &scratch,
20224                &["-c", "core.editor=true", "rebase", "--continue"],
20225            )
20226            .await
20227            .unwrap();
20228            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20229            assert!(!git::rebase_in_progress(&scratch).await);
20230            assert!(
20231                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20232                    .await
20233                    .unwrap()
20234                    .is_empty()
20235            );
20236            match damage {
20237                Some("record") => {
20238                    let path =
20239                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
20240                            .await
20241                            .unwrap();
20242                    std::fs::write(scratch.join(path), "").unwrap();
20243                }
20244                Some("foreign") => {
20245                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20246                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20247                    git::git(&scratch, &["commit", "-m", "foreign work"])
20248                        .await
20249                        .unwrap();
20250                }
20251                Some("dirty") => {
20252                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20253                }
20254                _ => {}
20255            }
20256            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20257            // Crash immediately after Git continuation, before finish runs.
20258            runner.state = RunState::load(&runner.state.id).unwrap();
20259            assert!(
20260                runner.state.base_sync_recovery.operations[0]
20261                    .validated_head
20262                    .is_none()
20263            );
20264            runner.sync_to_base().await.unwrap();
20265            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20266            assert_eq!(runner.state.base_episode_used(), 1);
20267            assert_eq!(runner.state.rebase_fixes.len(), 1);
20268            assert_eq!(
20269                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20270                retained_head
20271            );
20272            if damage.is_some() {
20273                assert!(runner.state.base_sync_blocked());
20274                assert!(scratch.exists());
20275                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20276                assert!(
20277                    runner.state.base_sync_recovery.operations[0]
20278                        .validated_head
20279                        .is_none()
20280                );
20281            } else {
20282                assert!(!runner.state.base_sync_blocked());
20283                assert!(!scratch.exists());
20284                assert!(runner.state.base_sync_recovery.operations[0].finished);
20285                assert_eq!(
20286                    runner.state.base_sync_recovery.operations[0]
20287                        .validated_head
20288                        .as_deref(),
20289                    Some(result.as_str())
20290                );
20291                let winner = runner.state.winner().unwrap().clone();
20292                let wait = runner.repository_wait();
20293                assert!(
20294                    verify_current_head(&mut runner.state, &winner, &wait)
20295                        .await
20296                        .unwrap()
20297                );
20298                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20299                runner.state = RunState::load(&runner.state.id).unwrap();
20300                runner.sync_to_base().await.unwrap();
20301                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20302            }
20303        }
20304    }
20305
20306    #[cfg(unix)]
20307    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20308        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20309        // This is an ordinary gate stop, not an authorized base-budget recovery.
20310        runner.state.prep_complete = Some(true);
20311        runner.state.base_sync = None;
20312        runner.state.base_sync_recovery = Default::default();
20313        runner.state.config.graph.gate_fix_rounds = 1;
20314        let mut review = review_round(true, 0, 1, 1, false, true);
20315        review.head = head.clone();
20316        review.verified_head = Some(head.clone());
20317        runner.state.reviews = vec![review];
20318        runner.state.gate = vec![CommandOutcome {
20319            command: "old gate".into(),
20320            code: Some(1),
20321            output_tail: "old failure".into(),
20322            duration_ms: 0,
20323            resource_blocked: false,
20324            ..Default::default()
20325        }];
20326        runner.state.gate_head = Some(head.clone());
20327        runner.state.gate_ran = true;
20328        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20329            agent: "fixture".into(),
20330            failed: runner.state.gate.clone(),
20331            notes: "spent".into(),
20332            committed: false,
20333            error: None,
20334        }];
20335        runner.state.land_approval = Some(crate::run::LandApproval {
20336            question: "old approval".into(),
20337            head: head.clone(),
20338        });
20339        runner.state.status = RunStatus::Blocked;
20340        (tmp, runner, head)
20341    }
20342
20343    #[cfg(unix)]
20344    #[tokio::test]
20345    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20346        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20347        runner.sync_to_base().await.unwrap();
20348        let winner = runner.state.winner().unwrap().clone();
20349        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20350        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20351        assert_ne!(head, base);
20352        runner.state.config.verify.e2e = vec![format!(
20353            "git update-ref refs/remotes/origin/main {head} && false"
20354        )];
20355        let wait = repository_wait(&runner.state, None);
20356        assert!(
20357            !verify_current_head(&mut runner.state, &winner, &wait)
20358                .await
20359                .unwrap()
20360        );
20361        assert_eq!(
20362            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20363                .await
20364                .unwrap(),
20365            head
20366        );
20367        assert_eq!(
20368            runner
20369                .state
20370                .head_e2e
20371                .as_ref()
20372                .unwrap()
20373                .base_commit
20374                .as_deref(),
20375            Some(base.as_str())
20376        );
20377    }
20378
20379    #[cfg(unix)]
20380    #[tokio::test]
20381    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20382        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20383            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20384            let phases = tmp.path().join("phases");
20385            runner.state.config.verify.e2e = vec![format!(
20386                "echo e2e >> '{}'; {}",
20387                phases.display(),
20388                if e2e_ok {
20389                    "true"
20390                } else {
20391                    "echo new-e2e-failure; false"
20392                }
20393            )];
20394            runner.state.config.verify.gate = vec![format!(
20395                "echo gate >> '{}'; {}",
20396                phases.display(),
20397                if gate_ok {
20398                    "true"
20399                } else {
20400                    "echo new-gate-failure; false"
20401                }
20402            )];
20403            runner.state.save().unwrap();
20404            runner.state = RunState::load(&runner.state.id).unwrap();
20405            runner.sync_to_base().await.unwrap();
20406            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20407            assert_ne!(head, old);
20408            // Reentry after Git updated but before verification was invalidated.
20409            runner.state = RunState::load(&runner.state.id).unwrap();
20410            runner.execute_graph().await.unwrap();
20411            assert_eq!(runner.state.gate_fixes.len(), 1);
20412            assert_eq!(runner.state.reviews.len(), 1);
20413            assert_eq!(runner.state.reviews[0].head, old);
20414            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20415            assert_eq!(runner.state.verification_history.len(), 1);
20416            let history = &runner.state.verification_history[0];
20417            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20418            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20419            assert!(history.archived_at.is_some());
20420            assert_eq!(history.fixes_spent, Some(1));
20421            assert_eq!(history.gate[0].output_tail, "old failure");
20422            let archive_events: Vec<_> = runner
20423                .state
20424                .events
20425                .iter()
20426                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20427                .collect();
20428            assert_eq!(archive_events.len(), 1);
20429            assert!(archive_events[0].message.contains(&short(&old)));
20430            assert!(archive_events[0].message.contains(&short(&head)));
20431            assert!(
20432                archive_events[0]
20433                    .message
20434                    .contains("1 gate-fix round(s) already spent stay spent")
20435            );
20436            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20437            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20438            if e2e_ok {
20439                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20440                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20441            } else {
20442                assert!(!runner.state.gate_ran);
20443            }
20444            assert_eq!(
20445                runner.state.status,
20446                if e2e_ok && gate_ok {
20447                    RunStatus::Ready
20448                } else {
20449                    RunStatus::Blocked
20450                }
20451            );
20452            if !e2e_ok || !gate_ok {
20453                let cause = runner.state.verification_blocking_cause().unwrap();
20454                assert!(cause.contains(&head));
20455                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20456                // A later successful progress event must not become the cause.
20457                runner.state.event("land", "rebased successfully");
20458                let notice = crate::notices::run_ended(&runner.state).unwrap();
20459                assert!(!format!("{notice:?}").contains("rebased successfully"));
20460                assert!(runner.state.merge.is_none());
20461            }
20462            let before = std::fs::read_to_string(&phases).unwrap();
20463            runner.state.save().unwrap();
20464            runner.state = RunState::load(&runner.state.id).unwrap();
20465            runner.review_loop().await.unwrap();
20466            runner.gate().await.unwrap();
20467            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20468            assert_eq!(runner.state.verification_history.len(), 1);
20469            let history = &runner.state.verification_history[0];
20470            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20471            assert!(history.archived_at.is_some());
20472            assert_eq!(history.fixes_spent, Some(1));
20473        }
20474    }
20475
20476    #[cfg(unix)]
20477    #[tokio::test]
20478    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20479        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20480        let marker = tmp.path().join("gate-ran");
20481        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20482        runner.review_loop().await.unwrap();
20483        runner.gate().await.unwrap();
20484        assert_eq!(runner.state.status, RunStatus::Blocked);
20485        assert!(!marker.exists());
20486        assert!(runner.state.verification_history.is_empty());
20487        runner.state.gate_head = None;
20488        runner.gate().await.unwrap();
20489        assert!(marker.exists());
20490        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20491        assert_eq!(runner.state.verification_history.len(), 1);
20492        assert_eq!(runner.state.gate_fixes.len(), 1);
20493    }
20494
20495    #[cfg(unix)]
20496    #[tokio::test]
20497    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20498        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20499        runner.sync_to_base().await.unwrap();
20500        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20501        runner.state.reconcile_verification_head(&head);
20502        // Both crash-before-command and resource wait are unresolved evidence.
20503        for outcomes in [
20504            Vec::new(),
20505            vec![CommandOutcome {
20506                command: "true".into(),
20507                code: None,
20508                output_tail: "cache unavailable".into(),
20509                duration_ms: 0,
20510                resource_blocked: true,
20511                ..Default::default()
20512            }],
20513        ] {
20514            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20515                head.clone(),
20516                false,
20517                outcomes,
20518            ));
20519            runner.state.gate_ran = false;
20520            runner.state.gate.clear();
20521            runner.state.save().unwrap();
20522            runner.state = RunState::load(&runner.state.id).unwrap();
20523            runner.merge().await.unwrap();
20524            assert!(runner.state.merge.is_none());
20525            runner.review_loop().await.unwrap();
20526            runner.gate().await.unwrap();
20527            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20528            assert!(runner.state.gate_allows_progress());
20529            assert_eq!(runner.state.gate_fixes.len(), 1);
20530            assert!(runner.state.merge.is_none());
20531        }
20532        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20533        git::git(
20534            &runner.state.repo,
20535            &["commit", "--allow-empty", "-m", "external update"],
20536        )
20537        .await
20538        .unwrap();
20539        runner.merge().await.unwrap();
20540        assert!(runner.state.merge.is_none());
20541        assert_eq!(runner.state.status, RunStatus::Blocked);
20542    }
20543
20544    #[cfg(unix)]
20545    #[tokio::test]
20546    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20547        for waiting_on_gate in [false, true] {
20548            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20549            runner.sync_to_base().await.unwrap();
20550            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20551            runner.state.reconcile_verification_head(&head);
20552            if waiting_on_gate {
20553                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20554                    head.clone(),
20555                    true,
20556                    Vec::new(),
20557                ));
20558            }
20559            let cache = tmp.path().join("cache");
20560            runner.state.config.verify.e2e =
20561                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20562            runner.state.config.verify.gate = vec!["true".into()];
20563            runner.state.config.graph.timeout_resource_wait = 1;
20564            let owner =
20565                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20566            let guard =
20567                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20568                    crate::cache::AcquireOutcome::Acquired(g) => g,
20569                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20570                };
20571            runner.review_loop().await.unwrap();
20572            runner.gate().await.unwrap();
20573            assert!(!runner.state.gate_ran);
20574            assert_eq!(runner.state.gate_fixes.len(), 1);
20575            assert!(runner.state.resource_block.is_some());
20576            runner.merge().await.unwrap();
20577            assert!(runner.state.merge.is_none());
20578            drop(guard);
20579            runner.state = RunState::load(&runner.state.id).unwrap();
20580            // The driver clears the previous pass's resource stop on resume.
20581            runner.state.resource_block = None;
20582            runner.review_loop().await.unwrap();
20583            runner.gate().await.unwrap();
20584            assert!(runner.state.gate_allows_progress());
20585            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20586            assert_eq!(runner.state.gate_fixes.len(), 1);
20587        }
20588    }
20589
20590    #[cfg(unix)]
20591    #[tokio::test]
20592    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20593        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20594        runner.sync_to_base().await.unwrap();
20595        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20596        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20597        // Verification passes before pre_gate and fails on the mechanically changed head.
20598        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20599        runner.review_loop().await.unwrap();
20600        runner.gate().await.unwrap();
20601        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20602        assert_ne!(before, after);
20603        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20604        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20605        assert!(!runner.state.gate_allows_progress());
20606        runner.merge().await.unwrap();
20607        assert!(runner.state.merge.is_none());
20608        assert!(
20609            runner
20610                .state
20611                .verification_history
20612                .iter()
20613                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20614        );
20615
20616        // An incomplete review is still an independent hold on a changed head.
20617        runner.state.reviews[0].clean = false;
20618        runner.state.reviews[0].answered = 0;
20619        runner.state.config.verify.e2e = vec!["true".into()];
20620        runner.review_loop().await.unwrap();
20621        runner.gate().await.unwrap();
20622        runner.merge().await.unwrap();
20623        assert_eq!(runner.state.status, RunStatus::Blocked);
20624        assert!(runner.state.merge.is_none());
20625        assert!(
20626            runner
20627                .state
20628                .verification_blocking_cause()
20629                .unwrap()
20630                .contains("review blocked")
20631        );
20632    }
20633
20634    #[cfg(unix)]
20635    #[tokio::test]
20636    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20637        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20638        runner.state.gate_head = None;
20639        runner.state.config.verify.gate =
20640            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20641        runner.review_loop().await.unwrap();
20642        runner.gate().await.unwrap();
20643        assert_ne!(
20644            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20645            old
20646        );
20647        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20648        assert!(!runner.state.gate_allows_progress());
20649        assert_eq!(runner.state.status, RunStatus::Blocked);
20650        runner.merge().await.unwrap();
20651        assert!(runner.state.merge.is_none());
20652    }
20653
20654    #[cfg(unix)]
20655    #[tokio::test]
20656    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20657        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20658        let mut old_review = review_round(true, 0, 1, 1, false, true);
20659        old_review.head = head.clone();
20660        old_review.verified_head = Some(head.clone());
20661        runner.state.reviews = vec![old_review];
20662        runner.state.gate = vec![CommandOutcome {
20663            command: "old gate".into(),
20664            code: None,
20665            output_tail: "timed out after 2400s".into(),
20666            duration_ms: 2_400_000,
20667            resource_blocked: false,
20668            ..Default::default()
20669        }];
20670        runner.state.gate_ran = true;
20671        runner.state.gate_head = Some(head.clone());
20672        runner.state.land_approval = Some(crate::run::LandApproval {
20673            question: "old-head-approval".into(),
20674            head: head.clone(),
20675        });
20676        runner.state.authorize_base_sync(&task).unwrap();
20677        runner.sync_to_base().await.unwrap();
20678        assert!(!runner.state.base_sync_blocked());
20679        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20680        assert_ne!(head, fresh);
20681        assert_eq!(runner.state.reviews.len(), 1);
20682        assert!(!runner.state.gate_ran);
20683        let saved = &runner.state.base_sync_recovery.authorizations[0];
20684        assert_eq!(saved.reviews[0].head, head);
20685        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20686        assert!(saved.gate_ran);
20687        assert!(!saved.gate[0].ok());
20688        runner.review_loop().await.unwrap();
20689        runner.gate().await.unwrap();
20690        assert_eq!(runner.state.reviews[0].head, head);
20691        assert_eq!(
20692            runner.state.reviews[0].verified_head.as_deref(),
20693            Some(head.as_str())
20694        );
20695        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20696        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20697        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20698        assert!(runner.state.gate_ran);
20699        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20700        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20701        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20702        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20703        assert_eq!(
20704            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20705            "retained change"
20706        );
20707    }
20708
20709    #[cfg(unix)]
20710    #[tokio::test]
20711    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20712        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20713        let queue = crate::queue::Queue::open();
20714        let mut owner = queue.get(&task).unwrap();
20715        owner.release_operator("test-resume", None);
20716        queue.put(&mut owner).unwrap();
20717        let generation = owner.resumption.as_ref().unwrap().generation;
20718        runner.state.task_instruction = Some(owner.instruction.clone());
20719        runner.state.driver_exited = true;
20720        runner.state.save().unwrap();
20721        let home = crate::run::home();
20722        let _claim = queue.claim(&task).unwrap();
20723        owner.resumption.as_mut().unwrap().at =
20724            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20725        queue.put(&mut owner).unwrap();
20726        assert!(
20727            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20728                .await
20729                .is_err(),
20730            "an approval from before the stop grants nothing"
20731        );
20732        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20733        queue.put(&mut owner).unwrap();
20734        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20735            .await
20736            .unwrap();
20737        assert!(
20738            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20739                .await
20740                .is_err()
20741        );
20742        runner.state = RunState::load(&runner.state.id).unwrap();
20743        assert_eq!(
20744            runner.state.base_sync_recovery.authorizations[0].generation,
20745            Some(generation)
20746        );
20747        runner.sync_to_base().await.unwrap();
20748        let repo = runner.state.repo.clone();
20749        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20750        git::git(&repo, &["checkout", "main"]).await.unwrap();
20751        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20752        git::git(&repo, &["add", "."]).await.unwrap();
20753        git::git(&repo, &["commit", "-m", "move base again"])
20754            .await
20755            .unwrap();
20756        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20757        git::git(&repo, &["checkout", "fix/retained"])
20758            .await
20759            .unwrap();
20760        runner.sync_to_base().await.unwrap();
20761        assert!(!runner.state.base_sync_blocked());
20762        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20763        assert_eq!(runner.state.base_episode_used(), 2);
20764        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20765        assert_ne!(fresh, head);
20766        assert!(!runner.state.base_recovery_pending());
20767        // Even replaying the generation with a later timestamp grants nothing.
20768        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20769        queue.put(&mut owner).unwrap();
20770        assert!(
20771            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20772                .await
20773                .is_err()
20774        );
20775        runner.state = RunState::load(&runner.state.id).unwrap();
20776        runner.sync_to_base().await.unwrap();
20777        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20778        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20779        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20780    }
20781
20782    #[cfg(unix)]
20783    #[tokio::test]
20784    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20785        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20786        runner.state.base_sync = None;
20787        runner.state.status = RunStatus::Blocked;
20788        let mut second = runner.state.candidates[0].clone();
20789        second.label = 'B';
20790        runner.state.candidates.push(second);
20791        assert!(runner.state.votes.is_empty());
20792        assert!(runner.state.deliberation.is_empty());
20793        runner.deliberate().await.unwrap();
20794        runner.vote().await.unwrap();
20795        assert_eq!(runner.state.status, RunStatus::Blocked);
20796        assert!(runner.state.votes.is_empty());
20797        assert!(runner.state.deliberation.is_empty());
20798    }
20799
20800    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20801    /// reads nothing else off it.
20802    fn runner_at(status: RunStatus) -> Runner {
20803        let mut state = RunState::new(
20804            PathBuf::from("/nonexistent/repo"),
20805            "main".to_owned(),
20806            "deadbeef".to_owned(),
20807            "task".to_owned(),
20808            Config::default(),
20809        );
20810        // These fixtures test execution flow, independent of host disk capacity.
20811        state.config.disk.min_free_bytes = 0;
20812        // These fixtures share one home and save concurrently. Short clock
20813        // IDs can collide, making an ownership test read another test's run.
20814        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20815        state.id = format!(
20816            "20000101-000000-{:04x}",
20817            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20818        );
20819        state.status = status;
20820        Runner {
20821            state,
20822            roles: ResolvedRoles {
20823                implementers: Vec::new(),
20824                judges: Vec::new(),
20825                reviewers: Vec::new(),
20826                fixer: None,
20827                conductor: conductor(),
20828                implementer_roster: Vec::new(),
20829                judge_roster: Vec::new(),
20830                reviewer_roster: Vec::new(),
20831            },
20832            sem: Arc::new(Semaphore::new(1)),
20833            pause: Pause::new(),
20834            interrupt: Pause::new(),
20835        }
20836    }
20837
20838    #[tokio::test]
20839    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20840        crate::run::pin_test_home();
20841        let home = crate::run::home();
20842        let mut runner = runner_at(RunStatus::Ready);
20843        runner.state.driver_exited = true;
20844        runner.state.save().unwrap();
20845        let id = runner.state.id.clone();
20846        let path = runner.state.dir().join("run.json");
20847        let ids = ["R1-1-1".into()];
20848        let lease = crate::driver::maintenance(&home, &id).unwrap();
20849        for (guard, expected) in [
20850            (Some(lease), "currently being worked on"),
20851            (None, "ownership is being updated"),
20852        ] {
20853            let owner = if guard.is_none() {
20854                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20855            } else {
20856                None
20857            };
20858            let before = std::fs::read(&path).unwrap();
20859            let err = runner
20860                .fix_selected(&ids, "ownership conflict", false)
20861                .await
20862                .unwrap_err();
20863            assert!(format!("{err:#}").contains(expected), "{err:#}");
20864            assert_eq!(std::fs::read(&path).unwrap(), before);
20865            assert!(!runner.state.dir().join("fix.lock").exists());
20866            drop(owner);
20867            drop(guard);
20868        }
20869        let mut disk = RunState::load(&id).unwrap();
20870        disk.driver_exited = false;
20871        disk.driver_pid = Some(std::process::id());
20872        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20873        disk.save().unwrap();
20874        assert_eq!(
20875            disk.liveness_under(&home, false),
20876            crate::run::Liveness::Live
20877        );
20878        let before = std::fs::read(&path).unwrap();
20879        let err = runner
20880            .fix_selected(&ids, "live driver", false)
20881            .await
20882            .unwrap_err();
20883        assert!(
20884            err.to_string().contains("currently being worked on"),
20885            "{err:#}"
20886        );
20887        assert_eq!(std::fs::read(&path).unwrap(), before);
20888        assert!(!runner.state.dir().join("fix.lock").exists());
20889        disk.driver_exited = true;
20890        disk.driver_pid = None;
20891        disk.driver_started_at = None;
20892        disk.status = RunStatus::Reviewing;
20893        disk.save().unwrap();
20894        let before = std::fs::read(&path).unwrap();
20895        let err = runner
20896            .fix_selected(&ids, "stale state", false)
20897            .await
20898            .unwrap_err();
20899        assert!(
20900            err.to_string().contains("run changed since it was loaded"),
20901            "{err:#}"
20902        );
20903        assert_eq!(std::fs::read(&path).unwrap(), before);
20904        assert!(!runner.state.dir().join("fix.lock").exists());
20905        assert!(runner.state.operator_fixes.is_empty());
20906    }
20907
20908    #[tokio::test]
20909    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20910        use std::future::Future;
20911        use std::task::Poll;
20912
20913        crate::run::pin_test_home();
20914        let home = crate::run::home();
20915        let repo = tempfile::tempdir().unwrap();
20916        let mut runner = runner_at(RunStatus::Ready);
20917        runner.state.repo = repo.path().to_path_buf();
20918        runner.state.driver_exited = true;
20919        runner.state.candidates.push(Candidate {
20920            index: 0,
20921            label: 'A',
20922            agent: "mock".into(),
20923            branch: "magi/test/A".into(),
20924            worktree: repo.path().join("wt"),
20925            summary: String::new(),
20926            stat: String::new(),
20927            files: 0,
20928            commits: 0,
20929            empty: false,
20930            failed: None,
20931            verified_noop: None,
20932            duration_ms: 0,
20933            folded: false,
20934        });
20935        runner.state.tally = Some(Tally {
20936            first_choice: BTreeMap::from([('A', 1)]),
20937            borda: BTreeMap::new(),
20938            winner: 'A',
20939            rankings: 1,
20940            unanimous_initial: true,
20941            deliberated: false,
20942            changed_votes: 0,
20943            unanimous_final: true,
20944            tie_break: None,
20945            judges: 1,
20946            present: 1,
20947            quorum: 1,
20948            met_quorum: true,
20949            uncontested: None,
20950        });
20951        runner.state.save().unwrap();
20952        let id = runner.state.id.clone();
20953        let dir = runner.state.dir();
20954        let before = std::fs::read(dir.join("run.json")).unwrap();
20955        let ids = ["R1-1-1".into()];
20956        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20957        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20958            Poll::Pending => Poll::Ready(()),
20959            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20960        })
20961        .await;
20962        assert!(FixClaim::acquire(&dir).is_err());
20963        assert!(crate::driver::maintenance(&home, &id).is_err());
20964        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20965        drop(fix);
20966        assert!(FixClaim::acquire(&dir).is_ok());
20967        assert!(crate::driver::maintenance(&home, &id).is_ok());
20968        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20969    }
20970
20971    #[tokio::test]
20972    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20973        crate::run::pin_test_home();
20974        let temp = tempfile::tempdir().unwrap();
20975        let root = temp.path().canonicalize().unwrap();
20976        let repo = root.join("repo");
20977        std::fs::create_dir(&repo).unwrap();
20978        init_repo(&repo);
20979        git::git(&repo, &["config", "core.autocrlf", "false"])
20980            .await
20981            .unwrap();
20982        let mut runner = runner_at(RunStatus::Blocked);
20983        runner.state.repo = repo.clone();
20984        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20985        runner.state.config.agents = vec![conductor()];
20986        runner.state.config.graph.selected_implementer = Some("conductor".into());
20987        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20988        let (shell, command, setup_output) = if cfg!(windows) {
20989            (
20990                vec!["cmd".into(), "/C".into()],
20991                "echo ready>seat-ready",
20992                "ready\r\n",
20993            )
20994        } else {
20995            (
20996                vec!["sh".into(), "-c".into()],
20997                "printf ready > seat-ready",
20998                "ready",
20999            )
21000        };
21001        runner.state.config.verify.shell = Some(shell);
21002        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
21003            run: Some(command.into()),
21004            ..Default::default()
21005        }];
21006        runner.state.save().unwrap();
21007        let path = runner.state.worktree_root().join("judge-1");
21008        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
21009            .await
21010            .unwrap();
21011        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
21012        git::git(&path, &["add", "."]).await.unwrap();
21013        let tree = git::git(&path, &["write-tree"]).await.unwrap();
21014        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
21015            .await
21016            .unwrap();
21017        git::git(&path, &["checkout", "--detach", &head])
21018            .await
21019            .unwrap();
21020        let evidence = crate::fold_evidence::snapshot(
21021            &runner.state,
21022            &crate::run::home().canonicalize().unwrap(),
21023            &head,
21024            64 * 1024 * 1024,
21025        )
21026        .await
21027        .unwrap();
21028        let mut contents = BTreeMap::new();
21029        contents.insert(
21030            repo.join("logs/HEAD"),
21031            format!("{head} {head} fixture\n").into_bytes(),
21032        );
21033        let record = serde_json::json!({
21034            "version":1, "run":runner.state.id, "source":path, "head":head,
21035            "evidence":evidence, "admin":{}, "admin_contents":contents,
21036            "history":{head.clone():evidence}, "phase":"evicted"
21037        });
21038        std::fs::write(
21039            runner.state.dir().join("artifacts/eviction-judge-1.json"),
21040            serde_json::to_vec(&record).unwrap(),
21041        )
21042        .unwrap();
21043        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
21044        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
21045            .await
21046            .unwrap();
21047        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
21048        assert!(
21049            !git::git_raw(&repo, &["cat-file", "-e", &head])
21050                .await
21051                .unwrap()
21052                .ok()
21053        );
21054        let mut resumed = Runner::resume(&runner.state.id).unwrap();
21055        let error = resumed.execute().await.unwrap_err();
21056        assert!(
21057            error
21058                .to_string()
21059                .contains("selected implementation is held"),
21060            "{error:#}"
21061        );
21062        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
21063        assert_eq!(
21064            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
21065            setup_output
21066        );
21067        assert_eq!(
21068            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
21069            "unrelated seat"
21070        );
21071        let error = resumed.execute().await.unwrap_err();
21072        assert!(
21073            error
21074                .to_string()
21075                .contains("selected implementation is held"),
21076            "{error:#}"
21077        );
21078        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
21079        git::git(&path, &["add", "."]).await.unwrap();
21080        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
21081        let next = git::git(
21082            &path,
21083            &[
21084                "commit-tree",
21085                &next_tree,
21086                "-p",
21087                &head,
21088                "-m",
21089                "next review checkpoint",
21090            ],
21091        )
21092        .await
21093        .unwrap();
21094        git::git(&path, &["checkout", "--detach", &next])
21095            .await
21096            .unwrap();
21097        resumed.state.reviews.push(
21098            serde_json::from_value(serde_json::json!({
21099                "round":1, "head":next, "reviews":[]
21100            }))
21101            .unwrap(),
21102        );
21103        resumed.state.save().unwrap();
21104        let error = resumed.execute().await.unwrap_err();
21105        assert!(
21106            error
21107                .to_string()
21108                .contains("selected implementation is held"),
21109            "{error:#}"
21110        );
21111        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
21112    }
21113
21114    #[tokio::test]
21115    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
21116        crate::run::pin_test_home();
21117        let mut runner = runner_at(RunStatus::Gating);
21118        runner.state.save().unwrap();
21119        let id = runner.state.id.clone();
21120        let passes = runner.state.passes.len();
21121        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21122        let mut claiming = Box::pin(runner.claim_driver(None));
21123        std::future::poll_fn(|cx| {
21124            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
21125            std::task::Poll::Ready(())
21126        })
21127        .await;
21128        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
21129        drop(owner);
21130        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
21131            .await
21132            .unwrap()
21133            .unwrap();
21134        assert_eq!(execution.runner.state.passes.len(), passes + 1);
21135        assert!(execution.runner.state.resource_block.is_none());
21136        assert_eq!(
21137            execution.runner.state.liveness(false),
21138            crate::run::Liveness::Live
21139        );
21140        drop(execution);
21141        assert!(RunState::load(&id).unwrap().driver_exited);
21142    }
21143
21144    #[tokio::test]
21145    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
21146        crate::run::pin_test_home();
21147        let mut runner = runner_at(RunStatus::Gating);
21148        runner.state.save().unwrap();
21149        // run.json can commit, but the subsequent lease metadata write fails.
21150        // Cleanup must run after releasing the short ownership lock.
21151        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
21152        assert!(runner.claim_driver(None).await.is_err());
21153        assert!(runner.state.driver_exited);
21154        assert_eq!(runner.state.driver_pid, None);
21155        let disk = RunState::load(&runner.state.id).unwrap();
21156        assert!(disk.driver_exited);
21157        assert_eq!(disk.driver_pid, None);
21158        assert_eq!(disk.status, RunStatus::Gating);
21159    }
21160
21161    #[tokio::test]
21162    async fn an_early_graph_error_releases_its_driver() {
21163        crate::run::pin_test_home();
21164        let mut runner = runner_at(RunStatus::Blocked);
21165        runner.state.config.graph.selected_implementer = Some("selected".into());
21166        runner.state.save().unwrap();
21167        assert!(runner.execute().await.is_err());
21168        let disk = RunState::load(&runner.state.id).unwrap();
21169        assert!(disk.driver_exited);
21170        assert_eq!(disk.driver_pid, None);
21171        assert_eq!(disk.status, RunStatus::Blocked);
21172    }
21173
21174    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
21175        crate::run::MergeRepair {
21176            question: "repair-question".into(),
21177            head: "old-head".into(),
21178            pr: "https://github.com/o/r/pull/42".into(),
21179            reviews: vec![review_round(false, 1, 1, 1, false, true)],
21180            gate: vec![outcome(Some(0), false)],
21181            gate_head: Some("old-head".into()),
21182            gate_fixes: Vec::new(),
21183            pre_gate: Vec::new(),
21184            phase,
21185            failure: None,
21186        }
21187    }
21188
21189    #[tokio::test]
21190    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
21191        crate::run::pin_test_home();
21192        let mut runner = runner_at(RunStatus::Landing);
21193        runner.state.merge_repairs.push(merge_repair_request(
21194            crate::run::MergeRepairPhase::Requested,
21195        ));
21196        runner.state.save().unwrap();
21197        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
21198        assert!(
21199            runner
21200                .execute()
21201                .await
21202                .unwrap_err()
21203                .to_string()
21204                .contains("already running")
21205        );
21206        assert_eq!(
21207            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21208            crate::run::MergeRepairPhase::Requested
21209        );
21210        drop(claim);
21211        let mut disk = runner.state.clone();
21212        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
21213        disk.save().unwrap();
21214        assert!(
21215            runner
21216                .execute()
21217                .await
21218                .unwrap_err()
21219                .to_string()
21220                .contains("decision changed")
21221        );
21222        assert_eq!(
21223            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21224            crate::run::MergeRepairPhase::Complete
21225        );
21226    }
21227
21228    #[test]
21229    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
21230        crate::run::pin_test_home();
21231        let mut runner = runner_at(RunStatus::Landing);
21232        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
21233        runner.state.reviews = request.reviews.clone();
21234        runner.state.gate = request.gate.clone();
21235        runner.state.gate_ran = true;
21236        runner.state.land_approval = Some(crate::run::LandApproval {
21237            question: "old".into(),
21238            head: "old-head".into(),
21239        });
21240        runner.state.merge_repairs.push(request);
21241        runner.begin_merge_repair_review(0).unwrap();
21242        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
21243        assert!(!runner.state.gate_status().ok());
21244        assert!(runner.state.land_approval.is_none());
21245        let disk = RunState::load(&runner.state.id).unwrap();
21246        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21247        assert!(disk.merge_repairs[0].gate[0].ok());
21248        assert_eq!(
21249            disk.merge_repairs[0].phase,
21250            crate::run::MergeRepairPhase::Reviewing
21251        );
21252        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21253        assert!(disk.reviews.is_empty());
21254    }
21255
21256    #[tokio::test]
21257    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21258        crate::run::pin_test_home();
21259        for phase in [
21260            crate::run::MergeRepairPhase::Fixing,
21261            crate::run::MergeRepairPhase::Requested,
21262        ] {
21263            let mut runner = runner_at(RunStatus::Landing);
21264            runner.state.config.graph.land_rounds = 0;
21265            runner.state.merge_repairs.push(merge_repair_request(phase));
21266            runner.state.save().unwrap();
21267            assert!(!runner.repair_merge_review().await.unwrap());
21268            assert_eq!(runner.state.status, RunStatus::Blocked);
21269            assert_eq!(
21270                runner.state.merge_repairs[0].phase,
21271                crate::run::MergeRepairPhase::Failed
21272            );
21273            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21274            assert!(
21275                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21276                    "interrupted"
21277                } else {
21278                    "budget exhausted"
21279                })
21280            );
21281            assert!(runner.state.merge.is_none());
21282        }
21283    }
21284
21285    #[tokio::test]
21286    async fn failed_instruction_revision_repair_cannot_resume_into_landing() {
21287        crate::run::pin_test_home();
21288        let mut runner = runner_at(RunStatus::Landing);
21289        let old = merge_repair_request(crate::run::MergeRepairPhase::Complete);
21290        runner.state.reviews = old.reviews.clone();
21291        runner.state.gate = old.gate.clone();
21292        runner.state.gate_ran = true;
21293        runner.state.merge = Some(MergeOutcome {
21294            mode: MergeMode::Pr,
21295            ok: true,
21296            detail: old.pr.clone(),
21297            empty: false,
21298        });
21299        runner.state.merge_repairs.push(old.clone());
21300        crate::instruction_revision_control::adopt_into_run(
21301            &mut runner.state,
21302            "cli/revision",
21303            "revision-repair",
21304            "revised task",
21305            1,
21306            &old.head,
21307            &old.pr,
21308        );
21309        runner.hold_merge_repair(1, "fixer failed".into()).unwrap();
21310        runner.execute().await.unwrap();
21311        let saved = RunState::load(&runner.state.id).unwrap();
21312        assert_eq!(saved.status, RunStatus::Blocked);
21313        assert_eq!(
21314            saved.merge_repairs[0].phase,
21315            crate::run::MergeRepairPhase::Complete
21316        );
21317        assert_eq!(
21318            saved.merge_repairs[1].phase,
21319            crate::run::MergeRepairPhase::Failed
21320        );
21321        assert_eq!(
21322            saved.merge_repairs[1].failure.as_deref(),
21323            Some("fixer failed")
21324        );
21325        assert!(saved.land_approval.is_none());
21326        assert!(!saved.gate_ran);
21327        assert_eq!(saved.reviews.len(), 1);
21328        assert!(
21329            saved.events.iter().any(|event| event.node == "repair"
21330                && event.message.contains("normal resume cannot land"))
21331        );
21332        assert!(!saved.events.iter().any(|event| event.node == "land"));
21333    }
21334
21335    /// `park_here` folding in the reason `Pause::park_because` recorded -
21336    /// this is what lets an operator reading a run's events tell an
21337    /// interrupt-driven park from an ordinary shutdown park.
21338    #[test]
21339    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21340        crate::run::pin_test_home();
21341        let mut runner = runner_at(RunStatus::Implementing);
21342        let interrupt = Pause::new();
21343        runner.watch_interrupt(interrupt.clone());
21344
21345        interrupt.park_because("task a1b2 asked to run first");
21346
21347        assert!(runner.park_here().expect("park_here"));
21348        assert!(runner.state.parked);
21349        let last = runner.state.events.last().expect("a park event");
21350        assert_eq!(last.node, "park");
21351        assert!(
21352            last.message.contains("task a1b2 asked to run first"),
21353            "expected the interrupt reason in {:?}",
21354            last.message
21355        );
21356    }
21357
21358    /// The cause is stored on the pass when it parks, and the first cause a
21359    /// shared pause was given is the one that stays.
21360    #[test]
21361    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21362        crate::run::pin_test_home();
21363        let mut runner = runner_at(RunStatus::Implementing);
21364        runner.state.begin_pass();
21365        let shutdown = Pause::new();
21366        runner.on_pause(shutdown.clone());
21367        let upgrade = ParkCause::Upgrade {
21368            from: "0.121.0".to_owned(),
21369            to: Some("0.121.1".to_owned()),
21370        };
21371        shutdown.park_for(upgrade.clone());
21372        shutdown.park_for(ParkCause::Operator);
21373
21374        assert!(runner.park_here().expect("park_here"));
21375        assert_eq!(
21376            runner.state.passes[0].end,
21377            Some(crate::run::PassEnd::Parked { cause: upgrade })
21378        );
21379        let last = runner.state.events.last().expect("a park event");
21380        assert!(last.message.contains("0.121.0"), "{}", last.message);
21381    }
21382
21383    #[tokio::test]
21384    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21385        crate::run::pin_test_home();
21386        let mut runner = runner_at(RunStatus::Reviewing);
21387        runner.state.save().unwrap();
21388        let mut execution = runner.claim_driver(None).await.expect("first execution");
21389        assert_eq!(execution.runner.state.passes.len(), 1);
21390        execution
21391            .driver
21392            .finish(&mut execution.runner.state)
21393            .await
21394            .unwrap();
21395    }
21396
21397    #[tokio::test]
21398    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21399        crate::run::pin_test_home();
21400        let mut runner = runner_at(RunStatus::Reviewing);
21401        runner.state.config.agents = vec![conductor()];
21402        runner.state.config.graph.timeout_resource_wait = 0;
21403        runner.state.save().unwrap();
21404        let id = runner.state.id.clone();
21405        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21406        assert!(runner.claim_driver(None).await.is_err());
21407        drop(owner);
21408        drop(runner);
21409        let mut resumed = Runner::resume(&id).unwrap();
21410        assert_eq!(resumed.state.driver_claimed, Some(false));
21411        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21412        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21413        let mut execution = resumed
21414            .claim_driver(None)
21415            .await
21416            .expect("retry initial claim after reload");
21417        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21418        assert_eq!(execution.runner.state.passes.len(), 1);
21419        execution
21420            .driver
21421            .finish(&mut execution.runner.state)
21422            .await
21423            .unwrap();
21424    }
21425
21426    #[tokio::test]
21427    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21428        crate::run::pin_test_home();
21429        let mut runner = runner_at(RunStatus::Reviewing);
21430        runner.state.config.agents = vec![conductor()];
21431        runner.state.save().unwrap();
21432        let id = runner.state.id.clone();
21433        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21434        let mut resumed = Runner::resume(&id).unwrap();
21435        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21436        assert!(resumed.claim_driver(None).await.is_err());
21437        assert!(RunState::load(&id).unwrap().passes.is_empty());
21438        drop(lease);
21439        let mut execution = resumed.claim_driver(None).await.unwrap();
21440        execution
21441            .driver
21442            .finish(&mut execution.runner.state)
21443            .await
21444            .unwrap();
21445    }
21446
21447    #[tokio::test]
21448    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21449        crate::run::pin_test_home();
21450        let mut runner = runner_at(RunStatus::Reviewing);
21451        let state = &mut runner.state;
21452        state.config.agents = vec![conductor()];
21453        state.driver_claimed = None;
21454        state.driver_pid = Some(std::process::id());
21455        state.driver_started_at = None;
21456        state.begin_pass();
21457        state.save().unwrap();
21458        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21459        std::fs::write(
21460            state.dir().join("driver.json"),
21461            serde_json::to_vec(&serde_json::json!({
21462                "pid": state.driver_pid, "started_at": null,
21463                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21464            }))
21465            .unwrap(),
21466        )
21467        .unwrap();
21468        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21469        drop(lease);
21470        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21471        let mut resumed = Runner::resume(&state.id).unwrap();
21472        assert!(!resumed.state.driver_exited);
21473        let mut execution = resumed
21474            .claim_driver(None)
21475            .await
21476            .expect("lease proves previous execution ended");
21477        assert_eq!(execution.runner.state.passes.len(), 2);
21478        execution
21479            .driver
21480            .finish(&mut execution.runner.state)
21481            .await
21482            .unwrap();
21483    }
21484
21485    #[tokio::test]
21486    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21487        crate::run::pin_test_home();
21488        let mut runner = runner_at(RunStatus::Reviewing);
21489        let mut json = serde_json::to_value(&runner.state).unwrap();
21490        json.as_object_mut().unwrap().remove("driver_claimed");
21491        runner.state = serde_json::from_value(json).unwrap();
21492        assert_eq!(runner.state.driver_claimed, None);
21493        runner.state.save().unwrap();
21494        let mut execution = runner
21495            .claim_driver(None)
21496            .await
21497            .expect("the execution lease, not a missing marker, excludes a second driver");
21498        assert_eq!(execution.runner.state.passes.len(), 1);
21499        execution
21500            .driver
21501            .finish(&mut execution.runner.state)
21502            .await
21503            .unwrap();
21504    }
21505
21506    #[tokio::test]
21507    async fn driver_admission_refuses_a_proven_live_driver() {
21508        crate::run::pin_test_home();
21509        let mut runner = runner_at(RunStatus::Reviewing);
21510        let pid = std::process::id();
21511        runner.state.driver_pid = Some(pid);
21512        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21513        assert!(runner.state.driver_started_at.is_some());
21514        runner.state.save().unwrap();
21515        let error = runner
21516            .claim_driver(None)
21517            .await
21518            .err()
21519            .expect("a live driver must refuse");
21520        let message = error.to_string();
21521        assert!(
21522            message.starts_with("run already has a live driver: "),
21523            "{message}"
21524        );
21525        assert!(message.contains(&format!("pid={pid}")), "{message}");
21526        assert!(
21527            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21528            "{message}"
21529        );
21530        let saved = RunState::load(&runner.state.id).unwrap();
21531        assert_eq!(saved.driver_pid, Some(pid));
21532        assert_eq!(saved.status, RunStatus::Reviewing);
21533        assert!(saved.passes.is_empty());
21534    }
21535
21536    #[tokio::test]
21537    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21538        crate::run::pin_test_home();
21539        let home = crate::run::home();
21540        let mut runner = runner_at(RunStatus::Reviewing);
21541        runner.state.driver_exited = true;
21542        runner.state.driver_pid = None;
21543        runner.state.driver_started_at = None;
21544        runner.state.save().unwrap();
21545
21546        let queue = crate::queue::Queue::at(home.join("queue"));
21547        let mut task = crate::queue::Task::new(
21548            "task".into(),
21549            "task".into(),
21550            runner.state.repo.clone(),
21551            crate::queue::Source::Human,
21552        );
21553        task.runs.push(runner.state.id.clone());
21554        queue.put(&mut task).unwrap();
21555        let payload = serde_json::json!({
21556            "queue": home.join("queue"),
21557            "task": task.id,
21558            "opts": crate::daemon::Opts::default(),
21559            "standalone": false,
21560        });
21561        let (job, lease) =
21562            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21563
21564        let error = runner
21565            .claim_driver(None)
21566            .await
21567            .err()
21568            .expect("another active worker claim must refuse");
21569        let message = error.to_string();
21570        assert!(
21571            message.starts_with("run already has a live driver: worker claim"),
21572            "{message}"
21573        );
21574        assert!(message.contains(&job.id), "{message}");
21575        assert!(message.contains("status=running"), "{message}");
21576        assert!(message.contains("live.lock held"), "{message}");
21577
21578        drop(lease);
21579        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21580    }
21581
21582    #[test]
21583    fn parking_resource_halt_persists_the_pass_once() {
21584        crate::run::pin_test_home();
21585        let mut runner = runner_at(RunStatus::Reviewing);
21586        runner.state.begin_pass();
21587        runner.state.resource_block = Some(crate::run::ResourceBlock {
21588            node: "fix".into(),
21589            kind: "shared build cache".into(),
21590            detail: "cancelled".into(),
21591            at: Timestamp::now(),
21592            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21593        });
21594        let cause = ParkCause::Upgrade {
21595            from: "old".into(),
21596            to: Some("new".into()),
21597        };
21598        runner.pause.park_for(cause.clone());
21599        // Both direct fixer exits and graph resource boundaries must complete
21600        // parking, rather than returning a stale Reviewing record.
21601        runner.stop_for_resource().unwrap();
21602        assert!(runner.resource_halt().unwrap());
21603        assert!(runner.park_here().unwrap());
21604        let saved = RunState::load(&runner.state.id).unwrap();
21605        assert!(saved.parked);
21606        assert_eq!(saved.status, RunStatus::Reviewing);
21607        assert!(saved.passes[0].ended_at.is_some());
21608        assert_eq!(
21609            saved.passes[0].end,
21610            Some(crate::run::PassEnd::Parked {
21611                cause: cause.clone()
21612            })
21613        );
21614        assert_eq!(
21615            saved.resource_block.unwrap().cause,
21616            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21617        );
21618        assert_eq!(
21619            saved
21620                .events
21621                .iter()
21622                .filter(|event| event.node == "park")
21623                .count(),
21624            1
21625        );
21626    }
21627
21628    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21629    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21630    /// cleared) must not make a *different* run - one only watching its own,
21631    /// unshared interrupt `Pause` - see itself as parked. If a future change
21632    /// ever collapsed these back into one handle, the interrupt scheduler
21633    /// would park every run for the rest of the daemon's life, not just the
21634    /// one it meant to interrupt.
21635    #[test]
21636    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21637        crate::run::pin_test_home();
21638        let mut runner = runner_at(RunStatus::Implementing);
21639        let shutdown = Pause::new();
21640        runner.on_pause(shutdown.clone());
21641        let interrupt = Pause::new();
21642        runner.watch_interrupt(interrupt.clone());
21643
21644        // Nobody has asked for anything yet.
21645        assert!(!runner.park_here().expect("park_here"));
21646        assert!(!runner.state.parked);
21647
21648        // Only the interrupt handle fires; the shutdown handle stays clear.
21649        interrupt.park_because("test");
21650        assert!(!shutdown.parked());
21651        assert!(runner.park_here().expect("park_here"));
21652    }
21653
21654    /// The property every prior attempt at this feature failed to pin down:
21655    /// asking a run to park while one of its nodes has a real, in-flight
21656    /// async operation running (an agent call, in production) must not cut
21657    /// that operation short. `park_here` is only ever consulted *between*
21658    /// `execute`'s node calls - see its own doc - so nothing inside a node
21659    /// can observe a park request until the node itself returns. This proves
21660    /// that structurally, with real `tokio` concurrency and a channel
21661    /// handshake (never a sleep, which would only prove "usually", not
21662    /// "cannot"): the "node" below reports that it has genuinely started,
21663    /// and only then is the park requested; the node still has to be told to
21664    /// finish before `park_here` is ever called, exactly mirroring every
21665    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21666    /// in `execute`.
21667    #[tokio::test]
21668    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21669        crate::run::pin_test_home();
21670        let mut runner = runner_at(RunStatus::Implementing);
21671        let interrupt = Pause::new();
21672        runner.watch_interrupt(interrupt.clone());
21673
21674        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21675        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21676
21677        // Stands in for one node's in-flight agent call: it proves it has
21678        // genuinely started, then blocks - exactly as a spawned CLI process
21679        // does - until told to finish.
21680        let node = async move {
21681            started_tx.send(()).expect("send started");
21682            finish_rx.await.expect("recv finish");
21683            "node finished"
21684        };
21685
21686        let interrupter = async move {
21687            started_rx.await.expect("recv started");
21688            // The call is now genuinely in flight. Ask it to park.
21689            interrupt.park_because("higher-priority task waiting");
21690            // Nothing the node does can observe this yet - there is no
21691            // check inside it, by construction - so let the executor run
21692            // anything pending and then let the node finish on its own.
21693            tokio::task::yield_now().await;
21694            finish_tx.send(()).expect("send finish");
21695        };
21696
21697        let (node_result, ()) = tokio::join!(node, interrupter);
21698        assert_eq!(
21699            node_result, "node finished",
21700            "the in-flight call ran to completion"
21701        );
21702
21703        // Only now, at the boundary the real `execute` would check right
21704        // after this node, does the park take effect.
21705        assert!(runner.park_here().expect("park_here"));
21706        assert!(runner.state.parked);
21707    }
21708
21709    /// A run parked mid-competition carries every field it had accumulated
21710    /// through the exact same disk round-trip an ordinary resume uses -
21711    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21712    /// Nothing about parking for an interrupt is a special case of that path;
21713    /// this is what proves it rather than assuming it.
21714    #[test]
21715    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21716        crate::run::pin_test_home();
21717        let mut runner = runner_at(RunStatus::Judging);
21718        // `Runner::resume` re-resolves roles from the saved config, which
21719        // refuses an empty roster - give it the same minimal one `conductor`
21720        // itself uses.
21721        runner.state.config.agents = vec![conductor()];
21722        runner.state.candidates = vec![Candidate {
21723            index: 0,
21724            label: 'A',
21725            agent: "alpha".to_owned(),
21726            branch: "magi/x/A".to_owned(),
21727            worktree: PathBuf::from("/nonexistent/worktree"),
21728            summary: "did the thing".to_owned(),
21729            stat: "1 file changed".to_owned(),
21730            files: 1,
21731            commits: 1,
21732            empty: false,
21733            failed: None,
21734            verified_noop: None,
21735            duration_ms: 1234,
21736            folded: false,
21737        }];
21738        let run_id = runner.state.id.clone();
21739
21740        let interrupt = Pause::new();
21741        runner.watch_interrupt(interrupt.clone());
21742        interrupt.park_because("task c3d4 asked to run first");
21743        assert!(runner.park_here().expect("park_here"));
21744
21745        let resumed = Runner::resume(&run_id).expect("resume");
21746        assert_eq!(resumed.state.candidates.len(), 1);
21747        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21748        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21749        assert_eq!(resumed.state.status, runner.state.status);
21750        assert!(
21751            resumed.state.parked,
21752            "still parked until `execute` actually walks the graph again"
21753        );
21754        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21755    }
21756
21757    /// A fresh open question on `run`, stored and handed back for assertions.
21758    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21759        let mut q = ask::Question::new(
21760            run.to_owned(),
21761            "implement".to_owned(),
21762            "impl-A".to_owned(),
21763            "Which storage backend should the cache use?".to_owned(),
21764            String::new(),
21765            vec!["SQLite".to_owned(), "Redis".to_owned()],
21766        );
21767        store.put(&mut q).unwrap();
21768        q
21769    }
21770
21771    #[test]
21772    fn a_failed_runs_open_question_is_abandoned() {
21773        ask_test_home();
21774        let store = ask::Questions::open();
21775        let mut runner = runner_at(RunStatus::Failed);
21776        let run = runner.state.id.clone();
21777        let q = ask_open_question(&store, &run);
21778
21779        runner.settle_questions();
21780
21781        let back = store.get(&q.id).unwrap();
21782        assert!(
21783            !back.status.open(),
21784            "the seat that asked died with the run; nobody is left to read an answer"
21785        );
21786        assert!(
21787            back.detail.contains(&run) && back.detail.contains("failed"),
21788            "the reason names what the run became, not just that it is gone: {}",
21789            back.detail
21790        );
21791    }
21792
21793    #[test]
21794    fn a_merged_runs_open_question_is_abandoned_too() {
21795        ask_test_home();
21796        let store = ask::Questions::open();
21797        // A run that finishes cleanly still leaves nobody to read an answer -
21798        // this is not only a failure-path cleanup.
21799        for status in [RunStatus::Merged, RunStatus::Ready] {
21800            let mut runner = runner_at(status);
21801            let run = runner.state.id.clone();
21802            let q = ask_open_question(&store, &run);
21803
21804            runner.settle_questions();
21805
21806            let back = store.get(&q.id).unwrap();
21807            assert!(
21808                !back.status.open(),
21809                "{status:?} run's question must not outlive the run"
21810            );
21811        }
21812    }
21813
21814    #[test]
21815    fn a_still_resumable_runs_open_question_is_left_alone() {
21816        ask_test_home();
21817        let store = ask::Questions::open();
21818        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21819        // review round and the seat sessions are all still on disk — so a
21820        // question asked mid-round may yet get a real answer from a real
21821        // resume. Sweeping it here would be exactly the failure mode this
21822        // whole feature exists to avoid on the other side.
21823        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21824            let mut runner = runner_at(status);
21825            let run = runner.state.id.clone();
21826            let q = ask_open_question(&store, &run);
21827
21828            runner.settle_questions();
21829
21830            let back = store.get(&q.id).unwrap();
21831            assert!(
21832                back.status.open(),
21833                "{status:?} is still alive; the question must still be waiting"
21834            );
21835        }
21836    }
21837
21838    #[test]
21839    fn settle_questions_never_touches_an_already_answered_question() {
21840        ask_test_home();
21841        let store = ask::Questions::open();
21842        let mut runner = runner_at(RunStatus::Failed);
21843        let run = runner.state.id.clone();
21844        let mut q = ask_open_question(&store, &run);
21845        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21846            .unwrap();
21847        store.put(&mut q).unwrap();
21848
21849        // Called twice, the way a crash-recovered daemon reclaim and the
21850        // graph's own cleanup both can for the same run — `abandon_for_run`
21851        // only ever touches what is still open, so this must be inert both
21852        // times, not merely the second.
21853        runner.settle_questions();
21854        runner.settle_questions();
21855
21856        let back = store.get(&q.id).unwrap();
21857        assert_eq!(
21858            back.status,
21859            ask::QuestionStatus::Answered,
21860            "a real answer is a decision on record, never overwritten by a sweep"
21861        );
21862    }
21863
21864    #[tokio::test]
21865    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21866        let tmp = tempfile::tempdir().unwrap();
21867        let home = tmp.path().join("home");
21868        let repo = tmp.path().join("repo");
21869        std::fs::create_dir(&home).unwrap();
21870        std::fs::create_dir(&repo).unwrap();
21871        init_repo(&repo);
21872
21873        let mut config = Config::default();
21874        config.graph.worktree_root = Some(tmp.path().join("wt"));
21875        config.verify.build_cache = crate::config::BuildCache::Isolated;
21876        let mut state = RunState::new(
21877            repo.clone(),
21878            "main".into(),
21879            "base".into(),
21880            "fold fixture".into(),
21881            config,
21882        );
21883        let root = state.worktree_root();
21884        let mut outputs = Vec::new();
21885        for name in ["idle", "busy"] {
21886            let checkout = root.join(name);
21887            git::worktree_add_detached(&repo, &checkout, "main")
21888                .await
21889                .unwrap();
21890            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21891            let output = target.join("generated");
21892            std::fs::write(&output, name).unwrap();
21893            outputs.push((target, output));
21894        }
21895        let unknown = crate::build_target::root(&home)
21896            .join("00000000-0000-0000-0000-000000000000")
21897            .join("target");
21898        std::fs::create_dir_all(&unknown).unwrap();
21899        let unowned = unknown.join("generated");
21900        std::fs::write(&unowned, "keep").unwrap();
21901        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21902        let crate::cache::AcquireOutcome::Acquired(_lease) =
21903            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21904        else {
21905            panic!("fixture target must be free");
21906        };
21907
21908        state.save_under(&home).unwrap();
21909        fold_run(&mut state, true, &home).await.unwrap();
21910        assert!(!root.exists());
21911        assert!(!outputs[0].1.exists());
21912        assert!(outputs[1].1.is_file());
21913        assert!(unowned.is_file());
21914    }
21915
21916    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21917    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21918    /// without merging, whose winner is still the operator's answer to read.
21919    /// Nothing previously called `fold_run` itself with a real `tally`, so
21920    /// this is the first test to pin down the one distinction the whole
21921    /// automatic-fold feature depends on: the winner's worktree and branch
21922    /// must survive, everything else sharing the run's worktree bay - a
21923    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21924    /// second sweep treats every non-winner directory under the bay alike -
21925    /// must not.
21926    #[tokio::test]
21927    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21928        crate::run::pin_test_home();
21929        let tmp = tempfile::tempdir().expect("tempdir");
21930        let repo = tmp.path().join("repo");
21931        std::fs::create_dir_all(&repo).unwrap();
21932        init_repo(&repo);
21933
21934        let mut config = Config::default();
21935        config.graph.worktree_root = Some(tmp.path().join("wt"));
21936
21937        let mut state = RunState::new(
21938            repo.clone(),
21939            "main".to_owned(),
21940            "deadbeef".to_owned(),
21941            "task".to_owned(),
21942            config,
21943        );
21944        let root = state.worktree_root();
21945        let wt_a = root.join("cand-A");
21946        let wt_b = root.join("cand-B");
21947        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21948            .await
21949            .expect("worktree A");
21950        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21951            .await
21952            .expect("worktree B");
21953
21954        state.candidates = vec![
21955            Candidate {
21956                index: 0,
21957                label: 'A',
21958                agent: "alpha".to_owned(),
21959                branch: "magi/x/A".to_owned(),
21960                worktree: wt_a.clone(),
21961                summary: String::new(),
21962                stat: String::new(),
21963                files: 0,
21964                commits: 0,
21965                empty: false,
21966                failed: None,
21967                verified_noop: None,
21968                duration_ms: 0,
21969                folded: false,
21970            },
21971            Candidate {
21972                index: 1,
21973                label: 'B',
21974                agent: "beta".to_owned(),
21975                branch: "magi/x/B".to_owned(),
21976                worktree: wt_b.clone(),
21977                summary: String::new(),
21978                stat: String::new(),
21979                files: 0,
21980                commits: 0,
21981                empty: false,
21982                failed: None,
21983                verified_noop: None,
21984                duration_ms: 0,
21985                folded: false,
21986            },
21987        ];
21988        state.tally = Some(Tally {
21989            first_choice: BTreeMap::from([('A', 1)]),
21990            borda: BTreeMap::new(),
21991            winner: 'A',
21992            rankings: 1,
21993            unanimous_initial: true,
21994            deliberated: false,
21995            changed_votes: 0,
21996            unanimous_final: true,
21997            tie_break: None,
21998            judges: 1,
21999            present: 1,
22000            quorum: 1,
22001            met_quorum: true,
22002            uncontested: None,
22003        });
22004        state.status = RunStatus::Ready;
22005
22006        state.save_under(&crate::run::home()).unwrap();
22007        fold_run(&mut state, false, &crate::run::home())
22008            .await
22009            .expect("fold_run");
22010
22011        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
22012        assert!(
22013            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22014            "the unmerged winner's branch survives"
22015        );
22016        assert!(
22017            !state.candidates[0].folded,
22018            "the winner is not marked folded"
22019        );
22020
22021        assert!(!wt_b.exists(), "the loser's worktree is removed");
22022        assert!(
22023            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
22024            "the loser's branch is removed"
22025        );
22026        assert!(state.candidates[1].folded, "the loser is marked folded");
22027    }
22028
22029    #[tokio::test]
22030    #[cfg(unix)]
22031    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
22032        use std::os::fd::AsRawFd as _;
22033        use std::time::Duration;
22034
22035        let tmp = tempfile::tempdir().unwrap();
22036        let repo = tmp.path().join("repo");
22037        std::fs::create_dir_all(&repo).unwrap();
22038        init_repo(&repo);
22039        let common = repo.join(".git");
22040        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22041        let home = tmp.path().join("home");
22042        let mut config = Config::default();
22043        config.coordination = crate::config::test_coordination();
22044        config.graph.worktree_root = Some(tmp.path().join("wt"));
22045        config.graph.timeout_resource_wait = 1;
22046        let mut state = RunState::new(
22047            repo.clone(),
22048            "main".into(),
22049            "deadbeef".into(),
22050            "task".into(),
22051            config,
22052        );
22053        let root = state.worktree_root();
22054        let candidate = root.join("cand-A");
22055        let reviewer = root.join("review-1");
22056        let branch = state.branch_for('A');
22057        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22058            .await
22059            .unwrap();
22060        git::worktree_add_detached(&repo, &reviewer, "main")
22061            .await
22062            .unwrap();
22063        git::acquire_worktree_config(&repo).await.unwrap();
22064        state.enabled_worktree_config = true;
22065        state.status = RunStatus::Ready;
22066        state.candidates.push(Candidate {
22067            index: 0,
22068            label: 'A',
22069            agent: "implement".into(),
22070            branch: branch.clone(),
22071            worktree: candidate.clone(),
22072            summary: String::new(),
22073            stat: String::new(),
22074            files: 0,
22075            commits: 0,
22076            empty: false,
22077            failed: None,
22078            verified_noop: None,
22079            duration_ms: 0,
22080            folded: false,
22081        });
22082        state.save_under(&home).unwrap();
22083        let config_before = std::fs::read(common.join("config")).unwrap();
22084        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
22085            .await
22086            .unwrap();
22087        // A separate OS handle bypasses the launcher's local gate, exactly as
22088        // an external updater does, and must still prevent all folding work.
22089        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22090        assert_eq!(
22091            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22092            0
22093        );
22094        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22095        assert!(
22096            tokio::time::timeout(Duration::from_millis(200), &mut fold)
22097                .await
22098                .is_err()
22099        );
22100        assert!(candidate.exists());
22101        assert!(reviewer.exists());
22102        assert!(git::branch_exists(&repo, &branch).await.unwrap());
22103        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22104        assert_eq!(
22105            git::git(&repo, &["worktree", "list", "--porcelain"])
22106                .await
22107                .unwrap(),
22108            worktrees_before
22109        );
22110        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
22111            .await
22112            .unwrap()
22113            .unwrap_err();
22114        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
22115        drop(fold);
22116        assert!(candidate.exists() && reviewer.exists());
22117        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
22118        assert_eq!(
22119            state.resource_block.as_ref().unwrap().kind,
22120            "repository coordination"
22121        );
22122        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
22123        drop(external);
22124        let mut fold = Box::pin(fold_run(&mut state, true, &home));
22125        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
22126            .await
22127            .unwrap()
22128            .unwrap();
22129        drop(fold);
22130        assert!(removed.contains(&branch));
22131        assert!(!root.exists());
22132        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
22133        assert!(state.candidates[0].folded);
22134        assert!(!state.enabled_worktree_config);
22135        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
22136        let enabled = git::git_raw(
22137            &repo,
22138            &["config", "--local", "--get", "extensions.worktreeConfig"],
22139        )
22140        .await
22141        .unwrap();
22142        assert!(!enabled.ok(), "the last config reference was released");
22143    }
22144
22145    /// A handover holds repository coordination and then asks for the
22146    /// predecessor's owner lock; an automatic fold already holds that lock. The
22147    /// fold asks for coordination once and gives way, so the handover's short
22148    /// retry succeeds - waiting for it would leave both waiting for each other.
22149    /// Nothing is changed or saved on the way out and the refusal is `live`;
22150    /// the explicit entry points (`magi fold`) still wait, bounded as before.
22151    #[tokio::test]
22152    #[cfg(unix)]
22153    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
22154        use std::os::fd::AsRawFd as _;
22155        use std::time::Duration;
22156
22157        let tmp = tempfile::tempdir().unwrap();
22158        let repo = tmp.path().join("repo");
22159        std::fs::create_dir_all(&repo).unwrap();
22160        init_repo(&repo);
22161        let common = repo.join(".git");
22162        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22163        let home = tmp.path().join("home");
22164        let mut config = Config::default();
22165        config.coordination = crate::config::test_coordination();
22166        config.graph.worktree_root = Some(tmp.path().join("wt"));
22167        config.graph.timeout_resource_wait = 60;
22168        let mut state = RunState::new(
22169            repo.clone(),
22170            "main".into(),
22171            "deadbeef".into(),
22172            "task".into(),
22173            config,
22174        );
22175        let candidate = state.worktree_root().join("cand-A");
22176        let branch = state.branch_for('A');
22177        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22178            .await
22179            .unwrap();
22180        state.status = RunStatus::Ready;
22181        state.driver_exited = true;
22182        state.candidates.push(Candidate {
22183            index: 0,
22184            label: 'A',
22185            agent: "implement".into(),
22186            branch: branch.clone(),
22187            worktree: candidate.clone(),
22188            summary: String::new(),
22189            stat: String::new(),
22190            files: 0,
22191            commits: 0,
22192            empty: false,
22193            failed: None,
22194            verified_noop: None,
22195            duration_ms: 0,
22196            folded: false,
22197        });
22198        state.save_under(&home).unwrap();
22199        let id = state.id.clone();
22200        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
22201
22202        // A separate OS handle bypasses the launcher's local gate, exactly as
22203        // another process holding coordination does.
22204        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22205        assert_eq!(
22206            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22207            0
22208        );
22209        let error = tokio::time::timeout(
22210            Duration::from_secs(10),
22211            fold_run_when(&mut state, &home, &|_| Ok(true)),
22212        )
22213        .await
22214        .expect("the automatic fold does not wait out the 60 s resource wait")
22215        .unwrap_err();
22216        assert!(
22217            matches!(
22218                error.downcast_ref::<FoldRefusal>(),
22219                Some(FoldRefusal::Live(_))
22220            ),
22221            "{error:#}"
22222        );
22223        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
22224        // It gave way: both locks it held are free, nothing was removed and
22225        // nothing was saved (no resource block recorded on the record either).
22226        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
22227        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
22228        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
22229        assert_eq!(
22230            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
22231            record
22232        );
22233
22234        // The explicit entry point was asked for by a person and still waits.
22235        assert!(
22236            tokio::time::timeout(
22237                Duration::from_millis(300),
22238                fold_run(&mut state, true, &home)
22239            )
22240            .await
22241            .is_err(),
22242            "an explicit fold keeps waiting for coordination"
22243        );
22244        assert!(candidate.exists());
22245
22246        drop(external);
22247        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
22248            .await
22249            .unwrap();
22250        assert!(removed.contains(&branch));
22251        assert!(!candidate.exists());
22252    }
22253
22254    /// A branch handed to a later run is that run's (and its pull request's):
22255    /// folding the run that released it must not delete it.
22256    #[tokio::test]
22257    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
22258        let tmp = tempfile::tempdir().expect("tempdir");
22259        let repo = tmp.path().join("repo");
22260        std::fs::create_dir_all(&repo).unwrap();
22261        init_repo(&repo);
22262        let home = tmp.path().join("home");
22263
22264        let mut config = Config::default();
22265        config.graph.worktree_root = Some(tmp.path().join("wt"));
22266        let mut state = RunState::new(
22267            repo.clone(),
22268            "main".to_owned(),
22269            "deadbeef".to_owned(),
22270            "task".to_owned(),
22271            config,
22272        );
22273        // The worktree is already gone (released); the branch survives.
22274        git::git(&repo, &["branch", "magi/x/A", "main"])
22275            .await
22276            .expect("branch");
22277        state.candidates = vec![Candidate {
22278            index: 0,
22279            label: 'A',
22280            agent: "alpha".to_owned(),
22281            branch: "magi/x/A".to_owned(),
22282            worktree: state.worktree_root().join("cand-A"),
22283            summary: String::new(),
22284            stat: String::new(),
22285            files: 0,
22286            commits: 0,
22287            empty: false,
22288            failed: None,
22289            verified_noop: None,
22290            duration_ms: 0,
22291            folded: true,
22292        }];
22293        state.released_to = Some("20260901-000000-new1".to_owned());
22294        state.released_branches = vec!["magi/x/A".to_owned()];
22295
22296        state.save_under(&home).unwrap();
22297        fold_run(&mut state, true, &home).await.expect("fold_run");
22298        state.status = RunStatus::Merged;
22299        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22300        state.merge = Some(crate::run::MergeOutcome {
22301            mode: MergeMode::Pr,
22302            ok: true,
22303            detail: "confirmed merged".into(),
22304            empty: false,
22305        });
22306        state.save_under(&home).unwrap();
22307        fold_run(&mut state, true, &home)
22308            .await
22309            .expect("merged fold");
22310
22311        assert!(
22312            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22313            "the handed-over branch survives a fold"
22314        );
22315    }
22316
22317    /// A winner with nothing ahead of the base is caught before `gh` is ever
22318    /// asked for a pull request, and the message carries what the task's
22319    /// references resolved to.
22320    #[tokio::test]
22321    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22322        let tmp = tempfile::tempdir().expect("tempdir");
22323        let repo = tmp.path().join("repo");
22324        std::fs::create_dir_all(&repo).unwrap();
22325        init_repo(&repo);
22326        let run = |args: &[&str]| {
22327            let out = std::process::Command::new("git")
22328                .quiet()
22329                .args(args)
22330                .current_dir(&repo)
22331                .output()
22332                .expect("spawn git");
22333            assert!(out.status.success(), "git {args:?}");
22334        };
22335        run(&["branch", "magi/x/A"]);
22336        run(&["checkout", "-q", "-b", "magi/x/B"]);
22337        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22338        run(&["add", "-A"]);
22339        run(&["commit", "-q", "-m", "work"]);
22340        run(&["checkout", "-q", "main"]);
22341
22342        // A pull request is compared against the remote's base, so the
22343        // fixture needs one. Before it exists nothing can be read, and the
22344        // answer must be "not empty".
22345        let probe = RunState::new(
22346            repo.clone(),
22347            "main".to_owned(),
22348            "deadbeef".to_owned(),
22349            "task".to_owned(),
22350            Config::default(),
22351        );
22352        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22353        let bare = tmp.path().join("origin.git");
22354        let out = std::process::Command::new("git")
22355            .quiet()
22356            .args(["init", "-q", "--bare"])
22357            .arg(&bare)
22358            .output()
22359            .expect("spawn git");
22360        assert!(out.status.success(), "git init --bare");
22361        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22362        run(&["push", "-q", "origin", "main"]);
22363
22364        let mut state = RunState::new(
22365            repo.clone(),
22366            "main".to_owned(),
22367            "deadbeef".to_owned(),
22368            "task".to_owned(),
22369            Config::default(),
22370        );
22371        state.seeds = vec![refs::Seed {
22372            token: "magi/27b2/A".to_owned(),
22373            kind: refs::SeedKind::Unresolved,
22374            sha: String::new(),
22375            branch: true,
22376            detail: "no branch or commit named magi/27b2/A".to_owned(),
22377        }];
22378
22379        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22380        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22381        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22382        let detail = empty_candidate_detail(&state, "main");
22383        assert!(detail.starts_with("empty candidate"), "{detail}");
22384        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22385        assert!(detail.contains("--start-from"), "{detail}");
22386    }
22387
22388    /// `status == Ready` used to be read as "this is the harmless
22389    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22390    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22391    /// run's PR was closed without merging — and reentering `merge` with
22392    /// `mode` still `Pr` does not know the difference, so it pushed and
22393    /// opened a second pull request. `mode == Local` reproduces the same
22394    /// blind spot without a network call: reentry must not attempt another
22395    /// git merge once this node has already recorded an outcome.
22396    #[tokio::test]
22397    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22398        let tmp = tempfile::tempdir().expect("tempdir");
22399        let repo = tmp.path().join("repo");
22400        std::fs::create_dir_all(&repo).unwrap();
22401        init_repo(&repo);
22402
22403        let mut config = Config::default();
22404        config.merge.mode = MergeMode::Local;
22405
22406        let mut state = RunState::new(
22407            repo.clone(),
22408            "main".to_owned(),
22409            "deadbeef".to_owned(),
22410            "task".to_owned(),
22411            config,
22412        );
22413        state.candidates = vec![Candidate {
22414            index: 0,
22415            label: 'A',
22416            agent: "alpha".to_owned(),
22417            branch: "does-not-exist".to_owned(),
22418            worktree: repo.clone(),
22419            summary: String::new(),
22420            stat: String::new(),
22421            files: 0,
22422            commits: 0,
22423            empty: false,
22424            failed: None,
22425            verified_noop: None,
22426            duration_ms: 0,
22427            folded: false,
22428        }];
22429        state.tally = Some(Tally {
22430            first_choice: BTreeMap::from([('A', 1)]),
22431            borda: BTreeMap::new(),
22432            winner: 'A',
22433            rankings: 1,
22434            unanimous_initial: true,
22435            deliberated: false,
22436            changed_votes: 0,
22437            unanimous_final: true,
22438            tie_break: None,
22439            judges: 0,
22440            present: 0,
22441            quorum: 0,
22442            met_quorum: true,
22443            uncontested: Some("only candidate A produced a change".to_owned()),
22444        });
22445        state.reviews = vec![ReviewRound {
22446            round: 1,
22447            head: "deadbeef".to_owned(),
22448            verified_head: None,
22449            verified_at: None,
22450            reviews: Vec::new(),
22451            e2e: Vec::new(),
22452            fix: None,
22453            blocking: 0,
22454            answered: 0,
22455            expected: 0,
22456            clean: true,
22457            verify_retried: false,
22458            e2e_deferred: false,
22459            e2e_defer_reason: None,
22460            progressed: false,
22461            vote_split: false,
22462            reconsideration: Vec::new(),
22463            verdict: None,
22464        }];
22465        state.gate = vec![CommandOutcome {
22466            command: "test".to_owned(),
22467            code: Some(0),
22468            output_tail: String::new(),
22469            duration_ms: 0,
22470            resource_blocked: false,
22471            ..Default::default()
22472        }];
22473        state.gate_ran = true;
22474        // Reached its conclusion already — e.g. `land` closing the PR without
22475        // merging it, which (like the honest `MergeMode::None` path) leaves
22476        // `status` at `Ready`. The recorded outcome is what actually marks
22477        // this node done.
22478        state.status = RunStatus::Ready;
22479        state.merge = Some(MergeOutcome {
22480            mode: MergeMode::Local,
22481            ok: false,
22482            detail: "already concluded".to_owned(),
22483            empty: false,
22484        });
22485
22486        let mut runner = Runner {
22487            state,
22488            roles: ResolvedRoles {
22489                implementers: Vec::new(),
22490                judges: Vec::new(),
22491                reviewers: Vec::new(),
22492                fixer: None,
22493                conductor: conductor(),
22494                implementer_roster: Vec::new(),
22495                judge_roster: Vec::new(),
22496                reviewer_roster: Vec::new(),
22497            },
22498            sem: Arc::new(Semaphore::new(1)),
22499            pause: Pause::new(),
22500            interrupt: Pause::new(),
22501        };
22502
22503        runner.merge().await.expect("merge");
22504
22505        assert_eq!(
22506            runner.state.status,
22507            RunStatus::Ready,
22508            "a concluded run's status must not change on reentry"
22509        );
22510        assert_eq!(
22511            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22512            Some("already concluded"),
22513            "merge must not run again once the node already recorded an outcome"
22514        );
22515    }
22516
22517    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22518    /// when its last attempt was resource-blocked (the shared build cache
22519    /// could not be acquired or confirmed fresh in time - see
22520    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22521    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22522    /// a run merge a tree the gate never actually checked - exactly the case
22523    /// a contended cache produces on every retry until it clears. `merge`
22524    /// must refuse until `gate` has actually recorded an attempt.
22525    #[tokio::test]
22526    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22527        let tmp = tempfile::tempdir().expect("tempdir");
22528        let repo = tmp.path().join("repo");
22529        std::fs::create_dir_all(&repo).unwrap();
22530        init_repo(&repo);
22531
22532        let mut config = Config::default();
22533        config.merge.mode = MergeMode::Local;
22534
22535        let mut state = RunState::new(
22536            repo.clone(),
22537            "main".to_owned(),
22538            "deadbeef".to_owned(),
22539            "task".to_owned(),
22540            config,
22541        );
22542        state.candidates = vec![Candidate {
22543            index: 0,
22544            label: 'A',
22545            agent: "alpha".to_owned(),
22546            branch: "does-not-exist".to_owned(),
22547            worktree: repo.clone(),
22548            summary: String::new(),
22549            stat: String::new(),
22550            files: 0,
22551            commits: 0,
22552            empty: false,
22553            failed: None,
22554            verified_noop: None,
22555            duration_ms: 0,
22556            folded: false,
22557        }];
22558        state.tally = Some(Tally {
22559            first_choice: BTreeMap::from([('A', 1)]),
22560            borda: BTreeMap::new(),
22561            winner: 'A',
22562            rankings: 1,
22563            unanimous_initial: true,
22564            deliberated: false,
22565            changed_votes: 0,
22566            unanimous_final: true,
22567            tie_break: None,
22568            judges: 0,
22569            present: 0,
22570            quorum: 0,
22571            met_quorum: true,
22572            uncontested: Some("only candidate A produced a change".to_owned()),
22573        });
22574        state.reviews = vec![ReviewRound {
22575            round: 1,
22576            head: "deadbeef".to_owned(),
22577            verified_head: None,
22578            verified_at: None,
22579            reviews: Vec::new(),
22580            e2e: Vec::new(),
22581            fix: None,
22582            blocking: 0,
22583            answered: 0,
22584            expected: 0,
22585            clean: true,
22586            verify_retried: false,
22587            e2e_deferred: false,
22588            e2e_defer_reason: None,
22589            progressed: false,
22590            vote_split: false,
22591            reconsideration: Vec::new(),
22592            verdict: None,
22593        }];
22594        // The point: `gate` has not recorded anything yet.
22595        state.gate = Vec::new();
22596        state.gate_ran = false;
22597        state.status = RunStatus::Gating;
22598
22599        let mut runner = Runner {
22600            state,
22601            roles: ResolvedRoles {
22602                implementers: Vec::new(),
22603                judges: Vec::new(),
22604                reviewers: Vec::new(),
22605                fixer: None,
22606                conductor: conductor(),
22607                implementer_roster: Vec::new(),
22608                judge_roster: Vec::new(),
22609                reviewer_roster: Vec::new(),
22610            },
22611            sem: Arc::new(Semaphore::new(1)),
22612            pause: Pause::new(),
22613            interrupt: Pause::new(),
22614        };
22615
22616        runner.merge().await.expect("merge");
22617
22618        assert!(
22619            runner.state.merge.is_none(),
22620            "an empty gate must never be read as a passing one: {:?}",
22621            runner.state.merge
22622        );
22623    }
22624
22625    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22626    /// commands configured and `merge.mode` is `none` (a review-only run).
22627    /// `gate` must still record a real attempt — zero commands, vacuously
22628    /// passed — rather than leaving `state.gate` empty in a way `merge`
22629    /// cannot tell apart from "never ran"; otherwise the run reaches
22630    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22631    #[tokio::test]
22632    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22633        let tmp = tempfile::tempdir().expect("tempdir");
22634        let repo = tmp.path().join("repo");
22635        std::fs::create_dir_all(&repo).unwrap();
22636        init_repo(&repo);
22637
22638        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22639        let config = Config::default();
22640
22641        let mut state = RunState::new(
22642            repo.clone(),
22643            "main".to_owned(),
22644            "deadbeef".to_owned(),
22645            "task".to_owned(),
22646            config,
22647        );
22648        state.candidates = vec![Candidate {
22649            index: 0,
22650            label: 'A',
22651            agent: "alpha".to_owned(),
22652            branch: "does-not-exist".to_owned(),
22653            worktree: repo.clone(),
22654            summary: String::new(),
22655            stat: String::new(),
22656            files: 0,
22657            commits: 0,
22658            empty: false,
22659            failed: None,
22660            verified_noop: None,
22661            duration_ms: 0,
22662            folded: false,
22663        }];
22664        state.tally = Some(Tally {
22665            first_choice: BTreeMap::from([('A', 1)]),
22666            borda: BTreeMap::new(),
22667            winner: 'A',
22668            rankings: 1,
22669            unanimous_initial: true,
22670            deliberated: false,
22671            changed_votes: 0,
22672            unanimous_final: true,
22673            tie_break: None,
22674            judges: 0,
22675            present: 0,
22676            quorum: 0,
22677            met_quorum: true,
22678            uncontested: Some("only candidate A produced a change".to_owned()),
22679        });
22680        state.reviews = vec![ReviewRound {
22681            round: 1,
22682            head: "deadbeef".to_owned(),
22683            verified_head: None,
22684            verified_at: None,
22685            reviews: Vec::new(),
22686            e2e: Vec::new(),
22687            fix: None,
22688            blocking: 0,
22689            answered: 0,
22690            expected: 0,
22691            clean: true,
22692            verify_retried: false,
22693            e2e_deferred: false,
22694            e2e_defer_reason: None,
22695            progressed: false,
22696            vote_split: false,
22697            reconsideration: Vec::new(),
22698            verdict: None,
22699        }];
22700
22701        let mut runner = Runner {
22702            state,
22703            roles: ResolvedRoles {
22704                implementers: Vec::new(),
22705                judges: Vec::new(),
22706                reviewers: Vec::new(),
22707                fixer: None,
22708                conductor: conductor(),
22709                implementer_roster: Vec::new(),
22710                judge_roster: Vec::new(),
22711                reviewer_roster: Vec::new(),
22712            },
22713            sem: Arc::new(Semaphore::new(1)),
22714            pause: Pause::new(),
22715            interrupt: Pause::new(),
22716        };
22717
22718        runner.gate().await.expect("gate");
22719        assert!(
22720            runner.state.gate_ran,
22721            "zero configured commands is still a real attempt, not an unrun gate"
22722        );
22723        assert!(runner.state.gate.is_empty());
22724        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22725        assert_ne!(
22726            runner.state.status,
22727            RunStatus::Blocked,
22728            "a gate with nothing to check must not read as failed"
22729        );
22730
22731        runner.merge().await.expect("merge");
22732        assert_eq!(
22733            runner.state.status,
22734            RunStatus::Ready,
22735            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22736        );
22737    }
22738
22739    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22740    /// `verify.gate` (so the e2e leg and the final gate never build against
22741    /// different directories). With zero `verify.gate` commands but a
22742    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22743    /// that lease before discovering it had nothing to run - so a repo with
22744    /// no gate commands could come back `resource_blocked` (and therefore
22745    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22746    /// cache, exactly the contention this run's own zero commands could
22747    /// never have touched. `gate` must recognise there is nothing to check
22748    /// before it ever asks for the lease.
22749    #[tokio::test]
22750    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22751        crate::run::pin_test_home();
22752        let home = crate::run::home();
22753
22754        let tmp = tempfile::tempdir().expect("tempdir");
22755        let repo = tmp.path().join("repo");
22756        std::fs::create_dir_all(&repo).unwrap();
22757        init_repo(&repo);
22758        // Unique to this test, so holding its lease cannot collide with
22759        // another test sharing the same process-wide `home`.
22760        let cache_dir = tmp.path().join("target");
22761
22762        let mut config = Config::default();
22763        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22764        // `verify.gate` stays empty (the default). Any accidental cache
22765        // acquisition must report contention immediately, regardless of how
22766        // long unrelated Git subprocesses take under parallel test load.
22767        config.graph.timeout_verify = Some(2);
22768        config.graph.timeout_resource_wait = 0;
22769
22770        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22771        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22772            .expect("no io error acquiring directly")
22773        {
22774            crate::cache::AcquireOutcome::Acquired(g) => g,
22775            crate::cache::AcquireOutcome::Busy(b) => {
22776                panic!("expected the direct acquire to win the lease first: {b:?}")
22777            }
22778        };
22779
22780        let mut state = RunState::new(
22781            repo.clone(),
22782            "main".to_owned(),
22783            "deadbeef".to_owned(),
22784            "task".to_owned(),
22785            config,
22786        );
22787        state.candidates = vec![Candidate {
22788            index: 0,
22789            label: 'A',
22790            agent: "alpha".to_owned(),
22791            branch: "does-not-exist".to_owned(),
22792            worktree: repo.clone(),
22793            summary: String::new(),
22794            stat: String::new(),
22795            files: 0,
22796            commits: 0,
22797            empty: false,
22798            failed: None,
22799            verified_noop: None,
22800            duration_ms: 0,
22801            folded: false,
22802        }];
22803        state.tally = Some(Tally {
22804            first_choice: BTreeMap::from([('A', 1)]),
22805            borda: BTreeMap::new(),
22806            winner: 'A',
22807            rankings: 1,
22808            unanimous_initial: true,
22809            deliberated: false,
22810            changed_votes: 0,
22811            unanimous_final: true,
22812            tie_break: None,
22813            judges: 0,
22814            present: 0,
22815            quorum: 0,
22816            met_quorum: true,
22817            uncontested: Some("only candidate A produced a change".to_owned()),
22818        });
22819        state.reviews = vec![ReviewRound {
22820            round: 1,
22821            head: "deadbeef".to_owned(),
22822            verified_head: None,
22823            verified_at: None,
22824            reviews: Vec::new(),
22825            e2e: Vec::new(),
22826            fix: None,
22827            blocking: 0,
22828            answered: 0,
22829            expected: 0,
22830            clean: true,
22831            verify_retried: false,
22832            e2e_deferred: false,
22833            e2e_defer_reason: None,
22834            progressed: false,
22835            vote_split: false,
22836            reconsideration: Vec::new(),
22837            verdict: None,
22838        }];
22839
22840        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22841        state.reviews[0].e2e = vec![CommandOutcome {
22842            command: state.config.verify.e2e[0].clone(),
22843            code: Some(0),
22844            output_tail: String::new(),
22845            duration_ms: 0,
22846            resource_blocked: false,
22847            ..Default::default()
22848        }];
22849        let mut runner = Runner {
22850            state,
22851            roles: ResolvedRoles {
22852                implementers: Vec::new(),
22853                judges: Vec::new(),
22854                reviewers: Vec::new(),
22855                fixer: None,
22856                conductor: conductor(),
22857                implementer_roster: Vec::new(),
22858                judge_roster: Vec::new(),
22859                reviewer_roster: Vec::new(),
22860            },
22861            sem: Arc::new(Semaphore::new(1)),
22862            pause: Pause::new(),
22863            interrupt: Pause::new(),
22864        };
22865
22866        runner.gate().await.expect("gate");
22867        assert!(runner.state.resource_block.is_none());
22868        assert!(
22869            !runner
22870                .state
22871                .events
22872                .iter()
22873                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22874            "a gate with nothing to run must never request the held cache lease"
22875        );
22876        assert!(
22877            runner.state.gate_ran,
22878            "zero commands is still a real, immediate attempt"
22879        );
22880        assert!(runner.state.gate.is_empty());
22881        assert_ne!(
22882            runner.state.status,
22883            RunStatus::Blocked,
22884            "must not read as resource-blocked on a lease it never asked for"
22885        );
22886    }
22887
22888    /// A separate process carries a live worker's environment throughout all
22889    /// verification entry points; the parallel harness never changes its env.
22890    #[cfg(unix)]
22891    #[tokio::test]
22892    async fn verification_is_standalone_inside_a_live_worker() {
22893        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22894        if std::env::var_os(CHILD).is_none() {
22895            let home = tempfile::tempdir().unwrap();
22896            let generation = crate::worker::pin_current(home.path()).unwrap();
22897            let output = std::process::Command::new(std::env::current_exe().unwrap())
22898                .args([
22899                    "--exact",
22900                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22901                    "--nocapture",
22902                ])
22903                .env(CHILD, "1")
22904                .env("MAGI_HOME", home.path())
22905                .env("MAGI_WORKER_HOME", home.path())
22906                .env("MAGI_WORKER_ID", "abcdef")
22907                .env("MAGI_WORKER_GENERATION", &generation.id)
22908                .env("MAGI_WORKER_EXE", &generation.executable)
22909                .env("MAGI_RUN", "verification-parent")
22910                .env("MAGI_NODE", "gate")
22911                .env("MAGI_SEAT", "worker-fixture")
22912                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22913                .env("MAGI_NO_AUTOUPDATE", "0")
22914                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22915                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22916                .env(
22917                    "VERIFY_EXPECT_TOOLCHAIN",
22918                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22919                )
22920                .env(
22921                    "VERIFY_EXPECT_CACHE",
22922                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22923                )
22924                .output()
22925                .unwrap();
22926            assert!(
22927                output.status.success()
22928                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22929                "{}\n{}",
22930                String::from_utf8_lossy(&output.stdout),
22931                String::from_utf8_lossy(&output.stderr)
22932            );
22933            return;
22934        }
22935        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22936        let home = crate::run::home();
22937        let directory = home.join("workers/jobs/abcdef");
22938        std::fs::create_dir_all(&directory).unwrap();
22939        let job = crate::worker::Job {
22940            id: "abcdef".into(),
22941            sequence: 1,
22942            kind: "task".into(),
22943            key: "task:verification".into(),
22944            payload: serde_json::json!({}),
22945            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22946            version: Some(env!("CARGO_PKG_VERSION").into()),
22947            status: crate::worker::Status::Running,
22948            result: None,
22949            pid: Some(std::process::id()),
22950            created_at: 0,
22951            finished_at: None,
22952        };
22953        std::fs::write(
22954            directory.join("job.json"),
22955            serde_json::to_vec(&job).unwrap(),
22956        )
22957        .unwrap();
22958        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22959        let assert_worker = || {
22960            assert_eq!(
22961                crate::worker::current_job(&home).unwrap().unwrap().id,
22962                job.id
22963            );
22964            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22965            assert_eq!(
22966                crate::worker::helper_executable(&home).unwrap(),
22967                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22968            );
22969            assert!(
22970                crate::updater::Checker::new(&crate::config::Update {
22971                    mode: crate::config::UpdateMode::Notify,
22972                    interval: None,
22973                    auto_restart: false,
22974                })
22975                .is_none(),
22976                "the driver remains pinned, even while tests are standalone"
22977            );
22978        };
22979        assert_worker();
22980        let repo = home.join("repo");
22981        std::fs::create_dir_all(&repo).unwrap();
22982        init_repo(&repo);
22983        // Keep storage, seat/control context, containment and tool lookup.
22984        // No inherited values (or credentials) are printed on success.
22985        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22986            test -z "${MAGI_WORKER_GENERATION+x}" &&
22987            test -z "${MAGI_WORKER_HOME+x}" &&
22988            test -z "${MAGI_WORKER_EXE+x}" &&
22989            test "$MAGI_HOME/repo" -ef . &&
22990            test "$MAGI_RUN" = verification-parent &&
22991            test "$MAGI_NODE" = gate &&
22992            test "$MAGI_SEAT" = worker-fixture &&
22993            test -n "$MAGI_PROCESS_OWNER" &&
22994            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22995            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22996            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22997            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22998        // Negative control: an ordinary child inherits the contamination.
22999        assert!(
23000            !std::process::Command::new("sh")
23001                .args(["-c", probe])
23002                .current_dir(&repo)
23003                .status()
23004                .unwrap()
23005                .success()
23006        );
23007        let unrelated_home = tempfile::tempdir().unwrap();
23008        assert!(
23009            crate::worker::current_job(unrelated_home.path()).is_err(),
23010            "an inherited worker id cannot be resolved in a unit fixture's home"
23011        );
23012        let mut runner = runner_at(RunStatus::Gating);
23013        runner.state.repo = repo.clone();
23014        runner.state.config.disk.min_free_bytes = 0;
23015        runner.state.config.coordination = crate::config::test_coordination();
23016        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
23017        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
23018        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
23019        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
23020        let winner = Candidate {
23021            index: 0,
23022            label: 'A',
23023            agent: "fixture".into(),
23024            branch: "main".into(),
23025            worktree: repo.clone(),
23026            summary: String::new(),
23027            stat: String::new(),
23028            files: 0,
23029            commits: 0,
23030            empty: false,
23031            failed: None,
23032            verified_noop: None,
23033            duration_ms: 0,
23034            folded: false,
23035        };
23036        let (e2e, retried, pids) = run_e2e_with_retry(
23037            &mut runner.state,
23038            &["sh".into(), "-c".into()],
23039            &[format!("{probe} && printf initial")],
23040            &repo,
23041            Duration::from_secs(10),
23042            "initial",
23043            None,
23044        )
23045        .await;
23046        assert!(!retried && pids.is_empty());
23047        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
23048        assert_eq!(e2e[0].output_tail, "initial");
23049        let gate = runner.run_gate(&winner).await.unwrap();
23050        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
23051        // An interrupted repair must recheck e2e from saved state. Landing
23052        // reuses that state and must run both pre-gate and gate again.
23053        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
23054            git::rev_parse(&repo, "HEAD").await.unwrap(),
23055            false,
23056            Vec::new(),
23057        ));
23058        runner.state.save().unwrap();
23059        let mut resumed = RunState::load(&runner.state.id).unwrap();
23060        let wait = crate::repo_lock::WaitPolicy::default();
23061        assert!(matches!(
23062            check_gate_repair_e2e(&mut resumed, &winner, &wait)
23063                .await
23064                .unwrap(),
23065            GateFix::Retry
23066        ));
23067        let saved = RunState::load(&resumed.id).unwrap();
23068        let repair = saved.gate_repair_e2e.unwrap();
23069        assert!(repair.passed);
23070        assert_eq!(repair.outcomes.len(), 1);
23071        assert!(repair.outcomes[0].ok());
23072        let landing = run_landing_gate(&mut resumed, &winner, &wait)
23073            .await
23074            .unwrap();
23075        assert_eq!(landing.len(), 1);
23076        assert!(landing[0].ok(), "{landing:?}");
23077        assert_eq!(
23078            std::fs::read_to_string(repo.join("phases")).unwrap(),
23079            "pre\ngate\ne2e\npre\ngate\n"
23080        );
23081        assert_worker();
23082    }
23083
23084    #[tokio::test]
23085    async fn missing_verification_directory_is_a_command_failure() {
23086        crate::run::pin_test_home();
23087        let tmp = tempfile::tempdir().unwrap();
23088        let mut config = Config::default();
23089        config.verify.build_cache = crate::config::BuildCache::Isolated;
23090        config.verify.e2e = vec!["cd src-tauri && cargo test".into()];
23091        let commands = config.verify.e2e.clone();
23092        let mut state = RunState::new(
23093            tmp.path().to_owned(),
23094            "main".into(),
23095            "base".into(),
23096            "verification directory".into(),
23097            config,
23098        );
23099        let (outcomes, _) = run_commands(
23100            &mut state,
23101            "e2e",
23102            "e2e",
23103            1,
23104            &["sh".into(), "-c".into()],
23105            &commands,
23106            tmp.path(),
23107            Duration::from_secs(10),
23108        )
23109        .await;
23110        assert_eq!(outcomes.len(), 1);
23111        assert!(!outcomes[0].ok());
23112        assert!(!outcomes[0].resource_blocked);
23113        assert!(outcomes[0].output_tail.contains("src-tauri"));
23114        assert!(state.resource_block.is_none());
23115    }
23116
23117    #[cfg(unix)]
23118    #[tokio::test]
23119    async fn verification_keeps_the_panic_and_the_full_output() {
23120        crate::run::pin_test_home();
23121        let tmp = tempfile::tempdir().unwrap();
23122        let mut config = Config::default();
23123        config.disk.min_free_bytes = 0;
23124        let mut state = RunState::new(
23125            tmp.path().to_owned(),
23126            "main".into(),
23127            "base".into(),
23128            "verification evidence".into(),
23129            config,
23130        );
23131        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
23132                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
23133                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
23134        let mut names = Vec::new();
23135        for _ in 0..2 {
23136            let (outcomes, _) = run_commands(
23137                &mut state,
23138                "gate",
23139                "gate",
23140                0,
23141                &["sh".into(), "-c".into()],
23142                &[script.into()],
23143                tmp.path(),
23144                Duration::from_secs(60),
23145            )
23146            .await;
23147            let tail = &outcomes[0].output_tail;
23148            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
23149            assert!(tail.contains("boom assertion"));
23150            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
23151            let line = tail.lines().next().unwrap();
23152            names.push(line.to_owned());
23153        }
23154        assert_ne!(names[0], names[1], "the second run must not overwrite");
23155        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
23156        assert!(full.len() > 500_000 && full.contains("boom assertion"));
23157        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
23158
23159        // Storage failures are evidence too; preserve the command's verdict.
23160        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
23161        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
23162        let (outcomes, _) = run_commands(
23163            &mut state,
23164            "gate",
23165            "gate",
23166            0,
23167            &["sh".into(), "-c".into()],
23168            &["echo failure-output; exit 7".into()],
23169            tmp.path(),
23170            Duration::from_secs(10),
23171        )
23172        .await;
23173        assert_eq!(outcomes[0].code, Some(7));
23174        assert!(state.events.iter().any(|e| {
23175            e.node == "gate" && e.message.contains("could not save the full gate output:")
23176        }));
23177    }
23178
23179    #[cfg(unix)]
23180    #[tokio::test]
23181    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
23182        crate::run::pin_test_home();
23183        let tmp = tempfile::tempdir().unwrap();
23184        let mut config = Config::default();
23185        config.disk.min_free_bytes = 0;
23186        let mut state = RunState::new(
23187            tmp.path().to_owned(),
23188            "main".into(),
23189            "base".into(),
23190            "verification evidence".into(),
23191            config,
23192        );
23193        let (outcomes, pids) = run_commands(
23194            &mut state,
23195            "gate",
23196            "gate",
23197            1,
23198            &["sh".into(), "-c".into()],
23199            &[
23200                "printf before-timeout; exec sleep 30".into(),
23201                "kill -TERM $$".into(),
23202                "exit 7".into(),
23203                "printf success".into(),
23204            ],
23205            tmp.path(),
23206            Duration::from_secs(1),
23207        )
23208        .await;
23209        wait_for_timed_out_children_to_die(&pids).await;
23210        assert_eq!(
23211            pids.len(),
23212            1,
23213            "unleased timeout retains its death-check PID"
23214        );
23215        assert_eq!(outcomes.len(), 4);
23216        assert_eq!(outcomes[0].code, None);
23217        assert!(outcomes[0].output_tail.contains("before-timeout"));
23218        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
23219        assert_eq!(outcomes[1].code, None);
23220        assert!(outcomes[1].output_tail.contains("command terminated:"));
23221        assert!(!outcomes[1].output_tail.contains("timed out"));
23222        assert_eq!(outcomes[2].code, Some(7));
23223        assert!(!outcomes[2].output_tail.contains("timed out"));
23224        assert_eq!(outcomes[3].code, Some(0));
23225        assert_eq!(outcomes[3].output_tail, "success");
23226        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
23227    }
23228
23229    /// The addendum's second gap: a `verify.gate` command running for real
23230    /// wall-clock time had nothing at all to show for it in `active` before
23231    /// `run_commands` learned to record it — a run could sit in `Gating` for
23232    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
23233    /// what was actually happening. Proven with a genuinely still-running
23234    /// command, not just a before/after check on the final state: a poller
23235    /// task reads the same `run.json` `gate()` is writing, the same way the
23236    /// phone or `magi show` would, while the shell command is still blocked
23237    /// on its own release marker.
23238    #[tokio::test]
23239    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
23240        crate::run::pin_test_home();
23241
23242        let tmp = tempfile::tempdir().expect("tempdir");
23243        let repo = tmp.path().join("repo");
23244        std::fs::create_dir_all(&repo).unwrap();
23245        init_repo(&repo);
23246
23247        let mut config = Config::default();
23248        config.disk.min_free_bytes = 0;
23249        config.verify.gate = vec![
23250            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
23251             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
23252                .to_owned(),
23253        ];
23254
23255        let mut state = RunState::new(
23256            repo.clone(),
23257            "main".to_owned(),
23258            "deadbeef".to_owned(),
23259            "task".to_owned(),
23260            config,
23261        );
23262        let run_id = state.id.clone();
23263        state.candidates = vec![Candidate {
23264            index: 0,
23265            label: 'A',
23266            agent: "alpha".to_owned(),
23267            branch: "does-not-exist".to_owned(),
23268            worktree: repo.clone(),
23269            summary: String::new(),
23270            stat: String::new(),
23271            files: 0,
23272            commits: 0,
23273            empty: false,
23274            failed: None,
23275            verified_noop: None,
23276            duration_ms: 0,
23277            folded: false,
23278        }];
23279        state.tally = Some(Tally {
23280            first_choice: BTreeMap::from([('A', 1)]),
23281            borda: BTreeMap::new(),
23282            winner: 'A',
23283            rankings: 1,
23284            unanimous_initial: true,
23285            deliberated: false,
23286            changed_votes: 0,
23287            unanimous_final: true,
23288            tie_break: None,
23289            judges: 0,
23290            present: 0,
23291            quorum: 0,
23292            met_quorum: true,
23293            uncontested: Some("only candidate A produced a change".to_owned()),
23294        });
23295        state.reviews = vec![ReviewRound {
23296            round: 1,
23297            head: "deadbeef".to_owned(),
23298            verified_head: None,
23299            verified_at: None,
23300            reviews: Vec::new(),
23301            e2e: Vec::new(),
23302            fix: None,
23303            blocking: 0,
23304            answered: 0,
23305            expected: 0,
23306            clean: true,
23307            verify_retried: false,
23308            e2e_deferred: false,
23309            e2e_defer_reason: None,
23310            progressed: false,
23311            vote_split: false,
23312            reconsideration: Vec::new(),
23313            verdict: None,
23314        }];
23315
23316        let mut runner = Runner {
23317            state,
23318            roles: ResolvedRoles {
23319                implementers: Vec::new(),
23320                judges: Vec::new(),
23321                reviewers: Vec::new(),
23322                fixer: None,
23323                conductor: conductor(),
23324                implementer_roster: Vec::new(),
23325                judge_roster: Vec::new(),
23326                reviewer_roster: Vec::new(),
23327            },
23328            sem: Arc::new(Semaphore::new(1)),
23329            pause: Pause::new(),
23330            interrupt: Pause::new(),
23331        };
23332
23333        let started_marker = repo.join("started.marker");
23334        let release_marker = repo.join("release.marker");
23335        let observe = async {
23336            loop {
23337                if started_marker.exists()
23338                    && let Ok(s) = crate::run::RunState::load(&run_id)
23339                    && let Some(a) = s.active.get("gate")
23340                {
23341                    std::fs::write(&release_marker, b"go").expect("release marker");
23342                    break a.clone();
23343                }
23344                tokio::time::sleep(Duration::from_millis(50)).await;
23345            }
23346        };
23347        let captured = {
23348            let gate = runner.gate();
23349            tokio::pin!(gate);
23350            let captured = tokio::select! {
23351                observed = observe => observed,
23352                result = &mut gate => panic!(
23353                    "gate exited before its in-flight entry was observed: {result:?}"
23354                ),
23355            };
23356            gate.await.expect("gate");
23357            captured
23358        };
23359
23360        assert_eq!(captured.task.as_deref(), Some("gate"));
23361        assert_eq!(captured.node, "gate");
23362        assert_eq!(captured.index, Some(1));
23363        assert_eq!(captured.total, Some(1));
23364        assert!(
23365            captured
23366                .command
23367                .as_deref()
23368                .is_some_and(|c| c.contains("started.marker")),
23369            "{captured:?}"
23370        );
23371
23372        assert!(
23373            runner.state.active.is_empty(),
23374            "the entry must be cleared once the command actually finished: {:?}",
23375            runner.state.active
23376        );
23377        assert!(runner.state.gate_ran);
23378        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23379    }
23380
23381    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23382    /// record for `land`; one with only a Minor, or no reject, leaves none.
23383    #[tokio::test]
23384    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23385        use crate::verdict::{Finding, ReviewVote, Severity};
23386        crate::run::pin_test_home();
23387        let tmp = tempfile::tempdir().expect("tempdir");
23388        let repo = tmp.path().join("repo");
23389        std::fs::create_dir_all(&repo).unwrap();
23390        init_repo(&repo);
23391
23392        for (severity, vote, expect) in [
23393            (Severity::Major, ReviewVote::Reject, true),
23394            (Severity::Minor, ReviewVote::Reject, false),
23395            (Severity::Major, ReviewVote::Approve, false),
23396        ] {
23397            let mut round = review_round(false, 1, 1, 1, false, true);
23398            round.reviews = vec![ReviewRecord {
23399                reviewer: 1,
23400                agent: "alpha".to_owned(),
23401                summary: String::new(),
23402                findings: vec![Finding {
23403                    id: "R1-1-1".to_owned(),
23404                    severity,
23405                    file: None,
23406                    line: None,
23407                    title: "t".to_owned(),
23408                    detail: String::new(),
23409                }],
23410                vote: Some(vote),
23411                failed: None,
23412                duration_ms: 0,
23413                attempts: 0,
23414            }];
23415            let mut state = RunState::new(
23416                repo.clone(),
23417                "main".to_owned(),
23418                "deadbeef".to_owned(),
23419                "task".to_owned(),
23420                Config::default(),
23421            );
23422            state.reviews = vec![round];
23423            let mut runner = Runner {
23424                state,
23425                roles: ResolvedRoles {
23426                    implementers: Vec::new(),
23427                    judges: Vec::new(),
23428                    reviewers: Vec::new(),
23429                    fixer: None,
23430                    conductor: conductor(),
23431                    implementer_roster: Vec::new(),
23432                    judge_roster: Vec::new(),
23433                    reviewer_roster: Vec::new(),
23434                },
23435                sem: Arc::new(Semaphore::new(1)),
23436                pause: Pause::new(),
23437                interrupt: Pause::new(),
23438            };
23439            let shell = runner.state.config.shell();
23440            runner
23441                .stop_reviewing("round budget spent", &shell, &repo)
23442                .await
23443                .expect("stop_reviewing");
23444            assert_eq!(runner.state.status, RunStatus::Gating);
23445            assert_eq!(
23446                runner.state.contested_handoff.is_some(),
23447                expect,
23448                "{severity:?} + {vote:?}"
23449            );
23450        }
23451    }
23452
23453    /// The shape the incident this whole fix responds to actually had: the
23454    /// round budget spent, the last round's own e2e blocked on the shared
23455    /// build cache (held here by a live pid — this test process — exactly
23456    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23457    /// without forking a process). `stop_reviewing` must retry it — not
23458    /// silently leave the round looking untouched (the catch-up-only half of
23459    /// the bug), and not read the contention as a red `e2e` and block the
23460    /// run on it (the other half). Called directly, the same way
23461    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23462    /// above exercises `gate`, so this never needs a real cargo build to
23463    /// reach: the lease is never released, so `with_cache_lease` never gets
23464    /// past acquiring it into anything that would need a real workspace.
23465    #[tokio::test]
23466    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23467        crate::run::pin_test_home();
23468        let home = crate::run::home();
23469
23470        let tmp = tempfile::tempdir().expect("tempdir");
23471        let repo = tmp.path().join("repo");
23472        std::fs::create_dir_all(&repo).unwrap();
23473        init_repo(&repo);
23474        let head = crate::git::rev_parse(&repo, "HEAD")
23475            .await
23476            .expect("rev-parse");
23477        // Unique to this test, so holding its lease cannot collide with
23478        // another test sharing the same process-wide `home`.
23479        let cache_dir = tmp.path().join("target");
23480
23481        let mut config = Config::default();
23482        config.verify.e2e = vec![format!(
23483            "CARGO_TARGET_DIR='{}' test -f README.md",
23484            cache_dir.display()
23485        )];
23486        config.graph.review_rounds = 1;
23487        // Bounded so a regression that does start waiting fails the test in
23488        // seconds, not hangs it.
23489        config.graph.timeout_verify = Some(2);
23490        config.graph.timeout_resource_wait = 2;
23491
23492        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23493        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23494            .expect("no io error acquiring directly")
23495        {
23496            crate::cache::AcquireOutcome::Acquired(g) => g,
23497            crate::cache::AcquireOutcome::Busy(b) => {
23498                panic!("expected the direct acquire to win the lease first: {b:?}")
23499            }
23500        };
23501
23502        let mut state = RunState::new(
23503            repo.clone(),
23504            "main".to_owned(),
23505            head.clone(),
23506            "task".to_owned(),
23507            config,
23508        );
23509        state.candidates = vec![Candidate {
23510            index: 0,
23511            label: 'A',
23512            agent: "alpha".to_owned(),
23513            branch: "does-not-exist".to_owned(),
23514            worktree: repo.clone(),
23515            summary: String::new(),
23516            stat: String::new(),
23517            files: 0,
23518            commits: 0,
23519            empty: false,
23520            failed: None,
23521            verified_noop: None,
23522            duration_ms: 0,
23523            folded: false,
23524        }];
23525        state.tally = Some(Tally {
23526            first_choice: BTreeMap::from([('A', 1)]),
23527            borda: BTreeMap::new(),
23528            winner: 'A',
23529            rankings: 1,
23530            unanimous_initial: true,
23531            deliberated: false,
23532            changed_votes: 0,
23533            unanimous_final: true,
23534            tie_break: None,
23535            judges: 0,
23536            present: 0,
23537            quorum: 0,
23538            met_quorum: true,
23539            uncontested: Some("only candidate A produced a change".to_owned()),
23540        });
23541        // The round budget's last round, deferred: `needs_catchup_run`'s
23542        // other trigger. `stop_reviewing`'s retry machinery must treat this
23543        // exactly like a resource-blocked attempt once it actually runs.
23544        state.reviews = vec![ReviewRound {
23545            round: 1,
23546            head: head.clone(),
23547            verified_head: None,
23548            verified_at: None,
23549            reviews: Vec::new(),
23550            e2e: Vec::new(),
23551            fix: None,
23552            blocking: 1,
23553            answered: 1,
23554            expected: 1,
23555            clean: false,
23556            verify_retried: false,
23557            e2e_deferred: true,
23558            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23559            progressed: false,
23560            vote_split: false,
23561            reconsideration: Vec::new(),
23562            verdict: None,
23563        }];
23564
23565        let mut runner = Runner {
23566            state,
23567            roles: ResolvedRoles {
23568                implementers: Vec::new(),
23569                judges: Vec::new(),
23570                reviewers: Vec::new(),
23571                fixer: None,
23572                conductor: conductor(),
23573                implementer_roster: Vec::new(),
23574                judge_roster: Vec::new(),
23575                reviewer_roster: Vec::new(),
23576            },
23577            sem: Arc::new(Semaphore::new(1)),
23578            pause: Pause::new(),
23579            interrupt: Pause::new(),
23580        };
23581
23582        let shell = runner.state.config.shell();
23583        runner
23584            .stop_reviewing("round budget spent", &shell, &repo)
23585            .await
23586            .expect("stop_reviewing");
23587
23588        let last = runner.state.reviews.last().expect("round record");
23589        assert_eq!(
23590            last.e2e_status(),
23591            E2eStatus::ResourceBlocked,
23592            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23593             failed: {last:?}"
23594        );
23595        assert_eq!(
23596            last.verified_head.as_deref(),
23597            Some(head.as_str()),
23598            "which commit this attempt targeted is known even though nothing finished checking \
23599             it"
23600        );
23601        let first_attempt_at = last
23602            .verified_at
23603            .expect("when this attempt ran is known too");
23604        assert_ne!(
23605            runner.state.status,
23606            RunStatus::Blocked,
23607            "contention is evidence about the machine, not the patch — it must not settle the \
23608             run as blocked: {:?}",
23609            runner.state.status
23610        );
23611        assert!(
23612            !runner
23613                .state
23614                .events
23615                .iter()
23616                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23617            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23618            runner.state.events
23619        );
23620
23621        // The cache is still held: a later reentry must retry the same
23622        // round's verification again — not leave it looking exactly as
23623        // untouched as the first blocked attempt, which is indistinguishable
23624        // from never having tried again at all.
23625        runner
23626            .stop_reviewing("round budget spent", &shell, &repo)
23627            .await
23628            .expect("stop_reviewing retry");
23629        assert_eq!(
23630            runner.state.reviews.len(),
23631            1,
23632            "no new round was started: {:?}",
23633            runner.state.reviews
23634        );
23635        let last = runner.state.reviews.last().expect("round record");
23636        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23637        assert!(
23638            last.verified_at.expect("still known") > first_attempt_at,
23639            "a second reentry must be a fresh attempt, not a stale copy of the first"
23640        );
23641        assert_ne!(runner.state.status, RunStatus::Blocked);
23642
23643        held.release();
23644    }
23645
23646    #[cfg(unix)]
23647    #[tokio::test]
23648    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23649        ask_test_home();
23650        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23651            let tmp = tempfile::tempdir().unwrap();
23652            let repo = tmp.path().join("repo");
23653            std::fs::create_dir(&repo).unwrap();
23654            init_repo(&repo);
23655            let run_git = |args: &[&str]| {
23656                let out = std::process::Command::new("git")
23657                    .args(args)
23658                    .current_dir(&repo)
23659                    .output()
23660                    .unwrap();
23661                assert!(
23662                    out.status.success(),
23663                    "{args:?}: {}",
23664                    String::from_utf8_lossy(&out.stderr)
23665                );
23666            };
23667            let origin = tmp.path().join("origin.git");
23668            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23669            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23670            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23671            run_git(&["add", "spec.rs"]);
23672            run_git(&["commit", "-m", "initial spec"]);
23673            run_git(&["push", "origin", "main"]);
23674            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23675            run_git(&["checkout", "-b", "fix/review"]);
23676            std::fs::write(
23677                repo.join("check.rs"),
23678                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23679            )
23680            .unwrap();
23681            run_git(&["add", "check.rs"]);
23682            run_git(&["commit", "-m", "use spec"]);
23683            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23684            run_git(&["checkout", "main"]);
23685            std::fs::write(
23686                repo.join("spec.rs"),
23687                "struct AgentSpec { max_turn_secs: u64 }\n",
23688            )
23689            .unwrap();
23690            run_git(&["add", "spec.rs"]);
23691            run_git(&["commit", "-m", "extend spec"]);
23692            run_git(&["push", "origin", "main"]);
23693            run_git(&["checkout", "fix/review"]);
23694
23695            let mut runner = runner_at(RunStatus::Reviewing);
23696            runner.state.repo = repo.clone();
23697            runner.state.base_commit = base;
23698            runner.state.pr_head = Some("fix/review".into());
23699            runner.state.config.graph.review_rounds = max_rounds;
23700            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23701            runner.state.config.graph.sessions = false;
23702            runner.state.config.disk.min_free_bytes = 0;
23703            runner.state.config.verify.e2e =
23704                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23705            runner.state.candidates = vec![Candidate {
23706                index: 0,
23707                label: 'A',
23708                agent: "fixture".into(),
23709                branch: "fix/review".into(),
23710                worktree: repo.clone(),
23711                summary: String::new(),
23712                stat: String::new(),
23713                files: 1,
23714                commits: 1,
23715                empty: false,
23716                failed: None,
23717                verified_noop: None,
23718                duration_ms: 0,
23719                folded: false,
23720            }];
23721            runner.state.tally = Some(Tally {
23722                first_choice: BTreeMap::new(),
23723                borda: BTreeMap::new(),
23724                winner: 'A',
23725                rankings: 0,
23726                unanimous_initial: true,
23727                deliberated: false,
23728                changed_votes: 0,
23729                unanimous_final: true,
23730                tie_break: None,
23731                judges: 0,
23732                present: 0,
23733                quorum: 0,
23734                met_quorum: true,
23735                uncontested: Some("review-only".into()),
23736            });
23737            let mut last = review_round(false, 0, 1, 1, false, false);
23738            last.head = reviewed.clone();
23739            last.e2e_deferred = true;
23740            last.e2e[0].resource_blocked = true;
23741            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23742            if max_rounds == 1 {
23743                last.e2e.clear();
23744            }
23745            runner.state.reviews = vec![last];
23746            let calls = tmp.path().join("fix-calls");
23747            let mut fixer = spec("repair");
23748            fixer
23749                .env
23750                .insert("FIX_CALLS".into(), calls.display().to_string());
23751            fixer.command = vec!["sh".into(), "-c".into(), r#"
23752                echo fix >> "$FIX_CALLS"
23753                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23754                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23755                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23756                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23757            "#.into()];
23758            let mut reviewer = spec("reviewer");
23759            reviewer.command = vec![
23760                "sh".into(),
23761                "-c".into(),
23762                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23763                    .into(),
23764            ];
23765            runner.roles.fixer = Some(vec![fixer]);
23766            runner.roles.reviewers = vec![reviewer];
23767
23768            runner.sync_to_base().await.unwrap();
23769            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23770            assert_ne!(rebased, reviewed);
23771            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23772            if reentry {
23773                // Simulate a crash after catch-up evidence was saved but before
23774                // dispatching the fixer. No dedicated pending-repair field exists.
23775                let shell = runner.state.config.shell();
23776                runner
23777                    .stop_unresolved_review("deferred verification", &shell, &repo)
23778                    .await
23779                    .unwrap();
23780                assert!(runner.catchup_repairable());
23781                assert!(!calls.exists());
23782                runner.state = RunState::load(&runner.state.id).unwrap();
23783                assert!(runner.catchup_repairable());
23784            }
23785            runner.review_loop().await.unwrap();
23786            let first = &runner.state.reviews[0];
23787            assert_eq!(first.head, reviewed);
23788            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23789            assert!(
23790                first.verify_retried,
23791                "a reproduced build failure gets exactly one retry: {:?}",
23792                first.e2e
23793            );
23794            assert!(first.e2e[0].output_tail.contains("E0063"));
23795            assert!(!runner.catchup_repairable());
23796            if max_rounds == 2 {
23797                assert_eq!(
23798                    runner.state.status,
23799                    RunStatus::Gating,
23800                    "{}",
23801                    crate::report::run(&runner.state)
23802                );
23803                assert_eq!(runner.state.reviews.len(), 2);
23804                assert!(first.fix.as_ref().unwrap().committed);
23805                assert!(runner.state.reviews[1].clean);
23806                assert_eq!(
23807                    runner
23808                        .state
23809                        .reviews
23810                        .iter()
23811                        .filter(|r| r.fix.is_some())
23812                        .count(),
23813                    1
23814                );
23815                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23816                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23817            } else {
23818                assert_eq!(runner.state.status, RunStatus::Blocked);
23819                assert!(first.fix.is_none());
23820                assert!(!calls.exists());
23821                let recovery = crate::recovery::assess(
23822                    "prior",
23823                    Some(&runner.state),
23824                    &runner.landing_base(),
23825                    crate::recovery::Relation::Diverged,
23826                );
23827                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23828                let reasons = recovery.reasons.join("\n");
23829                assert!(
23830                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23831                    "{reasons}"
23832                );
23833                assert!(
23834                    reasons.contains("base sync to")
23835                        && reasons.contains("additional review is required"),
23836                    "{reasons}"
23837                );
23838            }
23839        }
23840    }
23841
23842    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23843    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23844    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23845    /// own top-of-function fast path (`review_conclusion`) correctly reads
23846    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23847    /// own `for` range is empty once the round budget is spent, so
23848    /// `review_loop` must retry the check itself rather than silently doing
23849    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23850    /// above exercises directly, but through `review_loop`'s own entry point
23851    /// this time, proving the wiring between the two rather than just the
23852    /// retry logic in isolation.
23853    #[tokio::test]
23854    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23855        crate::run::pin_test_home();
23856        let home = crate::run::home();
23857
23858        let tmp = tempfile::tempdir().expect("tempdir");
23859        let repo = tmp.path().join("repo");
23860        std::fs::create_dir_all(&repo).unwrap();
23861        init_repo(&repo);
23862        let head = crate::git::rev_parse(&repo, "HEAD")
23863            .await
23864            .expect("rev-parse");
23865        let cache_dir = tmp.path().join("target");
23866
23867        let mut config = Config::default();
23868        config.verify.e2e = vec![format!(
23869            "CARGO_TARGET_DIR='{}' test -f README.md",
23870            cache_dir.display()
23871        )];
23872        config.graph.review_rounds = 1;
23873        config.graph.timeout_verify = Some(2);
23874        config.graph.timeout_resource_wait = 2;
23875
23876        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23877        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23878            .expect("no io error acquiring directly")
23879        {
23880            crate::cache::AcquireOutcome::Acquired(g) => g,
23881            crate::cache::AcquireOutcome::Busy(b) => {
23882                panic!("expected the direct acquire to win the lease first: {b:?}")
23883            }
23884        };
23885
23886        let mut state = RunState::new(
23887            repo.clone(),
23888            "main".to_owned(),
23889            head.clone(),
23890            "task".to_owned(),
23891            config,
23892        );
23893        state.candidates = vec![Candidate {
23894            index: 0,
23895            label: 'A',
23896            agent: "alpha".to_owned(),
23897            branch: "does-not-exist".to_owned(),
23898            worktree: repo.clone(),
23899            summary: String::new(),
23900            stat: String::new(),
23901            files: 0,
23902            commits: 0,
23903            empty: false,
23904            failed: None,
23905            verified_noop: None,
23906            duration_ms: 0,
23907            folded: false,
23908        }];
23909        state.tally = Some(Tally {
23910            first_choice: BTreeMap::from([('A', 1)]),
23911            borda: BTreeMap::new(),
23912            winner: 'A',
23913            rankings: 1,
23914            unanimous_initial: true,
23915            deliberated: false,
23916            changed_votes: 0,
23917            unanimous_final: true,
23918            tie_break: None,
23919            judges: 0,
23920            present: 0,
23921            quorum: 0,
23922            met_quorum: true,
23923            uncontested: Some("only candidate A produced a change".to_owned()),
23924        });
23925        // The exact shape a prior process's `stop_reviewing` would have left
23926        // on disk: the round budget's last round, a real attempt already
23927        // made and already resource-blocked.
23928        state.reviews = vec![ReviewRound {
23929            round: 1,
23930            head: head.clone(),
23931            verified_head: Some(head.clone()),
23932            verified_at: Some(jiff::Timestamp::now()),
23933            reviews: Vec::new(),
23934            e2e: vec![CommandOutcome {
23935                command: format!(
23936                    "CARGO_TARGET_DIR='{}' test -f README.md",
23937                    cache_dir.display()
23938                ),
23939                code: None,
23940                output_tail: "waiting for the shared build cache".to_owned(),
23941                duration_ms: 0,
23942                resource_blocked: true,
23943                ..Default::default()
23944            }],
23945            fix: None,
23946            blocking: 1,
23947            answered: 1,
23948            expected: 1,
23949            clean: false,
23950            verify_retried: false,
23951            e2e_deferred: false,
23952            e2e_defer_reason: None,
23953            progressed: false,
23954            vote_split: false,
23955            reconsideration: Vec::new(),
23956            verdict: None,
23957        }];
23958
23959        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23960        let mut runner = Runner {
23961            state,
23962            roles: ResolvedRoles {
23963                implementers: Vec::new(),
23964                judges: Vec::new(),
23965                reviewers: Vec::new(),
23966                fixer: None,
23967                conductor: conductor(),
23968                implementer_roster: Vec::new(),
23969                judge_roster: Vec::new(),
23970                reviewer_roster: Vec::new(),
23971            },
23972            sem: Arc::new(Semaphore::new(1)),
23973            pause: Pause::new(),
23974            interrupt: Pause::new(),
23975        };
23976
23977        // The lease is still held throughout, so this reentry's own retry is
23978        // also contended — proving `review_loop` actually tried again (not
23979        // that it happened to succeed) is what the timestamp comparison
23980        // below is for.
23981        runner.review_loop().await.expect("review_loop");
23982
23983        assert_eq!(
23984            runner.state.reviews.len(),
23985            1,
23986            "no new round was started on top of the unresolved one: {:?}",
23987            runner.state.reviews
23988        );
23989        let last = &runner.state.reviews[0];
23990        assert_eq!(
23991            last.e2e_status(),
23992            E2eStatus::ResourceBlocked,
23993            "still contended: {last:?}"
23994        );
23995        assert!(
23996            last.verified_at.expect("still known") > first_attempt_at,
23997            "review_loop must have actually retried the check, not left it exactly as found"
23998        );
23999        assert_ne!(
24000            runner.state.status,
24001            RunStatus::Blocked,
24002            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
24003            runner.state.status
24004        );
24005
24006        held.release();
24007    }
24008
24009    #[tokio::test]
24010    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
24011        crate::run::pin_test_home();
24012        for status in [RunStatus::Blocked, RunStatus::Gating] {
24013            let mut runner = runner_at(status);
24014            runner.state.config.graph.land = true;
24015            runner.state.gate_ran = true;
24016            runner.state.merge = Some(MergeOutcome {
24017                mode: MergeMode::Pr,
24018                ok: false,
24019                detail: "the fixer produced no commit".into(),
24020                empty: false,
24021            });
24022            let url = "https://example.invalid/o/r/pull/1";
24023            runner.state.pr = Some(crate::run::PrRecord {
24024                url: url.into(),
24025                number: 1,
24026                state: "open".into(),
24027                checks: "red".into(),
24028                round: 1,
24029                rounds: 1,
24030                red_at_merge: Vec::new(),
24031            });
24032            runner.state.save().unwrap();
24033            // The nonexistent repository makes observation fail before a forge
24034            // command can run. We still must reach land, rather than silently
24035            // return from the graph with its old gate and merge records.
24036            runner.execute_graph().await.unwrap();
24037            assert_eq!(runner.state.status, RunStatus::Blocked);
24038            assert!(runner.state.land_sync_pending);
24039            assert!(runner.state.events.iter().any(|event|
24040                event.node == "land" && event.message == format!("watching {url}")));
24041            assert_eq!(
24042                runner.state.merge.as_ref().unwrap().detail,
24043                "the fixer produced no commit"
24044            );
24045        }
24046    }
24047
24048    #[tokio::test]
24049    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
24050        crate::run::pin_test_home();
24051        let tmp = tempfile::tempdir().expect("tempdir");
24052        let repo = tmp.path().join("repo");
24053        std::fs::create_dir_all(&repo).unwrap();
24054        init_repo(&repo);
24055
24056        let mut config = Config::default();
24057        config.merge.mode = MergeMode::Pr;
24058        config.graph.land = true;
24059        config.graph.land_approval = false;
24060
24061        let mut state = RunState::new(
24062            repo.clone(),
24063            "main".to_owned(),
24064            "deadbeef".to_owned(),
24065            "task".to_owned(),
24066            config,
24067        );
24068        state.candidates = vec![Candidate {
24069            index: 0,
24070            label: 'A',
24071            agent: "alpha".to_owned(),
24072            branch: "does-not-exist".to_owned(),
24073            worktree: repo.clone(),
24074            summary: String::new(),
24075            stat: String::new(),
24076            files: 0,
24077            commits: 0,
24078            empty: false,
24079            failed: None,
24080            verified_noop: None,
24081            duration_ms: 0,
24082            folded: false,
24083        }];
24084        state.tally = Some(Tally {
24085            first_choice: BTreeMap::from([('A', 1)]),
24086            borda: BTreeMap::new(),
24087            winner: 'A',
24088            rankings: 1,
24089            unanimous_initial: true,
24090            deliberated: false,
24091            changed_votes: 0,
24092            unanimous_final: true,
24093            tie_break: None,
24094            judges: 0,
24095            present: 0,
24096            quorum: 0,
24097            met_quorum: true,
24098            uncontested: Some("only candidate A produced a change".to_owned()),
24099        });
24100        state.reviews = vec![ReviewRound {
24101            round: 1,
24102            head: "deadbeef".to_owned(),
24103            verified_head: None,
24104            verified_at: None,
24105            reviews: Vec::new(),
24106            e2e: Vec::new(),
24107            fix: None,
24108            blocking: 0,
24109            answered: 0,
24110            expected: 0,
24111            clean: true,
24112            verify_retried: false,
24113            e2e_deferred: false,
24114            e2e_defer_reason: None,
24115            progressed: false,
24116            vote_split: false,
24117            reconsideration: Vec::new(),
24118            verdict: None,
24119        }];
24120        state.gate = vec![CommandOutcome {
24121            command: "test".to_owned(),
24122            code: Some(0),
24123            output_tail: String::new(),
24124            duration_ms: 0,
24125            resource_blocked: false,
24126            ..Default::default()
24127        }];
24128        state.gate_ran = true;
24129        // A first pass through `merge` already pushed and opened this pull
24130        // request; `status` is `Landing` because a previous call into `land`
24131        // parked or was interrupted before it reached a terminal outcome.
24132        state.status = RunStatus::Landing;
24133        state.merge = Some(MergeOutcome {
24134            mode: MergeMode::Pr,
24135            ok: true,
24136            detail: "https://example.invalid/x/y/pull/1".to_owned(),
24137            empty: false,
24138        });
24139
24140        // The Landing-resume shortcut calls `run_land` directly rather than
24141        // through `merge`, which is exactly the call site that used to skip
24142        // `settle_questions` - see the fixture below.
24143        ask_test_home();
24144        // A real resume loads a persisted run; driver ownership is checked
24145        // against that record before the Landing shortcut is entered.
24146        state.save().expect("save landing run");
24147        let store = ask::Questions::open();
24148        let q = ask_open_question(&store, &state.id);
24149
24150        let mut runner = Runner {
24151            state,
24152            roles: ResolvedRoles {
24153                implementers: Vec::new(),
24154                judges: Vec::new(),
24155                reviewers: Vec::new(),
24156                fixer: None,
24157                conductor: conductor(),
24158                implementer_roster: Vec::new(),
24159                judge_roster: Vec::new(),
24160                reviewer_roster: Vec::new(),
24161            },
24162            sem: Arc::new(Semaphore::new(1)),
24163            pause: Pause::new(),
24164            interrupt: Pause::new(),
24165        };
24166
24167        // `execute`, not `merge` directly: the Landing-resume shortcut lives
24168        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
24169        // exactly because `review_loop` would otherwise clobber the marker
24170        // first.
24171        runner.execute().await.expect("execute");
24172
24173        assert_eq!(
24174            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
24175            Some("https://example.invalid/x/y/pull/1"),
24176            "reentry must not push again or open a second pull request over the \
24177             one `land` is already watching"
24178        );
24179        assert_ne!(
24180            runner.state.status,
24181            RunStatus::Landing,
24182            "land could not actually reach the fake pull request, so it must \
24183             have given up rather than left the run silently parked forever"
24184        );
24185        // `land` could not reach the fake pull request, so it gave up into
24186        // `Blocked` - still resumable, so the question must not have been
24187        // swept just because this branch now also calls `settle_questions`.
24188        assert_eq!(runner.state.status, RunStatus::Blocked);
24189        assert!(
24190            store.get(&q.id).unwrap().status.open(),
24191            "Blocked is still alive; settle_questions must have been a no-op here"
24192        );
24193    }
24194
24195    fn state_with_round(round: ReviewRound) -> RunState {
24196        let mut s = RunState::new(
24197            PathBuf::from("/repo"),
24198            "main".to_owned(),
24199            "abc1234".to_owned(),
24200            "add retries".to_owned(),
24201            Config::default(),
24202        );
24203        s.reviews = vec![round];
24204        s
24205    }
24206
24207    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
24208        crate::verdict::Finding {
24209            id: id.to_owned(),
24210            severity,
24211            file: None,
24212            line: None,
24213            title: title.to_owned(),
24214            detail: String::new(),
24215        }
24216    }
24217
24218    #[test]
24219    fn pr_body_names_open_findings_and_declined_ones() {
24220        let round = ReviewRound {
24221            round: 2,
24222            head: "deadbee".to_owned(),
24223            verified_head: None,
24224            verified_at: None,
24225            reviews: vec![ReviewRecord {
24226                attempts: 0,
24227                reviewer: 1,
24228                agent: "alpha".to_owned(),
24229                summary: String::new(),
24230                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
24231                vote: None,
24232                failed: None,
24233                duration_ms: 0,
24234            }],
24235            e2e: vec![CommandOutcome {
24236                command: "cargo test".to_owned(),
24237                code: Some(0),
24238                output_tail: String::new(),
24239                duration_ms: 0,
24240                resource_blocked: false,
24241                ..Default::default()
24242            }],
24243            verify_retried: false,
24244            e2e_deferred: false,
24245            e2e_defer_reason: None,
24246            fix: Some(FixRecord {
24247                agent: "alpha".to_owned(),
24248                addressed: Vec::new(),
24249                rejected: vec![crate::verdict::Rejection {
24250                    id: "R1-1-1".to_owned(),
24251                    why: "not reachable from any caller".to_owned(),
24252                }],
24253                notes: String::new(),
24254                committed: true,
24255                failed: None,
24256                duration_ms: 0,
24257                continuation: None,
24258            }),
24259            blocking: 0,
24260            answered: 1,
24261            expected: 1,
24262            clean: false,
24263            progressed: true,
24264            vote_split: false,
24265            reconsideration: Vec::new(),
24266            verdict: None,
24267        };
24268        let state = state_with_round(round);
24269        let body = pr_message(&state, 'A').body;
24270
24271        assert!(body.contains("add retries"), "the task must still be there");
24272        assert!(body.contains("R2-1-1"), "{body}");
24273        assert!(!body.contains("unused import"), "{body}");
24274        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
24275        assert!(
24276            !body.contains("not reachable from any caller"),
24277            "the reason it was declined: {body}"
24278        );
24279    }
24280
24281    #[test]
24282    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
24283        let round = ReviewRound {
24284            round: 1,
24285            head: "deadbee".to_owned(),
24286            verified_head: None,
24287            verified_at: None,
24288            reviews: vec![ReviewRecord {
24289                attempts: 0,
24290                reviewer: 1,
24291                agent: "alpha".to_owned(),
24292                summary: String::new(),
24293                findings: Vec::new(),
24294                vote: None,
24295                failed: None,
24296                duration_ms: 0,
24297            }],
24298            e2e: Vec::new(),
24299            verify_retried: false,
24300            e2e_deferred: false,
24301            e2e_defer_reason: None,
24302            fix: None,
24303            blocking: 0,
24304            answered: 1,
24305            expected: 1,
24306            clean: true,
24307            progressed: false,
24308            vote_split: false,
24309            reconsideration: Vec::new(),
24310            verdict: None,
24311        };
24312        let state = state_with_round(round);
24313        let body = pr_message(&state, 'A').body;
24314        assert!(!body.contains("Open review findings"), "{body}");
24315        assert!(!body.contains("Declined"), "{body}");
24316    }
24317
24318    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
24319        let mut state = RunState::new(
24320            PathBuf::from("/repo"),
24321            "main".to_owned(),
24322            "abc1234".to_owned(),
24323            instruction.to_owned(),
24324            Config::default(),
24325        );
24326        // These fixtures test execution flow, independent of host disk capacity.
24327        state.config.disk.min_free_bytes = 0;
24328        state.candidates.push(Candidate {
24329            index: 0,
24330            label: 'A',
24331            agent: "alpha".to_owned(),
24332            branch: "magi/x/A".to_owned(),
24333            worktree: PathBuf::from("/wt"),
24334            summary: summary.to_owned(),
24335            stat: String::new(),
24336            files: 1,
24337            commits: 1,
24338            empty: false,
24339            failed: None,
24340            verified_noop: None,
24341            folded: false,
24342            duration_ms: 0,
24343        });
24344        state
24345    }
24346
24347    fn review_state(subjects: &[&str]) -> RunState {
24348        let mut state = state_with_summary(
24349            "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",
24350            "",
24351        );
24352        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24353        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24354        state
24355    }
24356
24357    /// A branch rebased onto a main that moved past the recorded
24358    /// `base_commit` is titled from its own first commit, never main's.
24359    #[tokio::test]
24360    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24361        ask_test_home();
24362        let tmp = tempfile::tempdir().unwrap();
24363        let repo = tmp.path().join("repo");
24364        std::fs::create_dir_all(&repo).unwrap();
24365        init_repo(&repo);
24366        let origin = tmp.path().join("origin.git");
24367        let g = |dir: &Path, args: &[&str]| {
24368            let out = std::process::Command::new("git")
24369                .args(args)
24370                .current_dir(dir)
24371                .quiet()
24372                .output()
24373                .expect("spawn git");
24374            assert!(
24375                out.status.success(),
24376                "git {args:?}: {}",
24377                String::from_utf8_lossy(&out.stderr)
24378            );
24379        };
24380        g(
24381            tmp.path(),
24382            &[
24383                "clone",
24384                "--bare",
24385                "-q",
24386                repo.to_str().unwrap(),
24387                origin.to_str().unwrap(),
24388            ],
24389        );
24390        g(
24391            &repo,
24392            &["remote", "add", "origin", origin.to_str().unwrap()],
24393        );
24394        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24395
24396        // Main moves on; the branch is built on top of the new main.
24397        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24398        g(&repo, &["add", "-A"]);
24399        g(
24400            &repo,
24401            &["commit", "-q", "-m", "chore(deps): update a crate"],
24402        );
24403        g(&repo, &["push", "-q", "origin", "main"]);
24404        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24405        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24406        g(&repo, &["add", "-A"]);
24407        g(
24408            &repo,
24409            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24410        );
24411        g(&repo, &["checkout", "-q", "main"]);
24412
24413        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24414        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24415        // Without a readable tracking ref the recorded base's merge base is used.
24416        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24417        assert_eq!(fallback, c1);
24418
24419        let mut state = review_state(&[
24420            "chore(deps): update a crate",
24421            "fix(daemon): apply a chosen action",
24422        ]);
24423        state.repo = repo.clone();
24424        state.base_branch = "main".to_owned();
24425        state.base_commit = c1;
24426        refresh_reviewed_commits(&mut state, "feat/own").await;
24427        assert_eq!(
24428            state.reviewed_commits,
24429            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24430        );
24431        assert_eq!(
24432            review_title(&state).as_deref(),
24433            Some("fix(daemon): apply a chosen action")
24434        );
24435        assert_eq!(
24436            leaked_subjects(&state, "feat/own").await,
24437            Some(vec!["chore(deps): update a crate".to_owned()])
24438        );
24439        // A stale tracking ref is still used when the fetch fails, but the
24440        // leak list is withheld.
24441        state.config.merge.remote = "nowhere".to_owned();
24442        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24443    }
24444
24445    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24446    /// with `origin/main` one commit behind it, and a summarizing agent that
24447    /// prints whatever `reply` holds.
24448    struct SummaryFixture {
24449        _tmp: tempfile::TempDir,
24450        repo: PathBuf,
24451        reply: PathBuf,
24452        runner: Runner,
24453    }
24454
24455    fn summary_fixture() -> SummaryFixture {
24456        ask_test_home();
24457        let tmp = tempfile::tempdir().unwrap();
24458        let repo = tmp.path().join("repo");
24459        std::fs::create_dir_all(&repo).unwrap();
24460        init_repo(&repo);
24461        let origin = tmp.path().join("origin.git");
24462        let g = |args: &[&str]| {
24463            let out = std::process::Command::new("git")
24464                .args(args)
24465                .current_dir(&repo)
24466                .quiet()
24467                .output()
24468                .expect("spawn git");
24469            assert!(
24470                out.status.success(),
24471                "git {args:?}: {}",
24472                String::from_utf8_lossy(&out.stderr)
24473            );
24474        };
24475        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24476        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24477        g(&["push", "-q", "origin", "main"]);
24478        g(&["checkout", "-q", "-b", "feat/own"]);
24479        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24480        g(&["add", "-A"]);
24481        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24482        let reply = tmp.path().join("reply.txt");
24483        std::fs::write(
24484            &reply,
24485            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24486        )
24487        .unwrap();
24488        let mut runner = runner_at(RunStatus::Gating);
24489        let mut state = review_state(&["feat(own): add the own file"]);
24490        state.repo = repo.clone();
24491        state.base_branch = "main".to_owned();
24492        state.candidates[0].branch = "feat/own".to_owned();
24493        state.candidates[0].worktree = repo.clone();
24494        let mut author = spec("alpha");
24495        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24496        author
24497            .env
24498            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24499        state.config.agents = vec![author];
24500        runner.state = state;
24501        SummaryFixture {
24502            _tmp: tmp,
24503            repo,
24504            reply,
24505            runner,
24506        }
24507    }
24508
24509    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24510        let winner = f.runner.state.candidates[0].clone();
24511        f.runner
24512            .guarded_pr_message(&winner, None, true)
24513            .await
24514            .unwrap()
24515            .expect("an English description never parks")
24516    }
24517
24518    fn clean_round_with_minor_findings() -> ReviewRound {
24519        let mut round = passing_round(2, None);
24520        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24521        round.reviews = vec![ReviewRecord {
24522            attempts: 0,
24523            reviewer: 1,
24524            agent: "alpha".into(),
24525            summary: "内部レビュー".into(),
24526            findings: vec![
24527                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24528                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24529            ],
24530            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24531            failed: None,
24532            duration_ms: 0,
24533        }];
24534        round
24535    }
24536
24537    #[tokio::test]
24538    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24539        for review_only in [false, true] {
24540            let mut f = summary_fixture();
24541            if !review_only {
24542                f.runner.state.candidates[0].agent = "alpha".into();
24543            }
24544            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24545            assert!(f.runner.state.reviews[0].clean);
24546            assert!(f.runner.state.reviews[0].fix.is_none());
24547            assert!(f.runner.state.open_findings().is_empty());
24548            assert_eq!(
24549                crate::pr_outcome::required_finding_ids(&f.runner.state),
24550                ["R2-1-1", "R2-1-2"]
24551            );
24552            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24553            let evidence = crate::pr_outcome::summary_evidence(
24554                &f.runner.state,
24555                crate::pr_outcome::FinalHead::At(&head),
24556            );
24557            assert!(
24558                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24559            );
24560            // The ordinary reply omits both IDs: no cached description is adopted.
24561            let omitted = posted(&mut f).await;
24562            assert!(omitted.body.contains("No description"));
24563            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24564            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24565            assert!(f.runner.state.change_summary.is_none());
24566            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();
24567            let described = posted(&mut f).await;
24568            assert!(described.body.contains("improve documentation for callers"));
24569            assert!(described.body.contains("remaining edge case"));
24570            assert!(described.body.contains("## Open review findings"));
24571            assert!(!described.body.contains("未修正"));
24572        }
24573    }
24574
24575    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24576        let mut f = summary_fixture();
24577        if !review_only {
24578            f.runner.state.candidates[0].agent = "alpha".into();
24579        }
24580        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24581        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24582        fixed
24583            .fix
24584            .as_mut()
24585            .unwrap()
24586            .rejected
24587            .push(crate::verdict::Rejection {
24588                id: "R1-1-1".into(),
24589                why: "呼び出されないコードのため辞退".into(),
24590            });
24591        let mut clean = clean_round_with_minor_findings();
24592        clean.verified_head = Some(head.clone());
24593        f.runner.state.reviews = vec![fixed, clean];
24594        ok_gate(&mut f.runner.state, Some(&head));
24595        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24596        f.runner.state.config.agents.push(scripted("beta", reply));
24597        f.runner.state.config.roles.language_judge =
24598            Some(crate::config::AgentChoice::One("beta".into()));
24599        f
24600    }
24601
24602    #[tokio::test]
24603    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24604        for review_only in [false, true] {
24605            let mut f = rewrite_fixture_with_findings(review_only,
24606                "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;
24607            let m = posted(&mut f).await;
24608            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24609            let expected =
24610                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24611            assert!(m.body.contains(&expected));
24612            assert!(m.body.contains("## Review rounds"));
24613            assert!(
24614                m.body
24615                    .contains("Gate (`verify.gate`): passed on the final commit")
24616            );
24617            assert!(
24618                m.body
24619                    .contains("Tests (`verify.e2e`): passed on the final commit")
24620            );
24621            let c = f.runner.state.change_summary.as_ref().unwrap();
24622            assert!(
24623                m.body
24624                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24625            );
24626            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24627            assert!(crate::pr_outcome::covers_required_findings(
24628                &f.runner.state,
24629                &m.body
24630            ));
24631            assert!(m.body.contains("documentation remains incomplete"));
24632            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24633            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24634            assert!(f.runner.state.github_text.is_none());
24635        }
24636    }
24637
24638    #[tokio::test]
24639    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24640        for review_only in [false, true] {
24641            for reply in [
24642                "TITLE: fix: public description\nA short English description.",
24643                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24644            ] {
24645                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24646                let winner = f.runner.state.candidates[0].clone();
24647                let posted = f
24648                    .runner
24649                    .guarded_pr_message(&winner, None, true)
24650                    .await
24651                    .unwrap();
24652                assert!(posted.is_none());
24653                assert!(f.runner.state.parked);
24654                let withheld = f.runner.state.github_text.as_ref().unwrap();
24655                assert!(
24656                    withheld.rewrite.is_none(),
24657                    "an incomplete rewrite must not be selectable"
24658                );
24659                let q = ask::Questions::open()
24660                    .get(withheld.question.as_ref().unwrap())
24661                    .unwrap();
24662                assert!(
24663                    !q.choices
24664                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24665                );
24666                assert!(
24667                    q.detail.contains("R1-1-1")
24668                        && q.detail.contains("R2-1-1")
24669                        && q.detail.contains("R2-1-2")
24670                );
24671            }
24672        }
24673    }
24674
24675    #[tokio::test]
24676    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24677        for review_only in [false, true] {
24678            let mut f = summary_fixture();
24679            if !review_only {
24680                f.runner.state.candidates[0].agent = "alpha".into();
24681            }
24682            f.runner.state.instruction = "内部タスクの説明".into();
24683            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24684            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24685            f.runner.state.reviews = vec![
24686                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24687                round_with_notes(2, Some("二回目の内部修正報告です。")),
24688                passing_round(3, Some(&head)),
24689            ];
24690            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24691            ok_gate(&mut f.runner.state, Some(&head));
24692            let captured = f.repo.join("public-prompt.txt");
24693            let author = &mut f.runner.state.config.agents[0];
24694            author.command = vec![
24695                "sh".into(),
24696                "-c".into(),
24697                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24698            ];
24699            author.env.insert(
24700                "PROMPT_FILE".into(),
24701                captured.to_string_lossy().into_owned(),
24702            );
24703            let m = posted(&mut f).await;
24704            assert!(m.body.contains("Adds `own.txt`"));
24705            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24706            assert!(m.body.contains("R1-1-1"));
24707            assert!(
24708                m.body
24709                    .contains("Gate (`verify.gate`): passed on the final commit")
24710            );
24711            assert!(
24712                m.body
24713                    .contains("Tests (`verify.e2e`): passed on the final commit")
24714            );
24715            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24716            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24717            let prompt = std::fs::read_to_string(captured).unwrap();
24718            assert!(prompt.contains(&format!(
24719                "git diff {} {head}",
24720                f.runner.state.change_summary.as_ref().unwrap().base
24721            )));
24722            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24723            assert_eq!(
24724                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24725                "二回目の内部修正報告です。"
24726            );
24727        }
24728    }
24729
24730    #[tokio::test]
24731    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24732        for review_only in [false, true] {
24733            let mut f = summary_fixture();
24734            if !review_only {
24735                f.runner.state.candidates[0].agent = "alpha".into();
24736            }
24737            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24738            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24739            std::fs::write(&f.reply, "no usable description").unwrap();
24740            let failed = posted(&mut f).await;
24741            assert!(
24742                failed
24743                    .body
24744                    .contains("No description of what this change does could be generated")
24745            );
24746            assert!(failed.body.is_ascii());
24747            assert!(f.runner.state.github_text.is_none());
24748            assert!(f.runner.state.change_summary.is_none());
24749            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24750            let evidence = crate::pr_outcome::summary_evidence(
24751                &f.runner.state,
24752                crate::pr_outcome::FinalHead::At(&head),
24753            );
24754            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24755            assert!(
24756                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24757                    .exists()
24758            );
24759            f.runner.state =
24760                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24761            std::fs::write(
24762                &f.reply,
24763                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24764            )
24765            .unwrap();
24766            let retried = posted(&mut f).await;
24767            assert!(retried.body.contains("Adds the committed own file."));
24768            assert_eq!(
24769                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24770                "日本語の修正報告"
24771            );
24772        }
24773    }
24774
24775    #[tokio::test]
24776    async fn same_head_verification_and_findings_invalidate_public_prose() {
24777        let mut f = summary_fixture();
24778        posted(&mut f).await;
24779        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24780        let original = f
24781            .runner
24782            .state
24783            .change_summary
24784            .as_ref()
24785            .unwrap()
24786            .evidence
24787            .clone();
24788        ok_gate(&mut f.runner.state, Some(&head));
24789        std::fs::write(
24790            &f.reply,
24791            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24792        )
24793        .unwrap();
24794        let verified = posted(&mut f).await;
24795        assert!(verified.body.contains("now verified"));
24796        assert_ne!(
24797            f.runner.state.change_summary.as_ref().unwrap().evidence,
24798            original
24799        );
24800        let mut round = round_with_notes(1, Some("内部報告"));
24801        round.reviews.push(ReviewRecord {
24802            attempts: 0,
24803            reviewer: 1,
24804            agent: "alpha".into(),
24805            summary: "内部レビュー".into(),
24806            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24807            vote: None,
24808            failed: None,
24809            duration_ms: 0,
24810        });
24811        round
24812            .fix
24813            .as_mut()
24814            .unwrap()
24815            .rejected
24816            .push(crate::verdict::Rejection {
24817                id: "R1-1-1".into(),
24818                why: "呼び出し元から到達できない".into(),
24819            });
24820        f.runner.state.reviews = vec![round];
24821        // A description omitting the required ID is unusable, even with a title.
24822        let omitted = posted(&mut f).await;
24823        assert!(omitted.body.contains("No description"));
24824        assert!(omitted.body.contains("R1-1-1"));
24825        assert!(!omitted.body.contains("到達"));
24826        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();
24827        let described = posted(&mut f).await;
24828        assert!(described.body.contains("unreachable from callers"));
24829        assert!(described.body.contains("R1-1-1"));
24830        assert!(!described.body.contains("到達"));
24831        let evidence = f
24832            .runner
24833            .state
24834            .change_summary
24835            .as_ref()
24836            .unwrap()
24837            .evidence
24838            .clone();
24839        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24840        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24841        assert!(posted(&mut f).await.body.contains("rationale updated"));
24842        assert_ne!(
24843            f.runner.state.change_summary.as_ref().unwrap().evidence,
24844            evidence
24845        );
24846        // Old serialized summaries have no evidence fingerprint and must regenerate.
24847        f.runner
24848            .state
24849            .change_summary
24850            .as_mut()
24851            .unwrap()
24852            .evidence
24853            .clear();
24854        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24855        assert!(posted(&mut f).await.body.contains("current specification"));
24856    }
24857
24858    #[tokio::test]
24859    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24860        let mut f = summary_fixture();
24861        let m = posted(&mut f).await;
24862        assert_eq!(m.title, "feat(own): add the own file");
24863        assert!(
24864            m.body
24865                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24866            "{}",
24867            m.body
24868        );
24869        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24870        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24871        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24872        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24873        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24874        let kept = f.runner.state.change_summary.as_ref().unwrap();
24875        assert_eq!(
24876            (kept.head.as_str(), kept.base.as_str()),
24877            (head.as_str(), base.as_str())
24878        );
24879        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24880    }
24881
24882    #[tokio::test]
24883    async fn review_only_summary_receives_the_configured_github_language() {
24884        let mut f = summary_fixture();
24885        f.runner.state.config.graph.github_language = "ja".into();
24886        let captured = f.repo.join("summary-prompt.txt");
24887        let author = &mut f.runner.state.config.agents[0];
24888        author.command = vec![
24889            "sh".into(),
24890            "-c".into(),
24891            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24892        ];
24893        author.env.insert(
24894            "PROMPT_FILE".into(),
24895            captured.to_string_lossy().into_owned(),
24896        );
24897        std::fs::write(
24898            &f.reply,
24899            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24900        )
24901        .unwrap();
24902        let m = posted(&mut f).await;
24903        let prompt = std::fs::read_to_string(captured).unwrap();
24904        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24905        assert!(!prompt.contains("in English"));
24906        assert_eq!(m.title, "feat(own): ファイルを追加");
24907        assert!(m.body.contains("own.txt を追加します。"));
24908    }
24909
24910    #[tokio::test]
24911    async fn review_fixes_come_after_the_whole_change_summary() {
24912        let mut f = summary_fixture();
24913        f.runner.state.reviews = vec![
24914            round_with_notes(1, Some("handled the PATH case")),
24915            round_with_notes(2, None),
24916        ];
24917        let m = posted(&mut f).await;
24918        let summary = m.body.find("## Summary").expect("summary");
24919        let fixes = m.body.find("## Review rounds").expect("review rounds");
24920        assert!(summary < fixes, "{}", m.body);
24921        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24922        assert!(m.body.contains("## Final verification"), "{}", m.body);
24923    }
24924
24925    #[tokio::test]
24926    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24927        let mut f = summary_fixture();
24928        let first = posted(&mut f).await;
24929        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24930        // The same head reuses the record: a different reply is not read.
24931        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24932        let again = posted(&mut f).await;
24933        assert_eq!((again.title, again.body), (first.title, first.body));
24934
24935        let g = |args: &[&str]| {
24936            let out = std::process::Command::new("git")
24937                .args(args)
24938                .current_dir(&f.repo)
24939                .quiet()
24940                .output()
24941                .expect("spawn git");
24942            assert!(out.status.success(), "git {args:?}");
24943        };
24944        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24945        g(&["add", "-A"]);
24946        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24947        let second = posted(&mut f).await;
24948        let kept = f.runner.state.change_summary.clone().unwrap();
24949        assert_ne!(kept.head, first_head);
24950        assert!(second.body.contains("Not read yet."), "{}", second.body);
24951        assert!(!second.body.contains("so the first summary is read"));
24952        assert_eq!(second.title, "feat(own): other");
24953    }
24954
24955    #[tokio::test]
24956    async fn an_unavailable_summary_is_stated_and_never_invented() {
24957        let mut f = summary_fixture();
24958        std::fs::write(&f.reply, "no title line here").unwrap();
24959        let m = posted(&mut f).await;
24960        assert!(
24961            m.body
24962                .contains("No description of what this change does could be generated"),
24963            "{}",
24964            m.body
24965        );
24966        assert!(m.body.contains("internal reports remain in local records"));
24967        assert!(f.runner.state.change_summary.is_none());
24968        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24969        // A preview asks nobody and claims nothing.
24970        let winner = f.runner.state.candidates[0].clone();
24971        let preview = f
24972            .runner
24973            .guarded_pr_message(&winner, None, false)
24974            .await
24975            .unwrap()
24976            .unwrap();
24977        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24978    }
24979
24980    #[test]
24981    fn pr_message_review_single_commit_uses_its_subject() {
24982        let state = review_state(&["feat(nats): per-role user"]);
24983        let m = pr_message(&state, 'A');
24984        assert_eq!(m.title, "feat(nats): per-role user");
24985        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24986        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24987    }
24988
24989    #[test]
24990    fn pr_message_review_multi_commit_takes_the_oldest() {
24991        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24992        let m = pr_message(&state, 'A');
24993        assert_eq!(m.title, "feat: the change");
24994        for s in ["feat: the change", "fix: typo", "fix: again"] {
24995            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24996        }
24997    }
24998
24999    #[test]
25000    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
25001        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
25002            let mut state = review_state(&[first, "fix: later fixup"]);
25003            state.candidates[0].branch = "機能/ログイン".to_owned();
25004            let m = pr_message(&state, 'A');
25005            assert!(
25006                m.title.starts_with("chore: land candidate A of run"),
25007                "{}",
25008                m.title
25009            );
25010        }
25011    }
25012
25013    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
25014        BranchFacts {
25015            commits: commits
25016                .iter()
25017                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
25018                .collect(),
25019            stat: stat.to_owned(),
25020        }
25021    }
25022
25023    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
25024        let mut r = review_round(true, 0, 1, 1, true, true);
25025        r.round = round;
25026        r.fix = notes.map(|n| FixRecord {
25027            agent: "fixer".to_owned(),
25028            addressed: Vec::new(),
25029            rejected: Vec::new(),
25030            notes: n.to_owned(),
25031            committed: true,
25032            failed: None,
25033            duration_ms: 0,
25034            continuation: None,
25035        });
25036        r
25037    }
25038
25039    #[test]
25040    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
25041        let state = review_state(&["ignored"]);
25042        let f = facts(
25043            &[
25044                (
25045                    "fix(login): resolve PATH on macOS",
25046                    "Login shells skip rc files.",
25047                ),
25048                ("fix: address review", ""),
25049            ],
25050            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
25051        );
25052        let m = pr_message_with(&state, 'A', Some(&f));
25053        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
25054        assert!(
25055            m.body
25056                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
25057            "{}",
25058            m.body
25059        );
25060        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
25061        assert!(m.body.contains("## Diff stat"), "{}", m.body);
25062        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
25063        for banned in [
25064            "Review the work already",
25065            "no task statement",
25066            "Original task",
25067        ] {
25068            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
25069        }
25070        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
25071    }
25072
25073    #[test]
25074    fn pr_message_review_truncates_a_huge_first_commit_body() {
25075        let state = review_state(&["ignored"]);
25076        let f = facts(
25077            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
25078            "s",
25079        );
25080        let m = pr_message_with(&state, 'A', Some(&f));
25081        assert!(m.body.len() < 30_000, "{}", m.body.len());
25082        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
25083        assert!(
25084            m.body.contains("- ... 1 more commit(s)"),
25085            "{}",
25086            m.body.len()
25087        );
25088        assert!(m.body.ends_with("magi:candidate-a\n"));
25089    }
25090
25091    #[test]
25092    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
25093        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
25094        assert_eq!(m.title, "feat: x");
25095        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
25096        assert!(!m.body.contains("Diff stat"), "{}", m.body);
25097        assert!(!m.body.contains("no task statement"), "{}", m.body);
25098    }
25099
25100    #[test]
25101    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
25102        let mut state = review_state(&["日本語の件名"]);
25103        state.candidates[0].branch = "fix/macos-login-path".to_owned();
25104        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
25105        state.candidates[0].branch = "機能/ログイン".to_owned();
25106        assert!(
25107            pr_message(&state, 'A')
25108                .title
25109                .starts_with("chore: land candidate A")
25110        );
25111    }
25112
25113    #[test]
25114    fn pr_message_review_fixes_survive_a_clean_final_round() {
25115        let mut state = review_state(&["feat: x"]);
25116        state.reviews = vec![
25117            round_with_notes(1, Some("handled the PATH case")),
25118            round_with_notes(2, None),
25119        ];
25120        let body = pr_message(&state, 'A').body;
25121        assert!(
25122            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
25123            "{body}"
25124        );
25125        assert!(body.contains("### Round 1"), "{body}");
25126
25127        state.reviews = vec![
25128            round_with_notes(1, Some("first fix")),
25129            round_with_notes(2, Some("")),
25130            round_with_notes(3, Some("second fix")),
25131            round_with_notes(4, None),
25132        ];
25133        let body = pr_message(&state, 'A').body;
25134        assert!(
25135            body.contains("### Round 1") && !body.contains("first fix"),
25136            "{body}"
25137        );
25138        assert!(
25139            body.contains("### Round 3") && !body.contains("second fix"),
25140            "{body}"
25141        );
25142        assert!(body.contains("### Round 2"), "{body}");
25143    }
25144
25145    const FINAL: &str = "abcdef1234567890";
25146
25147    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
25148        let mut r = round_with_notes(round, None);
25149        r.verified_head = verified.map(str::to_owned);
25150        r
25151    }
25152
25153    fn ok_gate(state: &mut RunState, head: Option<&str>) {
25154        state.gate = vec![CommandOutcome {
25155            command: "gate".to_owned(),
25156            code: Some(0),
25157            output_tail: String::new(),
25158            duration_ms: 0,
25159            resource_blocked: false,
25160            ..Default::default()
25161        }];
25162        state.gate_ran = true;
25163        state.gate_head = head.map(str::to_owned);
25164    }
25165
25166    fn body_at(state: &RunState) -> String {
25167        pr_message_raw(
25168            state,
25169            'A',
25170            None,
25171            crate::pr_outcome::FinalHead::At(FINAL),
25172            ChangeNote::NotAsked,
25173        )
25174        .body
25175    }
25176
25177    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
25178
25179    #[test]
25180    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
25181        let mut state = review_state(&["feat: x"]);
25182        state.reviews = vec![
25183            round_with_notes(1, Some(SANDBOXED)),
25184            passing_round(2, Some(FINAL)),
25185        ];
25186        ok_gate(&mut state, Some(FINAL));
25187        let body = body_at(&state);
25188        assert!(!body.contains("Handled the PATH case."), "{body}");
25189        assert!(!body.contains("could not commit"), "{body}");
25190        assert!(!body.contains("could not run"), "{body}");
25191        assert!(
25192            body.contains("The fix is committed on the branch"),
25193            "{body}"
25194        );
25195        assert!(!body.contains("sandbox"), "{body}");
25196        assert!(
25197            body.contains("Tests (`verify.e2e`): passed on the final commit"),
25198            "{body}"
25199        );
25200        assert!(
25201            body.contains("Gate (`verify.gate`): passed on the final commit"),
25202            "{body}"
25203        );
25204        // The raw report is untouched in the record.
25205        assert!(
25206            state.reviews[0]
25207                .fix
25208                .as_ref()
25209                .unwrap()
25210                .notes
25211                .contains("could not commit")
25212        );
25213    }
25214
25215    #[test]
25216    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
25217        let mut state = review_state(&["feat: x"]);
25218        let mut r1 = round_with_notes(1, Some(SANDBOXED));
25219        r1.fix.as_mut().unwrap().committed = false;
25220        let mut r2 = passing_round(2, Some(FINAL));
25221        r2.e2e[0].code = Some(1);
25222        state.reviews = vec![r1, r2];
25223        let body = body_at(&state);
25224        assert!(!body.contains("could not commit"), "{body}");
25225        assert!(!body.contains("could not run"), "{body}");
25226        assert!(body.contains("This round produced no commit"), "{body}");
25227        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
25228        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
25229        assert!(!body.contains("passed"), "{body}");
25230    }
25231
25232    #[test]
25233    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
25234        let mut state = review_state(&["feat: x"]);
25235        state.reviews = vec![
25236            round_with_notes(1, Some(SANDBOXED)),
25237            passing_round(2, Some("0123456789abcdef")),
25238        ];
25239        ok_gate(&mut state, Some("0123456789abcdef"));
25240        let body = body_at(&state);
25241        assert!(!body.contains("HTTP tests could not run"), "{body}");
25242        // The commit claim is still settled by the structured record.
25243        assert!(!body.contains("could not commit"), "{body}");
25244        assert!(
25245            body.contains("passed on an earlier commit (`0123456`)"),
25246            "{body}"
25247        );
25248        assert!(!body.contains("passed on the final commit"), "{body}");
25249
25250        // A gate recorded before `gate_head` existed is "not recorded".
25251        ok_gate(&mut state, None);
25252        let body = body_at(&state);
25253        assert!(
25254            body.contains("passed on a commit that was not recorded"),
25255            "{body}"
25256        );
25257    }
25258
25259    #[test]
25260    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
25261        let state = state_with_summary(
25262            "add retries to the client",
25263            "TITLE: feat: retries\n\nDid it.",
25264        );
25265        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
25266        assert_eq!(m.title, "feat: retries");
25267        assert!(
25268            m.body.contains("<summary>Original task</summary>"),
25269            "{}",
25270            m.body
25271        );
25272        assert!(!m.body.contains("Commits under review"), "{}", m.body);
25273        assert!(
25274            m.body
25275                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
25276            "{}",
25277            m.body
25278        );
25279    }
25280
25281    #[test]
25282    fn pr_message_review_bounds_a_long_english_subject() {
25283        let long = format!("feat: {}", "word ".repeat(100));
25284        let m = pr_message(&review_state(&[&long]), 'A');
25285        assert!(m.title.starts_with("feat: word"), "{}", m.title);
25286        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25287    }
25288
25289    #[test]
25290    fn pr_message_implementation_run_is_unchanged_by_review_support() {
25291        let state = state_with_summary("add retries\n\ndetails", "- did some things");
25292        let m = pr_message(&state, 'A');
25293        assert_eq!(m.title, "add retries");
25294        assert!(m.body.contains("<summary>Original task</summary>"));
25295        assert!(!m.body.contains("Commits under review"));
25296        assert_eq!(landing_subject_source(&state), state.instruction);
25297    }
25298
25299    #[test]
25300    fn review_run_squash_subject_is_the_change_not_the_prompt() {
25301        let state = review_state(&["feat: the change", "fix: typo"]);
25302        let source = landing_subject_source(&state);
25303        assert_eq!(land::merge_subject("", &source), "feat: the change");
25304        assert_eq!(
25305            land::merge_subject("magi: candidate A (uncommitted work)", &source),
25306            "feat: the change"
25307        );
25308        // An operator's rename still wins.
25309        assert_eq!(
25310            land::merge_subject("feat: renamed by hand", &source),
25311            "feat: renamed by hand"
25312        );
25313        let blank = review_state(&["日本語"]);
25314        assert!(
25315            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
25316        );
25317    }
25318
25319    #[test]
25320    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
25321        let state = review_state(&["feat: the change"]);
25322        let source = landing_subject_source(&state);
25323        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
25324        assert_eq!(
25325            land::merge_subject(landing_title(&state, old), &source),
25326            "feat: the change"
25327        );
25328        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25329        let task = state_with_summary("add retries", "");
25330        assert_eq!(landing_title(&task, old), old);
25331    }
25332
25333    #[test]
25334    fn pr_message_describes_the_change_not_the_task() {
25335        let state = state_with_summary(
25336            "今回やってほしいこと: results projector を直す",
25337            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25338        );
25339        let m = pr_message(&state, 'A');
25340        assert_eq!(m.title, "fix(web): batch the runs list reads");
25341        assert!(
25342            m.body.starts_with("## Summary\n\n- reads run.json once"),
25343            "{}",
25344            m.body
25345        );
25346        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25347        let task_at = m.body.find("今回やってほしいこと").unwrap();
25348        let details_at = m.body.find("<details>").unwrap();
25349        assert!(
25350            details_at < task_at,
25351            "the task lives inside <details>: {}",
25352            m.body
25353        );
25354        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25355        assert!(m.body.contains("magi:candidate-a"));
25356    }
25357
25358    #[test]
25359    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25360        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25361        let m = pr_message(&state, 'A');
25362        assert_eq!(m.title, "add retries");
25363        assert!(
25364            m.body.contains("## Summary\n\n- did some things"),
25365            "{}",
25366            m.body
25367        );
25368
25369        let none = RunState::new(
25370            PathBuf::from("/repo"),
25371            "main".to_owned(),
25372            "abc1234".to_owned(),
25373            "add retries".to_owned(),
25374            Config::default(),
25375        );
25376        let m = pr_message(&none, 'A');
25377        assert_eq!(m.title, "add retries");
25378        assert!(!m.body.contains("## Summary"), "{}", m.body);
25379    }
25380
25381    #[test]
25382    fn pr_message_refuses_the_candidate_commit_subject() {
25383        for bad in [
25384            "TITLE: magi: candidate A (uncommitted work)",
25385            "TITLE: chore: stuff (uncommitted work)",
25386            "TITLE:   ",
25387        ] {
25388            let state = state_with_summary("add retries", bad);
25389            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25390        }
25391    }
25392
25393    #[test]
25394    fn pr_message_bounds_a_very_long_task_and_title() {
25395        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25396        let state = state_with_summary(&long, "- nothing");
25397        let m = pr_message(&state, 'A');
25398        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25399        assert!(!m.title.contains('\n'));
25400
25401        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25402        let m = pr_message(&state, 'A');
25403        assert!(m.title.starts_with("feat: "));
25404        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25405        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25406    }
25407
25408    fn long_title_of(instruction: &str) -> String {
25409        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25410    }
25411
25412    #[test]
25413    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25414        let first = "Make the landing path keep a readable title for long tasks";
25415        let line = format!(
25416            "{first}. {}",
25417            "And then keep going with more words ".repeat(20)
25418        );
25419        let t = long_title_of(&line);
25420        assert_eq!(t, first);
25421        assert!(!t.starts_with("chore: land"));
25422    }
25423
25424    #[test]
25425    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25426        let line = "word ".repeat(200);
25427        let t = long_title_of(&line);
25428        assert!(t.ends_with("word..."), "{t}");
25429        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25430    }
25431
25432    #[test]
25433    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25434        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25435            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25436        }
25437    }
25438
25439    #[test]
25440    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25441        let mut state = state_with_summary("再試行を追加する", "- nothing");
25442        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25443        state.config.graph.github_language = "ja".into();
25444        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25445    }
25446
25447    #[test]
25448    fn pr_message_title_limit_is_exact() {
25449        let at = "a".repeat(PR_TITLE_MAX);
25450        assert_eq!(long_title_of(&at), at);
25451        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25452        assert!(over.ends_with("..."), "{over}");
25453        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25454    }
25455
25456    #[test]
25457    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25458        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25459        let t = long_title_of(&line);
25460        assert!(t.ends_with("..."), "{t}");
25461        assert!(t.is_ascii(), "{t}");
25462    }
25463
25464    #[test]
25465    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25466        let line = format!(
25467            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25468            "plus more filler words ".repeat(20)
25469        );
25470        let t = long_title_of(&line);
25471        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25472    }
25473
25474    #[test]
25475    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25476        let line = format!("\n\n# {}", "title words ".repeat(40));
25477        let state = state_with_summary(&line, "- nothing");
25478        let m = pr_message(&state, 'A');
25479        assert!(m.title.starts_with("title words"), "{}", m.title);
25480        assert_eq!(
25481            land::merge_subject(&m.title, &landing_subject_source(&state)),
25482            m.title
25483        );
25484        // An operator's rename wins untouched.
25485        assert_eq!(
25486            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25487            "feat: renamed by hand"
25488        );
25489    }
25490
25491    #[tokio::test]
25492    async fn github_text_rewrite_is_bounded_and_falls_back() {
25493        crate::run::pin_test_home();
25494        for (reply, accepted) in [
25495            (
25496                "TITLE: fix: retries\nAdd retries for failed requests.",
25497                true,
25498            ),
25499            (
25500                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25501                false,
25502            ),
25503            (
25504                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25505                true,
25506            ),
25507            (
25508                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25509                true,
25510            ),
25511            (
25512                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25513                true,
25514            ),
25515            (
25516                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25517                false,
25518            ),
25519            ("TITLE: fix: retries\n", false),
25520        ] {
25521            let dir = tempfile::tempdir().unwrap();
25522            let mut runner = runner_at(RunStatus::Gating);
25523            runner.state = state_with_summary(
25524                "add retries",
25525                "TITLE: fix: retries\n日本語の説明を書きます。",
25526            );
25527            runner.state.repo = dir.path().to_owned();
25528            runner.state.candidates[0].worktree = dir.path().to_owned();
25529            let mut author = spec("alpha");
25530            author.command = vec![
25531                "sh".into(),
25532                "-c".into(),
25533                "printf '%s' \"$REWRITE_REPLY\"".into(),
25534            ];
25535            author.env.insert("REWRITE_REPLY".into(), reply.into());
25536            runner.state.config.agents = vec![author];
25537            seed_public_summary(&mut runner);
25538            let winner = runner.state.candidates[0].clone();
25539            let first = runner
25540                .guarded_pr_message(&winner, None, true)
25541                .await
25542                .unwrap();
25543            let message = if accepted {
25544                first.expect("a passing rewrite never asks")
25545            } else {
25546                // Withheld: the run parks on a question and posts nothing yet.
25547                assert!(first.is_none());
25548                assert!(runner.state.parked);
25549                let store = ask::Questions::open();
25550                let asked: Vec<_> = store
25551                    .list()
25552                    .into_iter()
25553                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25554                    .collect();
25555                assert_eq!(asked.len(), 1);
25556                assert!(!asked[0].detail.contains("secret"));
25557                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25558                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25559                assert_eq!(
25560                    asked[0]
25561                        .choices
25562                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25563                    rewrite.is_some()
25564                );
25565                // Silence: the question lapses and the neutral text is used,
25566                // without a second rewrite call or a second question.
25567                store
25568                    .update(&asked[0].id, |q| {
25569                        q.abandon("test");
25570                        Ok(())
25571                    })
25572                    .unwrap();
25573                let again = runner
25574                    .guarded_pr_message(&winner, None, true)
25575                    .await
25576                    .unwrap()
25577                    .expect("an abandoned question falls back");
25578                let n = store
25579                    .list()
25580                    .into_iter()
25581                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25582                    .count();
25583                assert_eq!(n, 1, "asked once per rejected text");
25584                again
25585            };
25586            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25587            assert!(!message.body.contains("secret"));
25588            assert!(!message.body.contains("prefix"));
25589            assert!(!message.title.contains("secret"));
25590            assert_eq!(
25591                message.body.contains("Add retries for failed requests."),
25592                accepted
25593            );
25594            assert_eq!(
25595                runner.state.seats["github-text-rewrite"].turns, 1,
25596                "only one rewrite invocation"
25597            );
25598            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25599            if accepted {
25600                assert!(runner.state.github_text.is_none());
25601                assert!(!runner.state.parked);
25602                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25603                assert!(message.body.contains("## Final verification"));
25604                assert!(message.body.contains("Evidence: final diff"));
25605                assert!(
25606                    message
25607                        .body
25608                        .contains(&format!("magi:run/{}", runner.state.id))
25609                );
25610            }
25611            if !accepted {
25612                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25613                assert!(
25614                    message
25615                        .body
25616                        .contains(&format!("magi:run/{}", runner.state.id))
25617                );
25618            }
25619        }
25620    }
25621
25622    fn scripted(id: &str, reply: &str) -> AgentSpec {
25623        let mut a = spec(id);
25624        a.command = vec![
25625            "sh".into(),
25626            "-c".into(),
25627            "printf '%s' \"$REWRITE_REPLY\"".into(),
25628        ];
25629        a.env.insert("REWRITE_REPLY".into(), reply.into());
25630        a
25631    }
25632
25633    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25634    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25635
25636    /// Gate tests inject generated public output, not internal reports.
25637    fn seed_public_summary(runner: &mut Runner) {
25638        let repo = &runner.state.repo;
25639        let g = |args: &[&str]| {
25640            let out = std::process::Command::new("git")
25641                .args(args)
25642                .current_dir(repo)
25643                .quiet()
25644                .output()
25645                .unwrap();
25646            assert!(out.status.success(), "git {args:?}");
25647            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25648        };
25649        g(&["init", "-q", "-b", "main"]);
25650        g(&[
25651            "-c",
25652            "user.name=Test",
25653            "-c",
25654            "user.email=test@example.invalid",
25655            "commit",
25656            "-q",
25657            "--allow-empty",
25658            "-m",
25659            "feat: fixture",
25660        ]);
25661        let head = g(&["rev-parse", "HEAD"]);
25662        g(&["update-ref", "refs/remotes/origin/main", &head]);
25663        let evidence = crate::pr_outcome::summary_evidence(
25664            &runner.state,
25665            crate::pr_outcome::FinalHead::At(&head),
25666        );
25667        let generated = &runner.state.candidates[0].summary;
25668        runner.state.change_summary = Some(crate::run::ChangeSummary {
25669            base: head.clone(),
25670            head,
25671            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25672            title: summary_title(generated).unwrap(),
25673            body: summary_without_title(generated),
25674        });
25675    }
25676
25677    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25678        let mut runner = runner_at(RunStatus::Gating);
25679        runner.state = state_with_summary("add retries", JA_SUMMARY);
25680        if review_only {
25681            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25682        }
25683        runner.state.repo = dir.to_owned();
25684        runner.state.candidates[0].worktree = dir.to_owned();
25685        runner.state.config.agents = agents;
25686        seed_public_summary(&mut runner);
25687        runner
25688    }
25689
25690    fn gate_questions(runner: &Runner) -> usize {
25691        ask::Questions::open()
25692            .list()
25693            .into_iter()
25694            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25695            .count()
25696    }
25697
25698    #[tokio::test]
25699    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25700        crate::run::pin_test_home();
25701        let dir = tempfile::tempdir().unwrap();
25702        let mut runner = rewrite_runner(
25703            dir.path(),
25704            true,
25705            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25706        );
25707        runner.state.config.roles.language_judge =
25708            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25709        let winner = runner.state.candidates[0].clone();
25710        let msg = runner
25711            .guarded_pr_message(&winner, None, true)
25712            .await
25713            .unwrap()
25714            .expect("an English rewrite posts without asking");
25715        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25716        assert!(msg.body.contains("<details>kept</details>"));
25717        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25718        assert_eq!(gate_questions(&runner), 0);
25719        assert!(runner.state.github_text.is_none());
25720        assert!(!runner.state.seats.contains_key("impl-A"));
25721        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25722    }
25723
25724    #[tokio::test]
25725    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25726        crate::run::pin_test_home();
25727        let dir = tempfile::tempdir().unwrap();
25728        let mut runner = rewrite_runner(
25729            dir.path(),
25730            false,
25731            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25732        );
25733        runner.state.config.roles.language_judge =
25734            Some(crate::config::AgentChoice::One("beta".into()));
25735        runner.state.seats.insert(
25736            "impl-A".into(),
25737            SeatState::new("impl-A", "alpha", runner.state.seed),
25738        );
25739        let winner = runner.state.candidates[0].clone();
25740        let msg = runner
25741            .guarded_pr_message(&winner, None, true)
25742            .await
25743            .unwrap()
25744            .expect("rewritten");
25745        assert!(msg.body.contains("<details>kept</details>"));
25746        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25747        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25748        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25749    }
25750
25751    #[tokio::test]
25752    async fn rewrite_reuses_a_resumable_implementer_session() {
25753        crate::run::pin_test_home();
25754        let dir = tempfile::tempdir().unwrap();
25755        let mut runner = rewrite_runner(
25756            dir.path(),
25757            false,
25758            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25759        );
25760        runner.state.config.roles.language_judge =
25761            Some(crate::config::AgentChoice::One("beta".into()));
25762        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25763        seat.turns = 1;
25764        runner.state.seats.insert("impl-A".into(), seat);
25765        let winner = runner.state.candidates[0].clone();
25766        runner
25767            .guarded_pr_message(&winner, None, true)
25768            .await
25769            .unwrap()
25770            .expect("rewritten");
25771        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25772        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25773    }
25774
25775    #[tokio::test]
25776    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25777        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25778        // session, was out of quota, and nothing else was asked.
25779        crate::run::pin_test_home();
25780        let dir = tempfile::tempdir().unwrap();
25781        let mut exhausted = spec("alpha");
25782        exhausted.command = vec!["false".into()];
25783        let mut runner = rewrite_runner(
25784            dir.path(),
25785            false,
25786            vec![exhausted, scripted("beta", EN_REWRITE)],
25787        );
25788        // The implementer's own agent is in the role too: it is not asked twice.
25789        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25790            "alpha".into(),
25791            "beta".into(),
25792        ]));
25793        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25794        seat.turns = 1;
25795        runner.state.seats.insert("impl-A".into(), seat);
25796        let winner = runner.state.candidates[0].clone();
25797        let msg = runner
25798            .guarded_pr_message(&winner, None, true)
25799            .await
25800            .unwrap()
25801            .expect("the role rewrites after the implementer fails");
25802        assert!(msg.body.contains("`src/net.rs`"));
25803        assert_eq!(
25804            runner.state.seats["impl-A"].turns, 2,
25805            "the implementer was tried once"
25806        );
25807        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25808        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25809    }
25810
25811    #[tokio::test]
25812    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25813        crate::run::pin_test_home();
25814        let dir = tempfile::tempdir().unwrap();
25815        let mut broken = spec("bad");
25816        broken.command = vec!["false".into()];
25817        let mut runner = rewrite_runner(
25818            dir.path(),
25819            true,
25820            vec![
25821                broken,
25822                scripted("noformat", "Add retries."),
25823                scripted("good", EN_REWRITE),
25824            ],
25825        );
25826        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25827            "bad".into(),
25828            "noformat".into(),
25829            "good".into(),
25830        ]));
25831        let winner = runner.state.candidates[0].clone();
25832        let msg = runner
25833            .guarded_pr_message(&winner, None, true)
25834            .await
25835            .unwrap()
25836            .expect("the third agent rewrites");
25837        assert!(msg.body.contains("`src/net.rs`"));
25838        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25839        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25840    }
25841
25842    #[tokio::test]
25843    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25844        crate::run::pin_test_home();
25845        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25846        for (agents, role, saved) in [
25847            (
25848                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25849                Some("beta"),
25850                true,
25851            ),
25852            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25853            (Vec::new(), None, false),
25854        ] {
25855            let dir = tempfile::tempdir().unwrap();
25856            let mut runner = rewrite_runner(dir.path(), true, agents);
25857            runner.state.config.roles.language_judge =
25858                role.map(|r| crate::config::AgentChoice::One(r.into()));
25859            let winner = runner.state.candidates[0].clone();
25860            let first = runner
25861                .guarded_pr_message(&winner, None, true)
25862                .await
25863                .unwrap();
25864            assert!(first.is_none(), "withheld text parks the run");
25865            assert!(runner.state.parked);
25866            assert_eq!(gate_questions(&runner), 1);
25867            let g = runner.state.github_text.as_ref().unwrap();
25868            assert_eq!(g.rewrite.is_some(), saved);
25869            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25870        }
25871    }
25872
25873    #[tokio::test]
25874    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25875        crate::run::pin_test_home();
25876        let dir = tempfile::tempdir().unwrap();
25877        let mut runner = runner_at(RunStatus::Gating);
25878        runner.state =
25879            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25880        runner.state.repo = dir.path().to_owned();
25881        runner.state.candidates[0].worktree = dir.path().to_owned();
25882        let mut author = spec("alpha");
25883        author.command = vec![
25884            "sh".into(),
25885            "-c".into(),
25886            "printf '%s' \"$REWRITE_REPLY\"".into(),
25887        ];
25888        author.env.insert(
25889            "REWRITE_REPLY".into(),
25890            format!(
25891                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25892                "English sentence. ".repeat(600)
25893            ),
25894        );
25895        runner.state.config.agents = vec![author];
25896        seed_public_summary(&mut runner);
25897        let winner = runner.state.candidates[0].clone();
25898        assert!(
25899            runner
25900                .guarded_pr_message(&winner, None, true)
25901                .await
25902                .unwrap()
25903                .is_none()
25904        );
25905        let record = runner.state.github_text.clone().unwrap();
25906        let rewrite = record.rewrite.clone().unwrap();
25907        assert_eq!(rewrite.failed, ["body-language"]);
25908        assert!(
25909            rewrite
25910                .body
25911                .ends_with(&format!("magi:run/{}", runner.state.id))
25912        );
25913        let store = ask::Questions::open();
25914        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25915        assert!(
25916            q.choices
25917                .contains(&crate::github_text::USE_REWRITE.to_owned())
25918        );
25919        for label in [
25920            "ORIGINAL",
25921            "FALLBACK",
25922            "REWRITE",
25923            "Rules still failed: body-language",
25924            "truncated",
25925        ] {
25926            assert!(q.detail.contains(label), "{label}");
25927        }
25928        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25929            &runner.state,
25930            &crate::github_text::artifact_name(&record.fingerprint),
25931        ))
25932        .unwrap();
25933        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25934        // Restart from serialized state, then retry after a bad owner title.
25935        runner.state =
25936            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25937        store
25938            .update(&q.id, |q| {
25939                q.say("まだ日本語")?;
25940                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25941            })
25942            .unwrap();
25943        assert!(
25944            runner
25945                .guarded_pr_message(&winner, None, true)
25946                .await
25947                .unwrap()
25948                .is_none()
25949        );
25950        let retry = runner.state.github_text.as_ref().unwrap();
25951        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25952        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25953        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25954        assert!(
25955            q.posting_comparison
25956                .as_ref()
25957                .unwrap()
25958                .matches_detail(&q.detail)
25959        );
25960        store
25961            .update(&q.id, |q| {
25962                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25963            })
25964            .unwrap();
25965        let message = runner
25966            .guarded_pr_message(&winner, None, true)
25967            .await
25968            .unwrap()
25969            .unwrap();
25970        assert_eq!(message.title, rewrite.title);
25971        assert_eq!(message.body, rewrite.body);
25972        assert_eq!(
25973            runner.state.github_text.as_ref().unwrap().choice,
25974            Some(GithubTextChoice::Rewrite)
25975        );
25976        let again = runner
25977            .guarded_pr_message(&winner, None, true)
25978            .await
25979            .unwrap()
25980            .unwrap();
25981        assert_eq!(again.title, message.title);
25982        assert_eq!(again.body, message.body);
25983        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25984        assert!(
25985            !runner
25986                .state
25987                .events
25988                .iter()
25989                .any(|e| e.message.contains(&rewrite.title)
25990                    || e.message.contains("English sentence."))
25991        );
25992    }
25993
25994    #[tokio::test]
25995    async fn historical_posting_reply_never_expires_into_fallback() {
25996        crate::run::pin_test_home();
25997        let dir = tempfile::tempdir().unwrap();
25998        let mut runner = runner_at(RunStatus::Gating);
25999        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
26000        runner.state.repo = dir.path().to_owned();
26001        runner.state.candidates[0].worktree = dir.path().to_owned();
26002        seed_public_summary(&mut runner);
26003        let winner = runner.state.candidates[0].clone();
26004        assert!(
26005            runner
26006                .guarded_pr_message(&winner, None, true)
26007                .await
26008                .unwrap()
26009                .is_none()
26010        );
26011        let id = runner
26012            .state
26013            .github_text
26014            .as_ref()
26015            .unwrap()
26016            .question
26017            .clone()
26018            .unwrap();
26019        let store = ask::Questions::open();
26020        let mut q = store.get(&id).unwrap();
26021        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
26022        q.answer(ask::Answer::Choice(
26023            crate::github_text::POST_ORIGINAL.into(),
26024        ))
26025        .unwrap();
26026        q.answer_delivered = true;
26027        store.put(&mut q).unwrap();
26028        let source = std::fs::read(store.path_of(&id)).unwrap();
26029        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
26030        std::fs::create_dir_all(&migration).unwrap();
26031        std::fs::write(
26032            migration.join("state.json"),
26033            serde_json::to_vec(&serde_json::json!({
26034                "schema": 1, "sources": [id], "pending": [id]
26035            }))
26036            .unwrap(),
26037        )
26038        .unwrap();
26039        for _ in 0..2 {
26040            assert!(
26041                runner
26042                    .guarded_pr_message(&winner, None, true)
26043                    .await
26044                    .unwrap()
26045                    .is_none()
26046            );
26047            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
26048            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
26049        }
26050        let home = crate::run::home();
26051        crate::task_chat::sweep(
26052            &crate::queue::Queue::at(home.join("queue")),
26053            &crate::talk::Talks::at(home.join("talks")),
26054            &store,
26055            &home,
26056        );
26057        let outbox = crate::task_inquiry::Outbox::at(&home);
26058        outbox
26059            .update_decision(&id, |d| {
26060                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
26061                d.source_answer_at = q.answered_at;
26062                Ok(true)
26063            })
26064            .unwrap();
26065        outbox
26066            .settle(
26067                &id,
26068                "owner-chat",
26069                "Owner confirms no publication remains necessary",
26070                None,
26071            )
26072            .unwrap();
26073        assert!(
26074            runner
26075                .guarded_pr_message(&winner, None, true)
26076                .await
26077                .unwrap()
26078                .is_none()
26079        );
26080        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
26081        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
26082    }
26083
26084    #[tokio::test]
26085    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
26086        crate::run::pin_test_home();
26087        let dir = tempfile::tempdir().unwrap();
26088        let mut runner = runner_at(RunStatus::Gating);
26089        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
26090        runner.state.repo = dir.path().to_owned();
26091        runner.state.candidates[0].worktree = dir.path().to_owned();
26092        seed_public_summary(&mut runner);
26093        let winner = runner.state.candidates[0].clone();
26094        assert!(
26095            runner
26096                .guarded_pr_message(&winner, None, true)
26097                .await
26098                .unwrap()
26099                .is_none()
26100        );
26101        let record = runner.state.github_text.as_ref().unwrap();
26102        assert!(record.rewrite.is_none());
26103        // Records written before the additive field deserialize with no rewrite.
26104        let mut old = serde_json::to_value(record).unwrap();
26105        old.as_object_mut().unwrap().remove("rewrite");
26106        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
26107        assert!(old.rewrite.is_none());
26108        let id = record.question.clone().unwrap();
26109        ask::Questions::open()
26110            .update(&id, |q| {
26111                q.choices.push(crate::github_text::USE_REWRITE.into());
26112                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
26113            })
26114            .unwrap();
26115        let message = runner
26116            .guarded_pr_message(&winner, None, true)
26117            .await
26118            .unwrap()
26119            .unwrap();
26120        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
26121        assert_eq!(
26122            runner.state.github_text.as_ref().unwrap().choice,
26123            Some(GithubTextChoice::Fallback)
26124        );
26125    }
26126
26127    #[tokio::test]
26128    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
26129        crate::run::pin_test_home();
26130        let dir = tempfile::tempdir().unwrap();
26131        let mut runner = runner_at(RunStatus::Gating);
26132        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
26133        runner.state.repo = dir.path().to_owned();
26134        runner.state.candidates[0].worktree = dir.path().to_owned();
26135        seed_public_summary(&mut runner);
26136        let winner = runner.state.candidates[0].clone();
26137        assert!(
26138            runner
26139                .guarded_pr_message(&winner, None, true)
26140                .await
26141                .unwrap()
26142                .is_none()
26143        );
26144        let store = ask::Questions::open();
26145        let find = |run: &str| {
26146            store
26147                .list()
26148                .into_iter()
26149                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
26150                .unwrap()
26151        };
26152        let run = runner.state.id.clone();
26153        let q = find(&run);
26154        let fp = runner
26155            .state
26156            .github_text
26157            .as_ref()
26158            .unwrap()
26159            .fingerprint
26160            .clone();
26161        let name = crate::github_text::artifact_name(&fp);
26162        let path = crate::run::artifact_path(&runner.state, &name);
26163        assert!(q.detail.contains(&path.display().to_string()));
26164        assert!(q.detail.contains("title-language: title"));
26165        let saved = std::fs::read_to_string(&path).expect("artifact written");
26166        assert!(saved.contains("日本語のタイトル"));
26167        assert!(q.cwd.is_none());
26168        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
26169        // A bad replacement is refused and asked about once more.
26170        let say = |id: &str, text: &str, choice: &str| {
26171            store
26172                .update(id, |q| {
26173                    q.thread.push(ask::Turn {
26174                        who: ask::Who::Operator,
26175                        body: text.to_owned(),
26176                        at: jiff::Timestamp::now(),
26177                        note: None,
26178                    });
26179                    q.answer(ask::Answer::Choice(choice.to_owned()))
26180                })
26181                .unwrap();
26182        };
26183        say(&q.id, "まだ日本語", "use my text");
26184        assert!(
26185            runner
26186                .guarded_pr_message(&winner, None, true)
26187                .await
26188                .unwrap()
26189                .is_none()
26190        );
26191        let second = find(&run);
26192        assert_ne!(second.id, q.id);
26193        assert!(second.detail.contains("did not pass"));
26194        // The retry still compares the original text; the rejected
26195        // replacement is named by category only.
26196        assert!(second.detail.contains("日本語のタイトル"));
26197        assert!(!second.detail.contains("まだ日本語"));
26198        assert!(second.detail.contains(&path.display().to_string()));
26199        say(&second.id, "fix: retry failed requests", "use my text");
26200        let message = runner
26201            .guarded_pr_message(&winner, None, true)
26202            .await
26203            .unwrap()
26204            .expect("a vetted replacement is posted");
26205        assert_eq!(message.title, "fix: retry failed requests");
26206        assert_eq!(
26207            runner
26208                .state
26209                .github_text
26210                .as_ref()
26211                .unwrap()
26212                .chosen_title
26213                .as_deref(),
26214            Some("fix: retry failed requests")
26215        );
26216        assert!(runner.state.github_text.as_ref().unwrap().resolved);
26217        // Resumed again: the saved decision is applied, nothing is re-asked.
26218        let again = runner
26219            .guarded_pr_message(&winner, None, true)
26220            .await
26221            .unwrap()
26222            .unwrap();
26223        assert_eq!(again.title, message.title);
26224        assert_eq!(
26225            store
26226                .list()
26227                .into_iter()
26228                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
26229                .count(),
26230            2
26231        );
26232    }
26233
26234    #[test]
26235    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
26236        // What magi itself writes stays English under any configured language,
26237        // so a future localisation of these headings fails here. (The agents'
26238        // own text is also checked by the posting gate.)
26239        let mut state = state_with_summary(
26240            "add retries",
26241            "TITLE: fix(web): batch reads\n- reads run.json once",
26242        );
26243        state.config.graph.language = "ja".to_owned();
26244        let m = pr_message(&state, 'A');
26245        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
26246        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
26247
26248        // The task is the operator's own text: it goes in untouched, and the
26249        // fallback title (no summary) may be in its language too.
26250        let task = "今回やってほしいこと: results projector を直す";
26251        let mut state = state_with_summary(task, "- no title line");
26252        state.config.graph.language = "ja".to_owned();
26253        let m = pr_message(&state, 'A');
26254        assert_eq!(
26255            m.title,
26256            format!("chore: land candidate A of run {}", state.id)
26257        );
26258        assert!(
26259            m.body.contains(&format!(
26260                "<summary>Original task</summary>\n\n{task}\n\n</details>"
26261            )),
26262            "{}",
26263            m.body
26264        );
26265    }
26266
26267    #[test]
26268    fn pr_message_scrubs_home_paths_and_addresses() {
26269        let state = state_with_summary(
26270            "fix it in /Users/someone/src/x",
26271            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
26272        );
26273        let m = pr_message(&state, 'A');
26274        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
26275            assert!(!m.body.contains(leak), "{}", m.body);
26276        }
26277        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
26278    }
26279
26280    #[test]
26281    fn pr_message_survives_a_task_that_closes_details() {
26282        let state = state_with_summary("a </details> b", "TITLE: fix: x");
26283        let m = pr_message(&state, 'A');
26284        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
26285    }
26286
26287    #[test]
26288    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
26289        let cmd = manual_merge_command(
26290            MergeStyle::Squash,
26291            Path::new("/repo"),
26292            "b",
26293            "fix: \"quoted\" $(x) `y`\n\nbody",
26294        );
26295        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
26296    }
26297
26298    #[test]
26299    fn manual_merge_command_matches_the_configured_style() {
26300        let repo = Path::new("/repo");
26301        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
26302
26303        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
26304        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
26305
26306        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
26307        assert_eq!(
26308            squash,
26309            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
26310             \"Merge magi run 0832 (candidate A)\""
26311        );
26312
26313        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
26314        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
26315    }
26316
26317    #[test]
26318    fn a_nudge_gets_a_quarter_of_the_budget() {
26319        // The judge and implement budgets magi ships with.
26320        assert_eq!(retry_budget(secs(1200), true), secs(300));
26321        assert_eq!(retry_budget(secs(3600), true), secs(900));
26322    }
26323
26324    #[test]
26325    fn a_resent_prompt_keeps_the_whole_budget() {
26326        // The seat kept no context, so the retry is the original job again and
26327        // shortening it would only guarantee a second failure.
26328        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26329        assert_eq!(retry_budget(secs(60), false), secs(60));
26330    }
26331
26332    #[test]
26333    fn the_floor_never_exceeds_the_original_budget() {
26334        // A short configured timeout must not be *raised* by the floor: the
26335        // operator asked for a bound, and a retry may not outlast the attempt
26336        // it is retrying.
26337        assert_eq!(retry_budget(secs(60), true), secs(60));
26338        assert_eq!(retry_budget(secs(480), true), secs(120));
26339        assert_eq!(retry_budget(secs(0), true), secs(0));
26340    }
26341
26342    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26343        agent::CommandEvidence {
26344            id: "item1".to_owned(),
26345            description: "cargo test".to_owned(),
26346            exit_code,
26347            result_summary: String::new(),
26348            source: "codex".to_owned(),
26349        }
26350    }
26351
26352    #[test]
26353    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26354        // No evidence is not the same fact as unconfirmed evidence: a
26355        // backend with no adapter, or a reply that ran no commands at all,
26356        // must not be misread as carrying a dangling job.
26357        assert!(!has_unconfirmed_command(&[]));
26358    }
26359
26360    fn reply(tool_calls: Option<u64>) -> AgentOutput {
26361        AgentOutput {
26362            text: "## SUMMARY\nImplementation incomplete.".to_owned(),
26363            exit_code: Some(0),
26364            timed_out: false,
26365            duration_ms: 7_000,
26366            artifacts: Vec::new(),
26367            quota: None,
26368            dropped: None,
26369            commands: Vec::new(),
26370            context_tokens: None,
26371            tool_calls,
26372        }
26373    }
26374
26375    #[test]
26376    fn a_clean_reply_with_no_tool_call_on_an_untouched_tree_is_unstarted() {
26377        assert!(ended_unstarted(
26378            &reply(Some(0)),
26379            Some("abc"),
26380            Some("abc"),
26381            Some(true)
26382        ));
26383    }
26384
26385    #[test]
26386    fn unknown_or_real_tool_activity_is_never_unstarted() {
26387        // A backend that reports no tool calls says nothing about them.
26388        assert!(!ended_unstarted(
26389            &reply(None),
26390            Some("abc"),
26391            Some("abc"),
26392            Some(true)
26393        ));
26394        // A seat that looked and then wrote nothing did start.
26395        assert!(!ended_unstarted(
26396            &reply(Some(3)),
26397            Some("abc"),
26398            Some("abc"),
26399            Some(true)
26400        ));
26401        let mut ran = reply(Some(0));
26402        ran.commands.push(evidence(Some(0)));
26403        assert!(!ended_unstarted(&ran, Some("abc"), Some("abc"), Some(true)));
26404    }
26405
26406    #[test]
26407    fn work_in_the_tree_or_an_unreadable_one_is_never_unstarted() {
26408        let out = reply(Some(0));
26409        // A commit, uncommitted edits, and each unknown: none may be replayed.
26410        assert!(!ended_unstarted(&out, Some("abc"), Some("def"), Some(true)));
26411        assert!(!ended_unstarted(
26412            &out,
26413            Some("abc"),
26414            Some("abc"),
26415            Some(false)
26416        ));
26417        assert!(!ended_unstarted(&out, None, Some("abc"), Some(true)));
26418        assert!(!ended_unstarted(&out, Some("abc"), None, Some(true)));
26419        assert!(!ended_unstarted(&out, Some("abc"), Some("abc"), None));
26420        assert!(!ended_unstarted(&out, None, None, Some(true)));
26421    }
26422
26423    #[test]
26424    fn a_failed_or_empty_turn_is_not_an_unstarted_reply() {
26425        let mut failed = reply(Some(0));
26426        failed.exit_code = Some(1);
26427        assert!(!ended_unstarted(
26428            &failed,
26429            Some("abc"),
26430            Some("abc"),
26431            Some(true)
26432        ));
26433        let mut silent = reply(Some(0));
26434        silent.text = String::new();
26435        assert!(!ended_unstarted(
26436            &silent,
26437            Some("abc"),
26438            Some("abc"),
26439            Some(true)
26440        ));
26441    }
26442
26443    #[test]
26444    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26445        // Deliberately not a check on the exit code's *value*: a fixer
26446        // legitimately runs something that fails mid-iteration before it
26447        // succeeds, and that must never by itself reopen a valid report.
26448        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26449        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26450        assert!(!has_unconfirmed_command(&[
26451            evidence(Some(0)),
26452            evidence(Some(101))
26453        ]));
26454    }
26455
26456    #[test]
26457    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26458        assert!(has_unconfirmed_command(&[
26459            evidence(Some(0)),
26460            evidence(None)
26461        ]));
26462    }
26463
26464    fn evidence_with(
26465        description: &str,
26466        exit_code: Option<i32>,
26467        result_summary: &str,
26468    ) -> agent::CommandEvidence {
26469        agent::CommandEvidence {
26470            id: "item1".to_owned(),
26471            description: description.to_owned(),
26472            exit_code,
26473            result_summary: result_summary.to_owned(),
26474            source: "codex".to_owned(),
26475        }
26476    }
26477
26478    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26479        format!(
26480            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":[]}}"#
26481        )
26482    }
26483
26484    #[test]
26485    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26486        let text = valid_noop_summary("b32cfc4", "retry_test");
26487        let claim = verified_noop_claim(true, &[], &text)
26488            .expect("valid structured report with no CommandEvidence must be accepted");
26489        assert!(claim.contains("b32cfc4"), "{claim}");
26490        assert!(claim.contains("retry_test"), "{claim}");
26491    }
26492
26493    #[test]
26494    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26495        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26496        assert!(verified_noop_claim(true, &[], regression).is_none());
26497        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26498        assert!(err.contains("single JSON object"), "{err}");
26499
26500        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26501        assert!(verified_noop_claim(true, &[], legacy).is_none());
26502    }
26503
26504    #[test]
26505    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26506        // A timeout or a bad exit code reads as the ordinary loss it is,
26507        // whatever the reply's own structured JSON claims.
26508        let text = valid_noop_summary("b32cfc4", "retry_test");
26509        assert!(verified_noop_claim(false, &[], &text).is_none());
26510    }
26511
26512    #[test]
26513    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26514        let text = valid_noop_summary("b32cfc4", "retry_test");
26515        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26516        // A matching confirmed command alongside the marker is fine.
26517        assert!(
26518            verified_noop_claim(
26519                true,
26520                &[evidence_with(
26521                    "cargo test --lib retry_test",
26522                    Some(0),
26523                    "1 passed"
26524                )],
26525                &text
26526            )
26527            .is_some()
26528        );
26529    }
26530
26531    #[test]
26532    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26533     {
26534        let text = valid_noop_summary("b32cfc4", "retry_test");
26535
26536        // Unrelated passing command cannot substantiate a claimed test run.
26537        let err = evaluate_noop_claim(
26538            true,
26539            &[evidence_with("git status", Some(0), "nothing to commit")],
26540            &text,
26541        )
26542        .unwrap_err();
26543        assert!(err.contains("no matching command was recorded"), "{err}");
26544
26545        // Final matching command exited non-zero -> rejected even if an
26546        // unrelated command succeeded afterward.
26547        let err = evaluate_noop_claim(
26548            true,
26549            &[
26550                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26551                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26552                evidence_with("rg retry_test src", Some(0), "retry_test"),
26553            ],
26554            &text,
26555        )
26556        .unwrap_err();
26557        assert!(err.contains("exited with"), "{err}");
26558
26559        // A different invocation containing the entire method is not a rerun.
26560        let err = evaluate_noop_claim(
26561            true,
26562            &[evidence_with(
26563                "echo 'cargo test --lib retry_test'",
26564                Some(0),
26565                "retry_test",
26566            )],
26567            &text,
26568        )
26569        .unwrap_err();
26570        assert!(err.contains("no matching command was recorded"), "{err}");
26571
26572        // Mid-investigation failure followed by a passing re-run -> accepted!
26573        assert!(
26574            verified_noop_claim(
26575                true,
26576                &[
26577                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26578                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26579                ],
26580                &text
26581            )
26582            .is_some()
26583        );
26584    }
26585
26586    #[test]
26587    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26588        let text = valid_noop_summary("b32cfc4", "retry_test");
26589        let method = "cargo test --lib retry_test";
26590        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26591        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26592        let failed =
26593            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26594        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26595        for output in [empty, ignored, failed] {
26596            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26597                .unwrap_err();
26598            assert!(err.contains("failure or no passing tests"), "{err}");
26599        }
26600        // Multiple harnesses can legitimately include a filtered-out suite.
26601        let mixed = format!("{passed}\n{empty}");
26602        assert!(
26603            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26604        );
26605        // A later real rerun of the same command can establish success.
26606        assert!(
26607            verified_noop_claim(
26608                true,
26609                &[
26610                    evidence_with(method, Some(0), empty),
26611                    evidence_with(method, Some(0), passed),
26612                ],
26613                &text,
26614            )
26615            .is_some()
26616        );
26617    }
26618
26619    #[test]
26620    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26621        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":[]}"#;
26622        let failed = evidence_with("rg expected README.md", Some(1), "");
26623        let unrelated = evidence_with("cat README.md", Some(0), "README");
26624        let err =
26625            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26626        assert!(err.contains("exited with"), "{err}");
26627        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26628        assert!(
26629            evaluate_noop_claim(
26630                true,
26631                &[
26632                    failed,
26633                    evidence_with("rg expected README.md", Some(0), "expected header"),
26634                ],
26635                text,
26636            )
26637            .unwrap()
26638            .is_some()
26639        );
26640    }
26641
26642    #[test]
26643    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26644        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26645        assert!(matches!(
26646            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26647            Ok(None)
26648        ));
26649    }
26650
26651    #[tokio::test]
26652    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26653        let tmp = tempfile::tempdir().unwrap();
26654        let repo = tmp.path().join("repo");
26655        std::fs::create_dir_all(&repo).unwrap();
26656        let run_git = |args: &[&str]| {
26657            let out = std::process::Command::new("git")
26658                .args(args)
26659                .current_dir(&repo)
26660                .output()
26661                .unwrap();
26662            assert!(out.status.success(), "git {args:?} failed");
26663            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26664        };
26665        run_git(&["init", "-b", "main"]);
26666        run_git(&["config", "user.name", "test"]);
26667        run_git(&["config", "user.email", "test@example.com"]);
26668        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26669        run_git(&["add", "-A"]);
26670        run_git(&["commit", "-m", "base commit"]);
26671        let base = run_git(&["rev-parse", "HEAD"]);
26672
26673        // Create a commit on a side branch not on `base`.
26674        run_git(&["checkout", "-b", "side"]);
26675        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26676        run_git(&["add", "-A"]);
26677        run_git(&["commit", "-m", "side commit"]);
26678        let side = run_git(&["rev-parse", "HEAD"]);
26679        run_git(&["checkout", "main"]);
26680
26681        // Valid commit on base + existing path -> Accepted.
26682        let valid = format!(
26683            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":[]}}"#
26684        );
26685        assert!(matches!(
26686            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26687            NoopClaimVerdict::Accepted
26688        ));
26689
26690        // Non-existent commit SHA -> Rejected.
26691        let missing_sha = valid.replace(&base, "deadbeef");
26692        assert!(matches!(
26693            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26694            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26695        ));
26696
26697        // Commit on unmerged side branch -> Rejected.
26698        let side_sha = valid.replace(&base, &side);
26699        assert!(matches!(
26700            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26701            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26702        ));
26703
26704        // Missing file path -> Rejected.
26705        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26706        assert!(matches!(
26707            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26708            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26709        ));
26710    }
26711
26712    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26713    /// pair, in order, labelled A, B, C, ...
26714    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26715        runner.state.candidates = shape
26716            .iter()
26717            .enumerate()
26718            .map(|(i, &(empty, verified))| {
26719                let (summary, verified_noop) = match verified {
26720                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26721                    None => (String::new(), None),
26722                };
26723                Candidate {
26724                    index: i,
26725                    label: (b'A' + i as u8) as char,
26726                    agent: "sonnet".to_owned(),
26727                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26728                    worktree: PathBuf::from(format!("/wt/{i}")),
26729                    summary,
26730                    stat: String::new(),
26731                    files: 0,
26732                    commits: 0,
26733                    empty,
26734                    failed: None,
26735                    verified_noop,
26736                    duration_ms: 0,
26737                    folded: false,
26738                }
26739            })
26740            .collect();
26741    }
26742
26743    #[test]
26744    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26745        ask_test_home();
26746        let mut runner = runner_at(RunStatus::Implementing);
26747        let a = valid_noop_summary("b32cfc4", "test_a");
26748        let b = valid_noop_summary("b32cfc4", "test_b");
26749        set_candidates(
26750            &mut runner,
26751            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26752        );
26753
26754        runner
26755            .after_implement()
26756            .expect("a verified no-op is not an error");
26757
26758        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26759    }
26760
26761    #[test]
26762    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26763        ask_test_home();
26764        let mut runner = runner_at(RunStatus::Implementing);
26765        let a = valid_noop_summary("b32cfc4", "test_a");
26766        // Candidate A declares a verified no-op; candidate B simply wrote
26767        // nothing and said nothing about why. One candidate's claim is not
26768        // the whole run's agreement.
26769        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26770
26771        let err = runner
26772            .after_implement()
26773            .expect_err("an unverified empty candidate must still fail the run");
26774
26775        assert!(
26776            err.to_string().contains("no candidate produced a change"),
26777            "{err}"
26778        );
26779        assert_eq!(runner.state.status, RunStatus::Failed);
26780    }
26781
26782    #[test]
26783    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26784        ask_test_home();
26785        let mut runner = runner_at(RunStatus::Implementing);
26786        // Simulate a saved incomplete run that stored a legacy/incomplete
26787        // `verified_noop` string before this build's strict contract.
26788        set_candidates(
26789            &mut runner,
26790            &[(
26791                true,
26792                Some(
26793                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26794                ),
26795            )],
26796        );
26797
26798        let err = runner
26799            .after_implement()
26800            .expect_err("invalid saved noop claim must fail the run");
26801        assert!(
26802            err.to_string().contains("no candidate produced a change"),
26803            "{err}"
26804        );
26805        assert_eq!(runner.state.status, RunStatus::Failed);
26806        assert!(runner.state.candidates[0].verified_noop.is_none());
26807        assert!(runner.state.candidates[0].failed.is_some());
26808        assert!(runner.state.events.iter().any(|e| {
26809            e.message
26810                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26811        }));
26812    }
26813
26814    #[test]
26815    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26816        ask_test_home();
26817        let mut runner = runner_at(RunStatus::Implementing);
26818        let a = valid_noop_summary("b32cfc4", "test_a");
26819        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26820        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26821
26822        let err = runner
26823            .after_implement()
26824            .expect_err("a failed candidate must never settle as verified no-op");
26825        assert!(err.to_string().contains("no candidate produced a change"));
26826        assert_eq!(runner.state.status, RunStatus::Failed);
26827        assert!(runner.state.candidates[0].verified_noop.is_none());
26828    }
26829
26830    #[test]
26831    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26832        ask_test_home();
26833        let mut runner = runner_at(RunStatus::Implementing);
26834        set_candidates(&mut runner, &[(true, None), (true, None)]);
26835
26836        let err = runner
26837            .after_implement()
26838            .expect_err("no candidate declared anything; this is an ordinary failure");
26839
26840        assert!(
26841            err.to_string().contains("no candidate produced a change"),
26842            "{err}"
26843        );
26844        assert_eq!(runner.state.status, RunStatus::Failed);
26845    }
26846}
26847
26848/// A graft rollback whose restore could not be confirmed (see
26849/// [`Runner::graft`]).
26850#[derive(Debug)]
26851struct GraftRestoreFailed(String);
26852
26853impl std::fmt::Display for GraftRestoreFailed {
26854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26855        write!(
26856            f,
26857            "could not restore the winner to its pre-graft commit: {}",
26858            self.0
26859        )
26860    }
26861}
26862
26863impl std::error::Error for GraftRestoreFailed {}
26864
26865/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26866/// not the agent: they never draw on an agent's own timeout, and running out of
26867/// them never reads as an agent failure.
26868#[cfg(test)]
26869mod resource_wait_tests {
26870    use super::*;
26871    use std::collections::BTreeMap;
26872
26873    fn sh(id: &str, script: &str) -> AgentSpec {
26874        AgentSpec {
26875            id: id.to_owned(),
26876            kind: crate::config::AgentKind::Command,
26877            model: None,
26878            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26879            extra_args: Vec::new(),
26880            env: BTreeMap::new(),
26881            prompt_delivery: None,
26882            max_turn_secs: None,
26883        }
26884    }
26885
26886    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26887        SeatJob {
26888            seat: SeatState::new("impl-A", &spec.id, 1),
26889            spec,
26890            cwd: dir.to_path_buf(),
26891            prompt: "do it".to_owned(),
26892            timeout,
26893            allow_write: true,
26894            sessions: false,
26895            artifacts: dir.join("art"),
26896            stem: "impl-A".to_owned(),
26897            handover: None,
26898        }
26899    }
26900
26901    fn state(resource_wait_secs: u64) -> RunState {
26902        let mut config = Config::default();
26903        config.graph.timeout_resource_wait = resource_wait_secs;
26904        RunState::new(
26905            PathBuf::from("/repo"),
26906            "main".to_owned(),
26907            "abc1234".to_owned(),
26908            "task".to_owned(),
26909            config,
26910        )
26911    }
26912
26913    fn hold(cache: &Path) -> crate::cache::Guard {
26914        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26915        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26916            crate::cache::AcquireOutcome::Acquired(g) => g,
26917            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26918        }
26919    }
26920
26921    async fn run(
26922        jobs: Vec<SeatJob>,
26923        sem: Arc<Semaphore>,
26924        cache: Option<&Path>,
26925        st: &mut RunState,
26926    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26927        let prompts = Prompts::default();
26928        let ctx = WaveCtx {
26929            run: "r",
26930            node: "implement",
26931            prompts: &prompts,
26932            cache,
26933            round: None,
26934            carry_seats: false,
26935            pauses: None,
26936        };
26937        wave(jobs, sem, &ctx, st, 0).await
26938    }
26939
26940    #[tokio::test]
26941    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26942        crate::run::pin_test_home();
26943        let home = crate::run::home();
26944        let tmp = tempfile::tempdir().unwrap();
26945        let repo = tmp.path().join("repo");
26946        let checkout = tmp.path().join("checkout");
26947        std::fs::create_dir(&repo).unwrap();
26948        git::git(&repo, &["init"]).await.unwrap();
26949        git::git(
26950            &repo,
26951            &[
26952                "-c",
26953                "user.name=Fixture",
26954                "-c",
26955                "user.email=fixture@example.invalid",
26956                "commit",
26957                "--allow-empty",
26958                "-m",
26959                "initial",
26960            ],
26961        )
26962        .await
26963        .unwrap();
26964        git::worktree_add_detached(&repo, &checkout, "HEAD")
26965            .await
26966            .unwrap();
26967        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26968        let target_lease = hold(&target);
26969        let shared = tmp.path().join("unrelated");
26970        let _shared_lease = hold(&shared);
26971        let mut st = state(0);
26972        st.repo = repo.clone();
26973        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26974        st.config.verify.e2e = vec![format!(
26975            "CARGO_TARGET_DIR='{}' cargo test",
26976            git::path_arg(&shared)
26977        )];
26978        let config = tmp.path().join("config.toml");
26979        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26980        let prompts = Prompts::default();
26981        let run_id = st.id.clone();
26982        let ctx = WaveCtx {
26983            run: &run_id,
26984            node: "implement",
26985            prompts: &prompts,
26986            cache: None,
26987            round: None,
26988            carry_seats: false,
26989            pauses: None,
26990        };
26991        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26992        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26993        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26994        assert_eq!(results[0].1.turns, 0);
26995        let saved = RunState::load_under(&run_id, &home).unwrap();
26996        let block = saved.resource_block.unwrap();
26997        assert!(matches!(
26998            block.cause,
26999            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
27000                if actual == &target
27001        ));
27002        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
27003        let mut task = crate::queue::Task::new(
27004            "build".into(),
27005            "build".into(),
27006            repo,
27007            crate::queue::Source::Human,
27008        );
27009        task.runs.push(run_id);
27010        task.hold_machine(Some(format!(
27011            "{}{}",
27012            crate::cache::RESOURCE_HOLD,
27013            block.description()
27014        )));
27015        queue.put(&mut task).unwrap();
27016        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
27017        let triage =
27018            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
27019        let pending = triage();
27020        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
27021        assert_eq!(
27022            queue.get(&task.id).unwrap().status,
27023            crate::queue::TaskStatus::Held
27024        );
27025        drop(target_lease);
27026        assert_eq!(triage().resumed, vec![task.id.clone()]);
27027        assert_eq!(
27028            queue.get(&task.id).unwrap().status,
27029            crate::queue::TaskStatus::Queued
27030        );
27031        assert!(crate::cache::in_use(&home, &shared));
27032    }
27033
27034    #[tokio::test]
27035    async fn verification_cache_wait_preserves_the_command_budget() {
27036        crate::run::pin_test_home();
27037        let tmp = tempfile::tempdir().unwrap();
27038        let cache = tmp.path().join("target");
27039        let guard = hold(&cache);
27040        let release = tokio::spawn(async move {
27041            tokio::time::sleep(Duration::from_millis(100)).await;
27042            guard.release();
27043        });
27044        let mut st = state(10);
27045        let budget = Duration::from_millis(50);
27046        let wait = repository_wait(&st, None);
27047        let (outcomes, _) = with_cache_lease(
27048            &mut st,
27049            Some(&cache),
27050            "gate",
27051            "gate",
27052            tmp.path(),
27053            "abc1234",
27054            budget,
27055            "test gate",
27056            &wait,
27057            |_, available| async move {
27058                assert_eq!(
27059                    available, budget,
27060                    "contention must not shorten verification"
27061                );
27062                (Vec::new(), false, Vec::new())
27063            },
27064        )
27065        .await
27066        .unwrap();
27067        release.await.unwrap();
27068        assert!(outcomes.is_empty(), "{outcomes:?}");
27069        assert!(
27070            st.events
27071                .iter()
27072                .any(|event| event.message.contains("waiting for"))
27073        );
27074        assert!(st.resource_wait.is_none());
27075        // The verification body no longer owns the lease after returning.
27076        hold(&cache).release();
27077    }
27078
27079    #[tokio::test]
27080    async fn verification_cache_wait_expires_without_starting_commands() {
27081        crate::run::pin_test_home();
27082        let tmp = tempfile::tempdir().unwrap();
27083        let cache = tmp.path().join("target");
27084        let _held = hold(&cache);
27085        let mut st = state(0);
27086        let wait = repository_wait(&st, None);
27087        let (outcomes, _) = with_cache_lease(
27088            &mut st,
27089            Some(&cache),
27090            "gate",
27091            "gate",
27092            tmp.path(),
27093            "abc1234",
27094            Duration::from_secs(60),
27095            "test gate",
27096            &wait,
27097            |_, _| async { panic!("commands must not start without the cache lease") },
27098        )
27099        .await
27100        .unwrap();
27101        assert_eq!(outcomes.len(), 1);
27102        assert!(outcomes[0].resource_blocked);
27103        assert!(st.resource_wait.is_none());
27104        assert!(matches!(
27105            st.resource_block.unwrap().cause,
27106            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
27107        ));
27108    }
27109
27110    #[tokio::test]
27111    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
27112        crate::run::pin_test_home();
27113        let tmp = tempfile::tempdir().unwrap();
27114        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
27115        let cache = tmp.path().join("cache");
27116        let mut state = state(21600);
27117        let wait = repository_wait(&state, None);
27118        let (outcomes, _) = with_cache_lease(
27119            &mut state,
27120            Some(&cache),
27121            "gate",
27122            "gate",
27123            tmp.path(),
27124            "head",
27125            Duration::from_secs(60),
27126            "gate",
27127            &wait,
27128            |_, _| async { panic!("freshness failure must not start verification") },
27129        )
27130        .await
27131        .unwrap();
27132        assert_eq!(outcomes.len(), 1);
27133        assert!(outcomes[0].resource_blocked);
27134        let block = state.resource_block.unwrap();
27135        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
27136        assert!(!block.description().contains("timed out"));
27137    }
27138
27139    #[tokio::test]
27140    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
27141        crate::run::pin_test_home();
27142        let tmp = tempfile::tempdir().unwrap();
27143        let cache = tmp.path().join("cache");
27144        let _held = hold(&cache);
27145        let mut state = state(21600);
27146        let pause = Pause::new();
27147        let interrupt = Pause::new();
27148        let cause = ParkCause::Operator;
27149        pause.park_for(cause.clone());
27150        let prompts = Prompts::default();
27151        let ctx = WaveCtx {
27152            run: "test",
27153            node: "fix",
27154            prompts: &prompts,
27155            cache: Some(&cache),
27156            round: None,
27157            carry_seats: false,
27158            pauses: Some((&pause, &interrupt)),
27159        };
27160        let result = wave(
27161            vec![job(
27162                sh("writer", "exit 99"),
27163                tmp.path(),
27164                Duration::from_secs(1),
27165            )],
27166            Arc::new(Semaphore::new(1)),
27167            &ctx,
27168            &mut state,
27169            0,
27170        )
27171        .await;
27172        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
27173        assert_eq!(result[0].1.turns, 0);
27174        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27175        assert_eq!(
27176            state.resource_block.unwrap().cause,
27177            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
27178        );
27179        assert!(state.active.is_empty());
27180    }
27181
27182    #[tokio::test]
27183    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
27184        crate::run::pin_test_home();
27185        let tmp = tempfile::tempdir().unwrap();
27186        let cache = tmp.path().join("target-a");
27187        let guard = hold(&cache);
27188        // Held for longer than the agent's whole 1s budget.
27189        tokio::spawn(async move {
27190            tokio::time::sleep(Duration::from_millis(1500)).await;
27191            guard.release();
27192        });
27193        let mut st = state(60);
27194        let results = run(
27195            vec![job(
27196                sh("alpha", "echo ok"),
27197                tmp.path(),
27198                Duration::from_secs(1),
27199            )],
27200            Arc::new(Semaphore::new(1)),
27201            Some(&cache),
27202            &mut st,
27203        )
27204        .await;
27205        assert!(
27206            matches!(results[0].2, AgentOutcome::Ok(_)),
27207            "the wait must not be charged to the agent"
27208        );
27209        assert!(st.resource_block.is_none());
27210        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27211        assert!(st.resource_wait.is_none() && st.active.is_empty());
27212    }
27213
27214    #[tokio::test]
27215    #[cfg(unix)]
27216    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
27217        use std::os::fd::AsRawFd as _;
27218        crate::run::pin_test_home();
27219        let tmp = tempfile::tempdir().unwrap();
27220        crate::git::git(tmp.path(), &["init"]).await.unwrap();
27221        let common = tmp.path().join(".git");
27222        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
27223        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
27224        assert_eq!(
27225            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
27226            0
27227        );
27228        let mut st = state(1);
27229        st.config.coordination = crate::config::test_coordination();
27230        let mut reader = job(
27231            sh("reader", "echo must-not-run"),
27232            tmp.path(),
27233            Duration::from_secs(30),
27234        );
27235        reader.allow_write = false;
27236        let results = run(
27237            vec![reader.clone()],
27238            Arc::new(Semaphore::new(1)),
27239            None,
27240            &mut st,
27241        )
27242        .await;
27243        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27244        assert_eq!(results[0].1.turns, 0);
27245        assert!(FailClass::of(&results[0].2).is_none());
27246        assert_eq!(
27247            st.resource_block.as_ref().unwrap().kind,
27248            "repository coordination"
27249        );
27250        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27251        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27252        drop(external);
27253        let editor = crate::repo_lock::SeatLease::for_checkout(
27254            tmp.path(),
27255            true,
27256            crate::config::test_coordination().as_ref(),
27257        )
27258        .await
27259        .unwrap();
27260        let pause = Pause::new();
27261        let interrupt = Pause::new();
27262        let prompts = Prompts::default();
27263        let ctx = WaveCtx {
27264            run: "r",
27265            node: "review",
27266            prompts: &prompts,
27267            cache: None,
27268            round: None,
27269            carry_seats: false,
27270            pauses: Some((&pause, &interrupt)),
27271        };
27272        let (results, ()) = tokio::join!(
27273            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
27274            async {
27275                tokio::time::sleep(Duration::from_millis(50)).await;
27276                pause.park();
27277            }
27278        );
27279        assert!(
27280            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
27281        );
27282        assert_eq!(results[0].1.turns, 0);
27283        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27284        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27285        drop(editor);
27286    }
27287
27288    #[tokio::test]
27289    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
27290        crate::run::pin_test_home();
27291        let tmp = tempfile::tempdir().unwrap();
27292        let cache = tmp.path().join("target-b");
27293        let _held = hold(&cache);
27294        let mut st = state(1);
27295        let results = run(
27296            vec![job(
27297                sh("alpha", "echo ok"),
27298                tmp.path(),
27299                Duration::from_secs(1),
27300            )],
27301            Arc::new(Semaphore::new(1)),
27302            Some(&cache),
27303            &mut st,
27304        )
27305        .await;
27306        let (_, seat, out) = &results[0];
27307        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
27308        assert!(wave_blocked(&results));
27309        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
27310        assert_eq!(seat.turns, 0, "nothing was asked");
27311        assert!(
27312            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
27313            "no agent was spawned"
27314        );
27315        assert!(FailClass::of(out).is_none(), "not a failure class");
27316        let block = st.resource_block.as_ref().expect("recorded for the resume");
27317        assert_eq!(block.kind, "shared build cache");
27318        assert!(matches!(
27319            block.cause,
27320            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
27321        ));
27322        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27323        assert!(st.active.is_empty());
27324    }
27325
27326    #[tokio::test]
27327    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
27328        crate::run::pin_test_home();
27329        let tmp = tempfile::tempdir().unwrap();
27330        let mut st = state(1);
27331        let results = run(
27332            vec![job(
27333                sh("alpha", "echo ok"),
27334                tmp.path(),
27335                Duration::from_secs(1),
27336            )],
27337            Arc::new(Semaphore::new(0)),
27338            None,
27339            &mut st,
27340        )
27341        .await;
27342        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27343        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
27344        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
27345    }
27346
27347    #[tokio::test]
27348    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
27349        crate::run::pin_test_home();
27350        let tmp = tempfile::tempdir().unwrap();
27351        let mut st = state(60);
27352        let results = run(
27353            vec![job(
27354                sh("alpha", "sleep 30"),
27355                tmp.path(),
27356                Duration::from_secs(1),
27357            )],
27358            Arc::new(Semaphore::new(1)),
27359            None,
27360            &mut st,
27361        )
27362        .await;
27363        let out = &results[0].2;
27364        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
27365        let class = FailClass::of(out).expect("a failure");
27366        assert_eq!(class, FailClass::Timeout);
27367        assert!(should_hand_over(None, &class), "existing handover policy");
27368        assert!(st.resource_block.is_none());
27369    }
27370}
27371
27372/// A fold acts on the record it locked, and on nothing else.
27373#[cfg(test)]
27374mod fold_record_tests {
27375    use super::*;
27376
27377    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
27378        error.downcast_ref::<FoldRefusal>()
27379    }
27380
27381    /// A deletion that lands after the fold's look at the record and before its
27382    /// locks must neither be undone (the fold's lock files bring the directory
27383    /// back, its stale copy the record) nor be acted on.
27384    #[tokio::test]
27385    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
27386        let dir = tempfile::tempdir().unwrap();
27387        let home = dir.path();
27388        let repo = home.join("repo");
27389        std::fs::create_dir_all(&repo).unwrap();
27390        crate::clean::tests::init_repo(&repo);
27391        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
27392            &home.join("runs"),
27393            &home.join("wt"),
27394            &repo,
27395            "20260801-000000-y001",
27396            RunStatus::Superseded,
27397        )
27398        .await;
27399        let mut state = RunState::load_under(&id, home).unwrap();
27400        BEFORE_LOCKS.with(|hook| {
27401            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
27402                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
27403            }));
27404        });
27405
27406        let error = fold_run(&mut state, true, home).await.unwrap_err();
27407        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27408        assert!(
27409            !home.join("runs").join(&id).exists(),
27410            "the fold's own lock files must not bring a deleted run back"
27411        );
27412        assert!(worktree.exists(), "nothing of a deleted run is removed");
27413    }
27414
27415    /// The caller's `state` is only a first look: a record that was never
27416    /// saved is not a record the fold may write.
27417    #[tokio::test]
27418    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27419        let dir = tempfile::tempdir().unwrap();
27420        let home = dir.path();
27421        let mut state = RunState::new(
27422            home.join("repo"),
27423            "main".to_owned(),
27424            "abc".to_owned(),
27425            "fixture".to_owned(),
27426            crate::config::Config::default(),
27427        );
27428        state.status = RunStatus::Superseded;
27429        let error = fold_run(&mut state, true, home).await.unwrap_err();
27430        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27431        assert!(
27432            !home.join("runs").exists(),
27433            "nothing was created: {error:#}"
27434        );
27435    }
27436
27437    /// A refusal changes nothing. A directory whose record is another run's is
27438    /// not the run that was locked: every entry point answers `record gone`,
27439    /// the other run's worktree is left alone, the record stays as it was, and
27440    /// the lock files are not unlinked (an unlinked lock file lets the next
27441    /// caller lock a different inode - `pr_head::owner_lock`).
27442    #[tokio::test]
27443    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27444        let dir = tempfile::tempdir().unwrap();
27445        let home = dir.path();
27446        let repo = home.join("repo");
27447        std::fs::create_dir_all(&repo).unwrap();
27448        crate::clean::tests::init_repo(&repo);
27449        let runs = home.join("runs");
27450        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27451            &runs,
27452            &home.join("wt"),
27453            &repo,
27454            "20260801-000000-y101",
27455            RunStatus::Superseded,
27456        )
27457        .await;
27458        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27459            &runs,
27460            &home.join("wt"),
27461            &repo,
27462            "20260801-000000-y102",
27463            RunStatus::Superseded,
27464        )
27465        .await;
27466        let first_look = RunState::load_under(&id, home).unwrap();
27467        let record = runs.join(&id).join("run.json");
27468        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27469        let before = std::fs::read(&record).unwrap();
27470        for entry in ["fold_run", "fold_run_when", "override"] {
27471            let mut state = first_look.clone();
27472            let result = match entry {
27473                "fold_run" => fold_run(&mut state, true, home).await,
27474                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27475                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27476            };
27477            let error = result.unwrap_err();
27478            assert_eq!(
27479                refusal(&error),
27480                Some(&FoldRefusal::RecordGone),
27481                "{entry}: {error:#}"
27482            );
27483            assert!(own.exists() && theirs.exists(), "{entry}");
27484            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27485            for lock in ["pr-owner.lock", "driver.lock"] {
27486                assert!(
27487                    runs.join(&id).join(lock).exists(),
27488                    "{entry}: {lock} stays in place"
27489                );
27490            }
27491            assert!(
27492                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27493                "{entry}: the other run was not folded"
27494            );
27495        }
27496    }
27497
27498    /// The refusal is added to the error underneath, never substituted for it:
27499    /// callers match `ResourceBlocked` for a coordination wait.
27500    #[test]
27501    fn a_live_refusal_keeps_the_error_callers_match() {
27502        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27503            "repository coordination".into(),
27504        ));
27505        let error = live_or(blocked);
27506        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27507        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27508        // Anything that is not a held lock is passed through untouched.
27509        let other = live_or(anyhow::anyhow!("git exploded"));
27510        assert!(refusal(&other).is_none());
27511    }
27512
27513    /// Contention is `live`, a lock call that failed for another reason is a
27514    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27515    #[test]
27516    fn source_verification_failures_are_told_apart() {
27517        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27518            .context("Cargo build is active");
27519        let error = source_proof_failure(contended);
27520        assert!(
27521            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27522            "{error:#}"
27523        );
27524
27525        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27526            "Cargo lock target/debug/.cargo-lock".into(),
27527            std::io::Error::from(std::io::ErrorKind::Interrupted),
27528        ));
27529        let error = source_proof_failure(failed);
27530        assert!(refusal(&error).is_none(), "{error:#}");
27531        assert!(
27532            error
27533                .chain()
27534                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27535        );
27536
27537        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27538        assert!(matches!(
27539            refusal(&error),
27540            Some(FoldRefusal::ProofIncomplete(_))
27541        ));
27542    }
27543
27544    /// A run directory that is not there is `record gone` at the lock, not
27545    /// something to create for the lock's sake.
27546    #[test]
27547    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27548        let dir = tempfile::tempdir().unwrap();
27549        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27550            .map(drop)
27551            .map_err(lock_refusal)
27552            .unwrap_err();
27553        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27554        assert!(!dir.path().join("runs").exists());
27555    }
27556}